]> icculus.org git repositories - divverent/darkplaces.git/blob - model_brush.c
removed an unneeded CHECKGLERROR
[divverent/darkplaces.git] / model_brush.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24 #include "polygon.h"
25 #include "curves.h"
26 #include "wad.h"
27
28
29 qbyte mod_q1bsp_novis[(MAX_MAP_LEAFS + 7)/ 8];
30
31 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128"};
32 cvar_t halflifebsp = {0, "halflifebsp", "0"};
33 cvar_t r_novis = {0, "r_novis", "0"};
34 cvar_t r_miplightmaps = {CVAR_SAVE, "r_miplightmaps", "0"};
35 cvar_t r_lightmaprgba = {0, "r_lightmaprgba", "1"};
36 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0"};
37 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4"};
38 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "1"};
39 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024"};
40 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536"};
41 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15"};
42 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "1"};
43 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024"};
44 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225"};
45 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1"};
46 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1"};
47 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0"};
48
49 static void Mod_Q1BSP_Collision_Init (void);
50 void Mod_BrushInit(void)
51 {
52 //      Cvar_RegisterVariable(&r_subdivide_size);
53         Cvar_RegisterVariable(&halflifebsp);
54         Cvar_RegisterVariable(&r_novis);
55         Cvar_RegisterVariable(&r_miplightmaps);
56         Cvar_RegisterVariable(&r_lightmaprgba);
57         Cvar_RegisterVariable(&r_nosurftextures);
58         Cvar_RegisterVariable(&r_subdivisions_tolerance);
59         Cvar_RegisterVariable(&r_subdivisions_mintess);
60         Cvar_RegisterVariable(&r_subdivisions_maxtess);
61         Cvar_RegisterVariable(&r_subdivisions_maxvertices);
62         Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
63         Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
64         Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
65         Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
66         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
67         Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
68         Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
69         memset(mod_q1bsp_novis, 0xff, sizeof(mod_q1bsp_novis));
70         Mod_Q1BSP_Collision_Init();
71 }
72
73 static mleaf_t *Mod_Q1BSP_PointInLeaf(model_t *model, const vec3_t p)
74 {
75         mnode_t *node;
76
77         if (model == NULL)
78                 return NULL;
79
80         Mod_CheckLoaded(model);
81
82         // LordHavoc: modified to start at first clip node,
83         // in other words: first node of the (sub)model
84         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
85         while (node->plane)
86                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
87
88         return (mleaf_t *)node;
89 }
90
91 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(model_t *model, const vec3_t p, qbyte *out, int outsize)
92 {
93         int i;
94         mleaf_t *leaf;
95         leaf = Mod_Q1BSP_PointInLeaf(model, p);
96         if (leaf)
97         {
98                 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
99                 if (i)
100                 {
101                         memcpy(out, leaf->ambient_sound_level, i);
102                         out += i;
103                         outsize -= i;
104                 }
105         }
106         if (outsize)
107                 memset(out, 0, outsize);
108 }
109
110 static int Mod_Q1BSP_BoxTouchingPVS(model_t *model, const qbyte *pvs, const vec3_t mins, const vec3_t maxs)
111 {
112         int clusterindex, side, nodestackindex = 0;
113         mnode_t *node, *nodestack[1024];
114         if (!model->brush.num_pvsclusters)
115                 return true;
116         node = model->brush.data_nodes;
117         for (;;)
118         {
119                 if (node->plane)
120                 {
121                         // node - recurse down the BSP tree
122                         side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
123                         if (side < 2)
124                         {
125                                 // box is on one side of plane, take that path
126                                 node = node->children[side];
127                         }
128                         else
129                         {
130                                 // box crosses plane, take one path and remember the other
131                                 if (nodestackindex < 1024)
132                                         nodestack[nodestackindex++] = node->children[0];
133                                 node = node->children[1];
134                         }
135                 }
136                 else
137                 {
138                         // leaf - check cluster bit
139                         clusterindex = ((mleaf_t *)node)->clusterindex;
140                         if (CHECKPVSBIT(pvs, clusterindex))
141                         {
142                                 // it is visible, return immediately with the news
143                                 return true;
144                         }
145                         else
146                         {
147                                 // nothing to see here, try another path we didn't take earlier
148                                 if (nodestackindex == 0)
149                                         break;
150                                 node = nodestack[--nodestackindex];
151                         }
152                 }
153         }
154         // it is not visible
155         return false;
156 }
157
158 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(model_t *model, const qbyte *visibleleafs, const vec3_t mins, const vec3_t maxs)
159 {
160         int side, nodestackindex = 0;
161         mnode_t *node, *nodestack[1024];
162         node = model->brush.data_nodes;
163         for (;;)
164         {
165                 if (node->plane)
166                 {
167                         // node - recurse down the BSP tree
168                         side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
169                         if (side < 2)
170                         {
171                                 // box is on one side of plane, take that path
172                                 node = node->children[side];
173                         }
174                         else
175                         {
176                                 // box crosses plane, take one path and remember the other
177                                 if (nodestackindex < 1024)
178                                         nodestack[nodestackindex++] = node->children[0];
179                                 node = node->children[1];
180                         }
181                 }
182                 else
183                 {
184                         // leaf - check if it is visible
185                         if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
186                         {
187                                 // it is visible, return immediately with the news
188                                 return true;
189                         }
190                         else
191                         {
192                                 // nothing to see here, try another path we didn't take earlier
193                                 if (nodestackindex == 0)
194                                         break;
195                                 node = nodestack[--nodestackindex];
196                         }
197                 }
198         }
199         // it is not visible
200         return false;
201 }
202
203 typedef struct findnonsolidlocationinfo_s
204 {
205         vec3_t center;
206         vec_t radius;
207         vec3_t nudge;
208         vec_t bestdist;
209         model_t *model;
210 }
211 findnonsolidlocationinfo_t;
212
213 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
214 {
215         int i, surfacenum, k, *tri, *mark;
216         float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
217         msurface_t *surface;
218         for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
219         {
220                 surface = info->model->brush.data_surfaces + *mark;
221                 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
222                 {
223                         for (k = 0;k < surface->mesh.num_triangles;k++)
224                         {
225                                 tri = surface->mesh.data_element3i + k * 3;
226                                 VectorCopy((surface->mesh.data_vertex3f + tri[0] * 3), vert[0]);
227                                 VectorCopy((surface->mesh.data_vertex3f + tri[1] * 3), vert[1]);
228                                 VectorCopy((surface->mesh.data_vertex3f + tri[2] * 3), vert[2]);
229                                 VectorSubtract(vert[1], vert[0], edge[0]);
230                                 VectorSubtract(vert[2], vert[1], edge[1]);
231                                 CrossProduct(edge[1], edge[0], facenormal);
232                                 if (facenormal[0] || facenormal[1] || facenormal[2])
233                                 {
234                                         VectorNormalize(facenormal);
235                                         f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
236                                         if (f <= info->bestdist && f >= -info->bestdist)
237                                         {
238                                                 VectorSubtract(vert[0], vert[2], edge[2]);
239                                                 VectorNormalize(edge[0]);
240                                                 VectorNormalize(edge[1]);
241                                                 VectorNormalize(edge[2]);
242                                                 CrossProduct(facenormal, edge[0], edgenormal[0]);
243                                                 CrossProduct(facenormal, edge[1], edgenormal[1]);
244                                                 CrossProduct(facenormal, edge[2], edgenormal[2]);
245                                                 // face distance
246                                                 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
247                                                  && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
248                                                  && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
249                                                 {
250                                                         // we got lucky, the center is within the face
251                                                         dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
252                                                         if (dist < 0)
253                                                         {
254                                                                 dist = -dist;
255                                                                 if (info->bestdist > dist)
256                                                                 {
257                                                                         info->bestdist = dist;
258                                                                         VectorScale(facenormal, (info->radius - -dist), info->nudge);
259                                                                 }
260                                                         }
261                                                         else
262                                                         {
263                                                                 if (info->bestdist > dist)
264                                                                 {
265                                                                         info->bestdist = dist;
266                                                                         VectorScale(facenormal, (info->radius - dist), info->nudge);
267                                                                 }
268                                                         }
269                                                 }
270                                                 else
271                                                 {
272                                                         // check which edge or vertex the center is nearest
273                                                         for (i = 0;i < 3;i++)
274                                                         {
275                                                                 f = DotProduct(info->center, edge[i]);
276                                                                 if (f >= DotProduct(vert[0], edge[i])
277                                                                  && f <= DotProduct(vert[1], edge[i]))
278                                                                 {
279                                                                         // on edge
280                                                                         VectorMA(info->center, -f, edge[i], point);
281                                                                         dist = sqrt(DotProduct(point, point));
282                                                                         if (info->bestdist > dist)
283                                                                         {
284                                                                                 info->bestdist = dist;
285                                                                                 VectorScale(point, (info->radius / dist), info->nudge);
286                                                                         }
287                                                                         // skip both vertex checks
288                                                                         // (both are further away than this edge)
289                                                                         i++;
290                                                                 }
291                                                                 else
292                                                                 {
293                                                                         // not on edge, check first vertex of edge
294                                                                         VectorSubtract(info->center, vert[i], point);
295                                                                         dist = sqrt(DotProduct(point, point));
296                                                                         if (info->bestdist > dist)
297                                                                         {
298                                                                                 info->bestdist = dist;
299                                                                                 VectorScale(point, (info->radius / dist), info->nudge);
300                                                                         }
301                                                                 }
302                                                         }
303                                                 }
304                                         }
305                                 }
306                         }
307                 }
308         }
309 }
310
311 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
312 {
313         if (node->plane)
314         {
315                 float f = PlaneDiff(info->center, node->plane);
316                 if (f >= -info->bestdist)
317                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
318                 if (f <= info->bestdist)
319                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
320         }
321         else
322         {
323                 if (((mleaf_t *)node)->numleafsurfaces)
324                         Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
325         }
326 }
327
328 static void Mod_Q1BSP_FindNonSolidLocation(model_t *model, const vec3_t in, vec3_t out, float radius)
329 {
330         int i;
331         findnonsolidlocationinfo_t info;
332         if (model == NULL)
333         {
334                 VectorCopy(in, out);
335                 return;
336         }
337         VectorCopy(in, info.center);
338         info.radius = radius;
339         info.model = model;
340         i = 0;
341         do
342         {
343                 VectorClear(info.nudge);
344                 info.bestdist = radius;
345                 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
346                 VectorAdd(info.center, info.nudge, info.center);
347         }
348         while (info.bestdist < radius && ++i < 10);
349         VectorCopy(info.center, out);
350 }
351
352 int Mod_Q1BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents)
353 {
354         switch(nativecontents)
355         {
356                 case CONTENTS_EMPTY:
357                         return 0;
358                 case CONTENTS_SOLID:
359                         return SUPERCONTENTS_SOLID;
360                 case CONTENTS_WATER:
361                         return SUPERCONTENTS_WATER;
362                 case CONTENTS_SLIME:
363                         return SUPERCONTENTS_SLIME;
364                 case CONTENTS_LAVA:
365                         return SUPERCONTENTS_LAVA;
366                 case CONTENTS_SKY:
367                         return SUPERCONTENTS_SKY;
368         }
369         return 0;
370 }
371
372 int Mod_Q1BSP_NativeContentsFromSuperContents(model_t *model, int supercontents)
373 {
374         if (supercontents & SUPERCONTENTS_SOLID)
375                 return CONTENTS_SOLID;
376         if (supercontents & SUPERCONTENTS_SKY)
377                 return CONTENTS_SKY;
378         if (supercontents & SUPERCONTENTS_LAVA)
379                 return CONTENTS_LAVA;
380         if (supercontents & SUPERCONTENTS_SLIME)
381                 return CONTENTS_SLIME;
382         if (supercontents & SUPERCONTENTS_WATER)
383                 return CONTENTS_WATER;
384         return CONTENTS_EMPTY;
385 }
386
387 typedef struct
388 {
389         // the hull we're tracing through
390         const hull_t *hull;
391
392         // the trace structure to fill in
393         trace_t *trace;
394
395         // start, end, and end - start (in model space)
396         double start[3];
397         double end[3];
398         double dist[3];
399 }
400 RecursiveHullCheckTraceInfo_t;
401
402 // 1/32 epsilon to keep floating point happy
403 #define DIST_EPSILON (0.03125)
404
405 #define HULLCHECKSTATE_EMPTY 0
406 #define HULLCHECKSTATE_SOLID 1
407 #define HULLCHECKSTATE_DONE 2
408
409 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
410 {
411         // status variables, these don't need to be saved on the stack when
412         // recursing...  but are because this should be thread-safe
413         // (note: tracing against a bbox is not thread-safe, yet)
414         int ret;
415         mplane_t *plane;
416         double t1, t2;
417
418         // variables that need to be stored on the stack when recursing
419         dclipnode_t *node;
420         int side;
421         double midf, mid[3];
422
423         // LordHavoc: a goto!  everyone flee in terror... :)
424 loc0:
425         // check for empty
426         if (num < 0)
427         {
428                 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
429                 if (!t->trace->startfound)
430                 {
431                         t->trace->startfound = true;
432                         t->trace->startsupercontents |= num;
433                 }
434                 if (num & SUPERCONTENTS_LIQUIDSMASK)
435                         t->trace->inwater = true;
436                 if (num == 0)
437                         t->trace->inopen = true;
438                 if (num & t->trace->hitsupercontentsmask)
439                 {
440                         // if the first leaf is solid, set startsolid
441                         if (t->trace->allsolid)
442                                 t->trace->startsolid = true;
443 #if COLLISIONPARANOID >= 3
444                         Con_Print("S");
445 #endif
446                         return HULLCHECKSTATE_SOLID;
447                 }
448                 else
449                 {
450                         t->trace->allsolid = false;
451 #if COLLISIONPARANOID >= 3
452                         Con_Print("E");
453 #endif
454                         return HULLCHECKSTATE_EMPTY;
455                 }
456         }
457
458         // find the point distances
459         node = t->hull->clipnodes + num;
460
461         plane = t->hull->planes + node->planenum;
462         if (plane->type < 3)
463         {
464                 t1 = p1[plane->type] - plane->dist;
465                 t2 = p2[plane->type] - plane->dist;
466         }
467         else
468         {
469                 t1 = DotProduct (plane->normal, p1) - plane->dist;
470                 t2 = DotProduct (plane->normal, p2) - plane->dist;
471         }
472
473         if (t1 < 0)
474         {
475                 if (t2 < 0)
476                 {
477 #if COLLISIONPARANOID >= 3
478                         Con_Print("<");
479 #endif
480                         num = node->children[1];
481                         goto loc0;
482                 }
483                 side = 1;
484         }
485         else
486         {
487                 if (t2 >= 0)
488                 {
489 #if COLLISIONPARANOID >= 3
490                         Con_Print(">");
491 #endif
492                         num = node->children[0];
493                         goto loc0;
494                 }
495                 side = 0;
496         }
497
498         // the line intersects, find intersection point
499         // LordHavoc: this uses the original trace for maximum accuracy
500 #if COLLISIONPARANOID >= 3
501         Con_Print("M");
502 #endif
503         if (plane->type < 3)
504         {
505                 t1 = t->start[plane->type] - plane->dist;
506                 t2 = t->end[plane->type] - plane->dist;
507         }
508         else
509         {
510                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
511                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
512         }
513
514         midf = t1 / (t1 - t2);
515         midf = bound(p1f, midf, p2f);
516         VectorMA(t->start, midf, t->dist, mid);
517
518         // recurse both sides, front side first
519         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
520         // if this side is not empty, return what it is (solid or done)
521         if (ret != HULLCHECKSTATE_EMPTY)
522                 return ret;
523
524         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
525         // if other side is not solid, return what it is (empty or done)
526         if (ret != HULLCHECKSTATE_SOLID)
527                 return ret;
528
529         // front is air and back is solid, this is the impact point...
530         if (side)
531         {
532                 t->trace->plane.dist = -plane->dist;
533                 VectorNegate (plane->normal, t->trace->plane.normal);
534         }
535         else
536         {
537                 t->trace->plane.dist = plane->dist;
538                 VectorCopy (plane->normal, t->trace->plane.normal);
539         }
540
541         // calculate the true fraction
542         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
543         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
544         midf = t1 / (t1 - t2);
545         t->trace->realfraction = bound(0, midf, 1);
546
547         // calculate the return fraction which is nudged off the surface a bit
548         midf = (t1 - DIST_EPSILON) / (t1 - t2);
549         t->trace->fraction = bound(0, midf, 1);
550
551 #if COLLISIONPARANOID >= 3
552         Con_Print("D");
553 #endif
554         return HULLCHECKSTATE_DONE;
555 }
556
557 #if COLLISIONPARANOID < 2
558 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
559 {
560         while (num >= 0)
561                 num = t->hull->clipnodes[num].children[(t->hull->planes[t->hull->clipnodes[num].planenum].type < 3 ? t->start[t->hull->planes[t->hull->clipnodes[num].planenum].type] : DotProduct(t->hull->planes[t->hull->clipnodes[num].planenum].normal, t->start)) < t->hull->planes[t->hull->clipnodes[num].planenum].dist];
562         num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
563         t->trace->startsupercontents |= num;
564         if (num & SUPERCONTENTS_LIQUIDSMASK)
565                 t->trace->inwater = true;
566         if (num == 0)
567                 t->trace->inopen = true;
568         if (num & t->trace->hitsupercontentsmask)
569         {
570                 t->trace->allsolid = t->trace->startsolid = true;
571                 return HULLCHECKSTATE_SOLID;
572         }
573         else
574         {
575                 t->trace->allsolid = t->trace->startsolid = false;
576                 return HULLCHECKSTATE_EMPTY;
577         }
578 }
579 #endif
580
581 static void Mod_Q1BSP_TraceBox(struct model_s *model, int frame, trace_t *trace, const vec3_t boxstartmins, const vec3_t boxstartmaxs, const vec3_t boxendmins, const vec3_t boxendmaxs, int hitsupercontentsmask)
582 {
583         // this function currently only supports same size start and end
584         double boxsize[3];
585         RecursiveHullCheckTraceInfo_t rhc;
586
587         memset(&rhc, 0, sizeof(rhc));
588         memset(trace, 0, sizeof(trace_t));
589         rhc.trace = trace;
590         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
591         rhc.trace->fraction = 1;
592         rhc.trace->realfraction = 1;
593         rhc.trace->allsolid = true;
594         VectorSubtract(boxstartmaxs, boxstartmins, boxsize);
595         if (boxsize[0] < 3)
596                 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
597         else if (model->brush.ishlbsp)
598         {
599                 // LordHavoc: this has to have a minor tolerance (the .1) because of
600                 // minor float precision errors from the box being transformed around
601                 if (boxsize[0] < 32.1)
602                 {
603                         if (boxsize[2] < 54) // pick the nearest of 36 or 72
604                                 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
605                         else
606                                 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
607                 }
608                 else
609                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
610         }
611         else
612         {
613                 // LordHavoc: this has to have a minor tolerance (the .1) because of
614                 // minor float precision errors from the box being transformed around
615                 if (boxsize[0] < 32.1)
616                         rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
617                 else
618                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
619         }
620         VectorSubtract(boxstartmins, rhc.hull->clip_mins, rhc.start);
621         VectorSubtract(boxendmins, rhc.hull->clip_mins, rhc.end);
622         VectorSubtract(rhc.end, rhc.start, rhc.dist);
623 #if COLLISIONPARANOID >= 2
624         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]);
625         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
626         Con_Print("\n");
627 #else
628         if (DotProduct(rhc.dist, rhc.dist))
629                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
630         else
631                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
632 #endif
633 }
634
635 static hull_t box_hull;
636 static dclipnode_t box_clipnodes[6];
637 static mplane_t box_planes[6];
638
639 static void Mod_Q1BSP_Collision_Init (void)
640 {
641         int             i;
642         int             side;
643
644         //Set up the planes and clipnodes so that the six floats of a bounding box
645         //can just be stored out and get a proper hull_t structure.
646
647         box_hull.clipnodes = box_clipnodes;
648         box_hull.planes = box_planes;
649         box_hull.firstclipnode = 0;
650         box_hull.lastclipnode = 5;
651
652         for (i = 0;i < 6;i++)
653         {
654                 box_clipnodes[i].planenum = i;
655
656                 side = i&1;
657
658                 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
659                 if (i != 5)
660                         box_clipnodes[i].children[side^1] = i + 1;
661                 else
662                         box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
663
664                 box_planes[i].type = i>>1;
665                 box_planes[i].normal[i>>1] = 1;
666         }
667 }
668
669 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)
670 {
671 #if 1
672         colbrushf_t cbox;
673         colplanef_t cbox_planes[6];
674         cbox.supercontents = boxsupercontents;
675         cbox.numplanes = 6;
676         cbox.numpoints = 0;
677         cbox.numtriangles = 0;
678         cbox.planes = cbox_planes;
679         cbox.points = NULL;
680         cbox.elements = NULL;
681         cbox.markframe = 0;
682         cbox.mins[0] = 0;
683         cbox.mins[1] = 0;
684         cbox.mins[2] = 0;
685         cbox.maxs[0] = 0;
686         cbox.maxs[1] = 0;
687         cbox.maxs[2] = 0;
688         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];
689         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];
690         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];
691         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];
692         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];
693         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];
694         memset(trace, 0, sizeof(trace_t));
695         trace->hitsupercontentsmask = hitsupercontentsmask;
696         trace->fraction = 1;
697         trace->realfraction = 1;
698         Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
699 #else
700         RecursiveHullCheckTraceInfo_t rhc;
701         // fill in a default trace
702         memset(&rhc, 0, sizeof(rhc));
703         memset(trace, 0, sizeof(trace_t));
704         //To keep everything totally uniform, bounding boxes are turned into small
705         //BSP trees instead of being compared directly.
706         // create a temp hull from bounding box sizes
707         box_planes[0].dist = cmaxs[0] - mins[0];
708         box_planes[1].dist = cmins[0] - maxs[0];
709         box_planes[2].dist = cmaxs[1] - mins[1];
710         box_planes[3].dist = cmins[1] - maxs[1];
711         box_planes[4].dist = cmaxs[2] - mins[2];
712         box_planes[5].dist = cmins[2] - maxs[2];
713 #if COLLISIONPARANOID >= 3
714         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]);
715 #endif
716         // trace a line through the generated clipping hull
717         //rhc.boxsupercontents = boxsupercontents;
718         rhc.hull = &box_hull;
719         rhc.trace = trace;
720         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
721         rhc.trace->fraction = 1;
722         rhc.trace->realfraction = 1;
723         rhc.trace->allsolid = true;
724         VectorCopy(start, rhc.start);
725         VectorCopy(end, rhc.end);
726         VectorSubtract(rhc.end, rhc.start, rhc.dist);
727         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
728         //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
729         if (rhc.trace->startsupercontents)
730                 rhc.trace->startsupercontents = boxsupercontents;
731 #endif
732 }
733
734 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
735 {
736         int side, distz = endz - startz;
737         float front, back;
738         float mid;
739
740 loc0:
741         if (!node->plane)
742                 return false;           // didn't hit anything
743
744         switch (node->plane->type)
745         {
746         case PLANE_X:
747                 node = node->children[x < node->plane->dist];
748                 goto loc0;
749         case PLANE_Y:
750                 node = node->children[y < node->plane->dist];
751                 goto loc0;
752         case PLANE_Z:
753                 side = startz < node->plane->dist;
754                 if ((endz < node->plane->dist) == side)
755                 {
756                         node = node->children[side];
757                         goto loc0;
758                 }
759                 // found an intersection
760                 mid = node->plane->dist;
761                 break;
762         default:
763                 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
764                 front += startz * node->plane->normal[2];
765                 back += endz * node->plane->normal[2];
766                 side = front < node->plane->dist;
767                 if ((back < node->plane->dist) == side)
768                 {
769                         node = node->children[side];
770                         goto loc0;
771                 }
772                 // found an intersection
773                 mid = startz + distz * (front - node->plane->dist) / (front - back);
774                 break;
775         }
776
777         // go down front side
778         if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
779                 return true;    // hit something
780         else
781         {
782                 // check for impact on this node
783                 if (node->numsurfaces)
784                 {
785                         int i, ds, dt;
786                         msurface_t *surface;
787
788                         surface = r_refdef.worldmodel->brush.data_surfaces + node->firstsurface;
789                         for (i = 0;i < node->numsurfaces;i++, surface++)
790                         {
791                                 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->samples)
792                                         continue;       // no lightmaps
793
794                                 ds = (int) (x * surface->texinfo->vecs[0][0] + y * surface->texinfo->vecs[0][1] + mid * surface->texinfo->vecs[0][2] + surface->texinfo->vecs[0][3]) - surface->texturemins[0];
795                                 dt = (int) (x * surface->texinfo->vecs[1][0] + y * surface->texinfo->vecs[1][1] + mid * surface->texinfo->vecs[1][2] + surface->texinfo->vecs[1][3]) - surface->texturemins[1];
796
797                                 if (ds >= 0 && ds < surface->extents[0] && dt >= 0 && dt < surface->extents[1])
798                                 {
799                                         qbyte *lightmap;
800                                         int lmwidth, lmheight, maps, line3, size3, dsfrac = ds & 15, dtfrac = dt & 15, scale = 0, r00 = 0, g00 = 0, b00 = 0, r01 = 0, g01 = 0, b01 = 0, r10 = 0, g10 = 0, b10 = 0, r11 = 0, g11 = 0, b11 = 0;
801                                         lmwidth = ((surface->extents[0]>>4)+1);
802                                         lmheight = ((surface->extents[1]>>4)+1);
803                                         line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
804                                         size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
805
806                                         lightmap = surface->samples + ((dt>>4) * lmwidth + (ds>>4))*3; // LordHavoc: *3 for colored lighting
807
808                                         for (maps = 0;maps < MAXLIGHTMAPS && surface->styles[maps] != 255;maps++)
809                                         {
810                                                 scale = d_lightstylevalue[surface->styles[maps]];
811                                                 r00 += lightmap[      0] * scale;g00 += lightmap[      1] * scale;b00 += lightmap[      2] * scale;
812                                                 r01 += lightmap[      3] * scale;g01 += lightmap[      4] * scale;b01 += lightmap[      5] * scale;
813                                                 r10 += lightmap[line3+0] * scale;g10 += lightmap[line3+1] * scale;b10 += lightmap[line3+2] * scale;
814                                                 r11 += lightmap[line3+3] * scale;g11 += lightmap[line3+4] * scale;b11 += lightmap[line3+5] * scale;
815                                                 lightmap += size3;
816                                         }
817
818 /*
819 LordHavoc: here's the readable version of the interpolation
820 code, not quite as easy for the compiler to optimize...
821
822 dsfrac is the X position in the lightmap pixel, * 16
823 dtfrac is the Y position in the lightmap pixel, * 16
824 r00 is top left corner, r01 is top right corner
825 r10 is bottom left corner, r11 is bottom right corner
826 g and b are the same layout.
827 r0 and r1 are the top and bottom intermediate results
828
829 first we interpolate the top two points, to get the top
830 edge sample
831
832         r0 = (((r01-r00) * dsfrac) >> 4) + r00;
833         g0 = (((g01-g00) * dsfrac) >> 4) + g00;
834         b0 = (((b01-b00) * dsfrac) >> 4) + b00;
835
836 then we interpolate the bottom two points, to get the
837 bottom edge sample
838
839         r1 = (((r11-r10) * dsfrac) >> 4) + r10;
840         g1 = (((g11-g10) * dsfrac) >> 4) + g10;
841         b1 = (((b11-b10) * dsfrac) >> 4) + b10;
842
843 then we interpolate the top and bottom samples to get the
844 middle sample (the one which was requested)
845
846         r = (((r1-r0) * dtfrac) >> 4) + r0;
847         g = (((g1-g0) * dtfrac) >> 4) + g0;
848         b = (((b1-b0) * dtfrac) >> 4) + b0;
849 */
850
851                                         ambientcolor[0] += (float) ((((((((r11-r10) * dsfrac) >> 4) + r10)-((((r01-r00) * dsfrac) >> 4) + r00)) * dtfrac) >> 4) + ((((r01-r00) * dsfrac) >> 4) + r00)) * (1.0f / 32768.0f);
852                                         ambientcolor[1] += (float) ((((((((g11-g10) * dsfrac) >> 4) + g10)-((((g01-g00) * dsfrac) >> 4) + g00)) * dtfrac) >> 4) + ((((g01-g00) * dsfrac) >> 4) + g00)) * (1.0f / 32768.0f);
853                                         ambientcolor[2] += (float) ((((((((b11-b10) * dsfrac) >> 4) + b10)-((((b01-b00) * dsfrac) >> 4) + b00)) * dtfrac) >> 4) + ((((b01-b00) * dsfrac) >> 4) + b00)) * (1.0f / 32768.0f);
854                                         return true; // success
855                                 }
856                         }
857                 }
858
859                 // go down back side
860                 node = node->children[side ^ 1];
861                 startz = mid;
862                 distz = endz - startz;
863                 goto loc0;
864         }
865 }
866
867 void Mod_Q1BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
868 {
869         Mod_Q1BSP_LightPoint_RecursiveBSPNode(ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2], p[2] - 65536);
870 }
871
872 static void Mod_Q1BSP_DecompressVis(const qbyte *in, const qbyte *inend, qbyte *out, qbyte *outend)
873 {
874         int c;
875         qbyte *outstart = out;
876         while (out < outend)
877         {
878                 if (in == inend)
879                 {
880                         Con_Printf("Mod_Q1BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
881                         return;
882                 }
883                 c = *in++;
884                 if (c)
885                         *out++ = c;
886                 else
887                 {
888                         if (in == inend)
889                         {
890                                 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun (during zero-run) on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
891                                 return;
892                         }
893                         for (c = *in++;c > 0;c--)
894                         {
895                                 if (out == outend)
896                                 {
897                                         Con_Printf("Mod_Q1BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
898                                         return;
899                                 }
900                                 *out++ = 0;
901                         }
902                 }
903         }
904 }
905
906 /*
907 =============
908 R_Q1BSP_LoadSplitSky
909
910 A sky texture is 256*128, with the right side being a masked overlay
911 ==============
912 */
913 void R_Q1BSP_LoadSplitSky (qbyte *src, int width, int height, int bytesperpixel)
914 {
915         int i, j;
916         unsigned solidpixels[128*128], alphapixels[128*128];
917
918         // if sky isn't the right size, just use it as a solid layer
919         if (width != 256 || height != 128)
920         {
921                 loadmodel->brush.solidskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_solidtexture", width, height, src, bytesperpixel == 4 ? TEXTYPE_RGBA : TEXTYPE_PALETTE, TEXF_PRECACHE, bytesperpixel == 1 ? palette_complete : NULL);
922                 loadmodel->brush.alphaskytexture = NULL;;
923                 return;
924         }
925
926         if (bytesperpixel == 4)
927         {
928                 for (i = 0;i < 128;i++)
929                 {
930                         for (j = 0;j < 128;j++)
931                         {
932                                 solidpixels[(i*128) + j] = ((unsigned *)src)[i*256+j+128];
933                                 alphapixels[(i*128) + j] = ((unsigned *)src)[i*256+j];
934                         }
935                 }
936         }
937         else
938         {
939                 // make an average value for the back to avoid
940                 // a fringe on the top level
941                 int p, r, g, b;
942                 union
943                 {
944                         unsigned int i;
945                         unsigned char b[4];
946                 }
947                 rgba;
948                 r = g = b = 0;
949                 for (i = 0;i < 128;i++)
950                 {
951                         for (j = 0;j < 128;j++)
952                         {
953                                 rgba.i = palette_complete[src[i*256 + j + 128]];
954                                 r += rgba.b[0];
955                                 g += rgba.b[1];
956                                 b += rgba.b[2];
957                         }
958                 }
959                 rgba.b[0] = r/(128*128);
960                 rgba.b[1] = g/(128*128);
961                 rgba.b[2] = b/(128*128);
962                 rgba.b[3] = 0;
963                 for (i = 0;i < 128;i++)
964                 {
965                         for (j = 0;j < 128;j++)
966                         {
967                                 solidpixels[(i*128) + j] = palette_complete[src[i*256 + j + 128]];
968                                 alphapixels[(i*128) + j] = (p = src[i*256 + j]) ? palette_complete[p] : rgba.i;
969                         }
970                 }
971         }
972
973         loadmodel->brush.solidskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_solidtexture", 128, 128, (qbyte *) solidpixels, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
974         loadmodel->brush.alphaskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_alphatexture", 128, 128, (qbyte *) alphapixels, TEXTYPE_RGBA, TEXF_ALPHA | TEXF_PRECACHE, NULL);
975 }
976
977 static void Mod_Q1BSP_LoadTextures(lump_t *l)
978 {
979         int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
980         miptex_t *dmiptex;
981         texture_t *tx, *tx2, *anims[10], *altanims[10];
982         dmiptexlump_t *m;
983         qbyte *data, *mtdata;
984         char name[256];
985
986         loadmodel->brush.data_textures = NULL;
987
988         // add two slots for notexture walls and notexture liquids
989         if (l->filelen)
990         {
991                 m = (dmiptexlump_t *)(mod_base + l->fileofs);
992                 m->nummiptex = LittleLong (m->nummiptex);
993                 loadmodel->brush.num_textures = m->nummiptex + 2;
994         }
995         else
996         {
997                 m = NULL;
998                 loadmodel->brush.num_textures = 2;
999         }
1000
1001         loadmodel->brush.data_textures = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_textures * sizeof(texture_t));
1002
1003         // fill out all slots with notexture
1004         for (i = 0, tx = loadmodel->brush.data_textures;i < loadmodel->brush.num_textures;i++, tx++)
1005         {
1006                 strcpy(tx->name, "NO TEXTURE FOUND");
1007                 tx->width = 16;
1008                 tx->height = 16;
1009                 tx->skin.base = r_texture_notexture;
1010                 if (i == loadmodel->brush.num_textures - 1)
1011                 {
1012                         tx->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES;
1013                         tx->supercontents = SUPERCONTENTS_WATER;
1014                 }
1015                 else
1016                 {
1017                         tx->basematerialflags |= MATERIALFLAG_WALL;
1018                         tx->supercontents = SUPERCONTENTS_SOLID;
1019                 }
1020                 tx->basematerialflags = 0;
1021                 tx->currentframe = tx;
1022         }
1023
1024         if (!m)
1025                 return;
1026
1027         // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1028         dofs = m->dataofs;
1029         // LordHavoc: mostly rewritten map texture loader
1030         for (i = 0;i < m->nummiptex;i++)
1031         {
1032                 dofs[i] = LittleLong(dofs[i]);
1033                 if (dofs[i] == -1 || r_nosurftextures.integer)
1034                         continue;
1035                 dmiptex = (miptex_t *)((qbyte *)m + dofs[i]);
1036
1037                 // make sure name is no more than 15 characters
1038                 for (j = 0;dmiptex->name[j] && j < 15;j++)
1039                         name[j] = dmiptex->name[j];
1040                 name[j] = 0;
1041
1042                 mtwidth = LittleLong(dmiptex->width);
1043                 mtheight = LittleLong(dmiptex->height);
1044                 mtdata = NULL;
1045                 j = LittleLong(dmiptex->offsets[0]);
1046                 if (j)
1047                 {
1048                         // texture included
1049                         if (j < 40 || j + mtwidth * mtheight > l->filelen)
1050                         {
1051                                 Con_Printf("Texture \"%s\" in \"%s\"is corrupt or incomplete\n", dmiptex->name, loadmodel->name);
1052                                 continue;
1053                         }
1054                         mtdata = (qbyte *)dmiptex + j;
1055                 }
1056
1057                 if ((mtwidth & 15) || (mtheight & 15))
1058                         Con_Printf("warning: texture \"%s\" in \"%s\" is not 16 aligned\n", dmiptex->name, loadmodel->name);
1059
1060                 // LordHavoc: force all names to lowercase
1061                 for (j = 0;name[j];j++)
1062                         if (name[j] >= 'A' && name[j] <= 'Z')
1063                                 name[j] += 'a' - 'A';
1064
1065                 tx = loadmodel->brush.data_textures + i;
1066                 strcpy(tx->name, name);
1067                 tx->width = mtwidth;
1068                 tx->height = mtheight;
1069
1070                 if (!tx->name[0])
1071                 {
1072                         sprintf(tx->name, "unnamed%i", i);
1073                         Con_Printf("warning: unnamed texture in %s, renaming to %s\n", loadmodel->name, tx->name);
1074                 }
1075
1076                 // LordHavoc: HL sky textures are entirely different than quake
1077                 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == 256 && mtheight == 128)
1078                 {
1079                         if (loadmodel->isworldmodel)
1080                         {
1081                                 data = loadimagepixels(tx->name, false, 0, 0);
1082                                 if (data)
1083                                 {
1084                                         R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1085                                         Mem_Free(data);
1086                                 }
1087                                 else if (mtdata != NULL)
1088                                         R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1089                         }
1090                 }
1091                 else
1092                 {
1093                         if (!Mod_LoadSkinFrame(&tx->skin, tx->name, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, false, tx->name[0] != '*', true))
1094                         {
1095                                 // did not find external texture, load it from the bsp or wad3
1096                                 if (loadmodel->brush.ishlbsp)
1097                                 {
1098                                         // internal texture overrides wad
1099                                         qbyte *pixels, *freepixels, *fogpixels;
1100                                         pixels = freepixels = NULL;
1101                                         if (mtdata)
1102                                                 pixels = W_ConvertWAD3Texture(dmiptex);
1103                                         if (pixels == NULL)
1104                                                 pixels = freepixels = W_GetTexture(tx->name);
1105                                         if (pixels != NULL)
1106                                         {
1107                                                 tx->width = image_width;
1108                                                 tx->height = image_height;
1109                                                 tx->skin.base = tx->skin.merged = R_LoadTexture2D(loadmodel->texturepool, tx->name, image_width, image_height, pixels, TEXTYPE_RGBA, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, NULL);
1110                                                 if (Image_CheckAlpha(pixels, image_width * image_height, true))
1111                                                 {
1112                                                         fogpixels = Mem_Alloc(tempmempool, image_width * image_height * 4);
1113                                                         for (j = 0;j < image_width * image_height * 4;j += 4)
1114                                                         {
1115                                                                 fogpixels[j + 0] = 255;
1116                                                                 fogpixels[j + 1] = 255;
1117                                                                 fogpixels[j + 2] = 255;
1118                                                                 fogpixels[j + 3] = pixels[j + 3];
1119                                                         }
1120                                                         tx->skin.fog = R_LoadTexture2D(loadmodel->texturepool, tx->name, image_width, image_height, pixels, TEXTYPE_RGBA, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, NULL);
1121                                                         Mem_Free(fogpixels);
1122                                                 }
1123                                         }
1124                                         if (freepixels)
1125                                                 Mem_Free(freepixels);
1126                                 }
1127                                 else if (mtdata) // texture included
1128                                         Mod_LoadSkinFrame_Internal(&tx->skin, tx->name, TEXF_MIPMAP | TEXF_PRECACHE | TEXF_PICMIP, false, tx->name[0] != '*', tx->name[0] != '*' && r_fullbrights.integer, mtdata, tx->width, tx->height);
1129                         }
1130                 }
1131                 if (tx->skin.base == NULL)
1132                 {
1133                         // no texture found
1134                         tx->width = 16;
1135                         tx->height = 16;
1136                         tx->skin.base = r_texture_notexture;
1137                 }
1138
1139                 tx->basematerialflags = 0;
1140                 if (tx->name[0] == '*')
1141                 {
1142                         // turb does not block movement
1143                         tx->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES;
1144                         // LordHavoc: some turbulent textures should be fullbright and solid
1145                         if (!strncmp(tx->name,"*lava",5)
1146                          || !strncmp(tx->name,"*teleport",9)
1147                          || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1148                                 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
1149                         else
1150                                 tx->basematerialflags |= MATERIALFLAG_WATERALPHA;
1151                         if (!strncmp(tx->name, "*lava", 5))
1152                                 tx->supercontents = SUPERCONTENTS_LAVA;
1153                         else if (!strncmp(tx->name, "*slime", 6))
1154                                 tx->supercontents = SUPERCONTENTS_SLIME;
1155                         else
1156                                 tx->supercontents = SUPERCONTENTS_WATER;
1157                 }
1158                 else if (tx->name[0] == 's' && tx->name[1] == 'k' && tx->name[2] == 'y')
1159                 {
1160                         tx->supercontents = SUPERCONTENTS_SKY;
1161                         tx->basematerialflags |= MATERIALFLAG_SKY;
1162                 }
1163                 else
1164                 {
1165                         tx->supercontents = SUPERCONTENTS_SOLID;
1166                         tx->basematerialflags |= MATERIALFLAG_WALL;
1167                 }
1168                 if (tx->skin.fog)
1169                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
1170
1171                 // start out with no animation
1172                 tx->currentframe = tx;
1173         }
1174
1175         // sequence the animations
1176         for (i = 0;i < m->nummiptex;i++)
1177         {
1178                 tx = loadmodel->brush.data_textures + i;
1179                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1180                         continue;
1181                 if (tx->anim_total[0] || tx->anim_total[1])
1182                         continue;       // already sequenced
1183
1184                 // find the number of frames in the animation
1185                 memset(anims, 0, sizeof(anims));
1186                 memset(altanims, 0, sizeof(altanims));
1187
1188                 for (j = i;j < m->nummiptex;j++)
1189                 {
1190                         tx2 = loadmodel->brush.data_textures + j;
1191                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1192                                 continue;
1193
1194                         num = tx2->name[1];
1195                         if (num >= '0' && num <= '9')
1196                                 anims[num - '0'] = tx2;
1197                         else if (num >= 'a' && num <= 'j')
1198                                 altanims[num - 'a'] = tx2;
1199                         else
1200                                 Con_Printf("Bad animating texture %s\n", tx->name);
1201                 }
1202
1203                 max = altmax = 0;
1204                 for (j = 0;j < 10;j++)
1205                 {
1206                         if (anims[j])
1207                                 max = j + 1;
1208                         if (altanims[j])
1209                                 altmax = j + 1;
1210                 }
1211                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1212
1213                 incomplete = false;
1214                 for (j = 0;j < max;j++)
1215                 {
1216                         if (!anims[j])
1217                         {
1218                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1219                                 incomplete = true;
1220                         }
1221                 }
1222                 for (j = 0;j < altmax;j++)
1223                 {
1224                         if (!altanims[j])
1225                         {
1226                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1227                                 incomplete = true;
1228                         }
1229                 }
1230                 if (incomplete)
1231                         continue;
1232
1233                 if (altmax < 1)
1234                 {
1235                         // if there is no alternate animation, duplicate the primary
1236                         // animation into the alternate
1237                         altmax = max;
1238                         for (k = 0;k < 10;k++)
1239                                 altanims[k] = anims[k];
1240                 }
1241
1242                 // link together the primary animation
1243                 for (j = 0;j < max;j++)
1244                 {
1245                         tx2 = anims[j];
1246                         tx2->animated = true;
1247                         tx2->anim_total[0] = max;
1248                         tx2->anim_total[1] = altmax;
1249                         for (k = 0;k < 10;k++)
1250                         {
1251                                 tx2->anim_frames[0][k] = anims[k];
1252                                 tx2->anim_frames[1][k] = altanims[k];
1253                         }
1254                 }
1255
1256                 // if there really is an alternate anim...
1257                 if (anims[0] != altanims[0])
1258                 {
1259                         // link together the alternate animation
1260                         for (j = 0;j < altmax;j++)
1261                         {
1262                                 tx2 = altanims[j];
1263                                 tx2->animated = true;
1264                                 // the primary/alternate are reversed here
1265                                 tx2->anim_total[0] = altmax;
1266                                 tx2->anim_total[1] = max;
1267                                 for (k = 0;k < 10;k++)
1268                                 {
1269                                         tx2->anim_frames[0][k] = altanims[k];
1270                                         tx2->anim_frames[1][k] = anims[k];
1271                                 }
1272                         }
1273                 }
1274         }
1275 }
1276
1277 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1278 {
1279         int i;
1280         qbyte *in, *out, *data, d;
1281         char litfilename[1024];
1282         loadmodel->brushq1.lightdata = NULL;
1283         if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1284         {
1285                 loadmodel->brushq1.lightdata = Mem_Alloc(loadmodel->mempool, l->filelen);
1286                 for (i=0; i<l->filelen; i++)
1287                         loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1288         }
1289         else // LordHavoc: bsp version 29 (normal white lighting)
1290         {
1291                 // LordHavoc: hope is not lost yet, check for a .lit file to load
1292                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1293                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1294                 strlcat (litfilename, ".lit", sizeof (litfilename));
1295                 data = (qbyte*) FS_LoadFile(litfilename, tempmempool, false);
1296                 if (data)
1297                 {
1298                         if (fs_filesize > 8 && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1299                         {
1300                                 i = LittleLong(((int *)data)[1]);
1301                                 if (i == 1)
1302                                 {
1303                                         Con_DPrintf("loaded %s\n", litfilename);
1304                                         loadmodel->brushq1.lightdata = Mem_Alloc(loadmodel->mempool, fs_filesize - 8);
1305                                         memcpy(loadmodel->brushq1.lightdata, data + 8, fs_filesize - 8);
1306                                         Mem_Free(data);
1307                                         return;
1308                                 }
1309                                 else
1310                                 {
1311                                         Con_Printf("Unknown .lit file version (%d)\n", i);
1312                                         Mem_Free(data);
1313                                 }
1314                         }
1315                         else
1316                         {
1317                                 if (fs_filesize == 8)
1318                                         Con_Print("Empty .lit file, ignoring\n");
1319                                 else
1320                                         Con_Print("Corrupt .lit file (old version?), ignoring\n");
1321                                 Mem_Free(data);
1322                         }
1323                 }
1324                 // LordHavoc: oh well, expand the white lighting data
1325                 if (!l->filelen)
1326                         return;
1327                 loadmodel->brushq1.lightdata = Mem_Alloc(loadmodel->mempool, l->filelen*3);
1328                 in = loadmodel->brushq1.lightdata + l->filelen*2; // place the file at the end, so it will not be overwritten until the very last write
1329                 out = loadmodel->brushq1.lightdata;
1330                 memcpy(in, mod_base + l->fileofs, l->filelen);
1331                 for (i = 0;i < l->filelen;i++)
1332                 {
1333                         d = *in++;
1334                         *out++ = d;
1335                         *out++ = d;
1336                         *out++ = d;
1337                 }
1338         }
1339 }
1340
1341 static void Mod_Q1BSP_LoadLightList(void)
1342 {
1343         int a, n, numlights;
1344         char tempchar, *s, *t, *lightsstring, lightsfilename[1024];
1345         mlight_t *e;
1346
1347         strlcpy (lightsfilename, loadmodel->name, sizeof (lightsfilename));
1348         FS_StripExtension (lightsfilename, lightsfilename, sizeof(lightsfilename));
1349         strlcat (lightsfilename, ".lights", sizeof (lightsfilename));
1350         s = lightsstring = (char *) FS_LoadFile(lightsfilename, tempmempool, false);
1351         if (s)
1352         {
1353                 numlights = 0;
1354                 while (*s)
1355                 {
1356                         while (*s && *s != '\n' && *s != '\r')
1357                                 s++;
1358                         if (!*s)
1359                         {
1360                                 Mem_Free(lightsstring);
1361                                 Con_Printf("lights file must end with a newline\n");
1362                                 return;
1363                         }
1364                         s++;
1365                         numlights++;
1366                 }
1367                 loadmodel->brushq1.lights = Mem_Alloc(loadmodel->mempool, numlights * sizeof(mlight_t));
1368                 s = lightsstring;
1369                 n = 0;
1370                 while (*s && n < numlights)
1371                 {
1372                         t = s;
1373                         while (*s && *s != '\n' && *s != '\r')
1374                                 s++;
1375                         if (!*s)
1376                         {
1377                                 Con_Printf("misparsed lights file!\n");
1378                                 break;
1379                         }
1380                         e = loadmodel->brushq1.lights + n;
1381                         tempchar = *s;
1382                         *s = 0;
1383                         a = sscanf(t, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d", &e->origin[0], &e->origin[1], &e->origin[2], &e->falloff, &e->light[0], &e->light[1], &e->light[2], &e->subtract, &e->spotdir[0], &e->spotdir[1], &e->spotdir[2], &e->spotcone, &e->distbias, &e->style);
1384                         *s = tempchar;
1385                         if (a != 14)
1386                         {
1387                                 Con_Printf("invalid lights file, found %d parameters on line %i, should be 14 parameters (origin[0] origin[1] origin[2] falloff light[0] light[1] light[2] subtract spotdir[0] spotdir[1] spotdir[2] spotcone distancebias style)\n", a, n + 1);
1388                                 break;
1389                         }
1390                         if (*s == '\r')
1391                                 s++;
1392                         if (*s == '\n')
1393                                 s++;
1394                         n++;
1395                 }
1396                 if (*s)
1397                         Con_Printf("misparsed lights file!\n");
1398                 loadmodel->brushq1.numlights = numlights;
1399                 Mem_Free(lightsstring);
1400         }
1401 }
1402
1403 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1404 {
1405         loadmodel->brushq1.num_compressedpvs = 0;
1406         loadmodel->brushq1.data_compressedpvs = NULL;
1407         if (!l->filelen)
1408                 return;
1409         loadmodel->brushq1.num_compressedpvs = l->filelen;
1410         loadmodel->brushq1.data_compressedpvs = Mem_Alloc(loadmodel->mempool, l->filelen);
1411         memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1412 }
1413
1414 // used only for HalfLife maps
1415 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1416 {
1417         char key[128], value[4096];
1418         char wadname[128];
1419         int i, j, k;
1420         if (!data)
1421                 return;
1422         if (!COM_ParseToken(&data, false))
1423                 return; // error
1424         if (com_token[0] != '{')
1425                 return; // error
1426         while (1)
1427         {
1428                 if (!COM_ParseToken(&data, false))
1429                         return; // error
1430                 if (com_token[0] == '}')
1431                         break; // end of worldspawn
1432                 if (com_token[0] == '_')
1433                         strcpy(key, com_token + 1);
1434                 else
1435                         strcpy(key, com_token);
1436                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1437                         key[strlen(key)-1] = 0;
1438                 if (!COM_ParseToken(&data, false))
1439                         return; // error
1440                 strcpy(value, com_token);
1441                 if (!strcmp("wad", key)) // for HalfLife maps
1442                 {
1443                         if (loadmodel->brush.ishlbsp)
1444                         {
1445                                 j = 0;
1446                                 for (i = 0;i < 4096;i++)
1447                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1448                                                 break;
1449                                 if (value[i])
1450                                 {
1451                                         for (;i < 4096;i++)
1452                                         {
1453                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1454                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1455                                                         j = i+1;
1456                                                 else if (value[i] == ';' || value[i] == 0)
1457                                                 {
1458                                                         k = value[i];
1459                                                         value[i] = 0;
1460                                                         strcpy(wadname, "textures/");
1461                                                         strcat(wadname, &value[j]);
1462                                                         W_LoadTextureWadFile(wadname, false);
1463                                                         j = i+1;
1464                                                         if (!k)
1465                                                                 break;
1466                                                 }
1467                                         }
1468                                 }
1469                         }
1470                 }
1471         }
1472 }
1473
1474 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1475 {
1476         loadmodel->brush.entities = NULL;
1477         if (!l->filelen)
1478                 return;
1479         loadmodel->brush.entities = Mem_Alloc(loadmodel->mempool, l->filelen);
1480         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1481         if (loadmodel->brush.ishlbsp)
1482                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1483 }
1484
1485
1486 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1487 {
1488         dvertex_t       *in;
1489         mvertex_t       *out;
1490         int                     i, count;
1491
1492         in = (void *)(mod_base + l->fileofs);
1493         if (l->filelen % sizeof(*in))
1494                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1495         count = l->filelen / sizeof(*in);
1496         out = Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1497
1498         loadmodel->brushq1.vertexes = out;
1499         loadmodel->brushq1.numvertexes = count;
1500
1501         for ( i=0 ; i<count ; i++, in++, out++)
1502         {
1503                 out->position[0] = LittleFloat(in->point[0]);
1504                 out->position[1] = LittleFloat(in->point[1]);
1505                 out->position[2] = LittleFloat(in->point[2]);
1506         }
1507 }
1508
1509 static void Mod_Q1BSP_LoadSubmodels(lump_t *l)
1510 {
1511         dmodel_t        *in;
1512         dmodel_t        *out;
1513         int                     i, j, count;
1514
1515         in = (void *)(mod_base + l->fileofs);
1516         if (l->filelen % sizeof(*in))
1517                 Host_Error("Mod_Q1BSP_LoadSubmodels: funny lump size in %s",loadmodel->name);
1518         count = l->filelen / sizeof(*in);
1519         out = Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1520
1521         loadmodel->brushq1.submodels = out;
1522         loadmodel->brush.numsubmodels = count;
1523
1524         for ( i=0 ; i<count ; i++, in++, out++)
1525         {
1526                 for (j=0 ; j<3 ; j++)
1527                 {
1528                         // spread the mins / maxs by a pixel
1529                         out->mins[j] = LittleFloat(in->mins[j]) - 1;
1530                         out->maxs[j] = LittleFloat(in->maxs[j]) + 1;
1531                         out->origin[j] = LittleFloat(in->origin[j]);
1532                 }
1533                 for (j=0 ; j<MAX_MAP_HULLS ; j++)
1534                         out->headnode[j] = LittleLong(in->headnode[j]);
1535                 out->visleafs = LittleLong(in->visleafs);
1536                 out->firstface = LittleLong(in->firstface);
1537                 out->numfaces = LittleLong(in->numfaces);
1538         }
1539 }
1540
1541 static void Mod_Q1BSP_LoadEdges(lump_t *l)
1542 {
1543         dedge_t *in;
1544         medge_t *out;
1545         int     i, count;
1546
1547         in = (void *)(mod_base + l->fileofs);
1548         if (l->filelen % sizeof(*in))
1549                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
1550         count = l->filelen / sizeof(*in);
1551         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
1552
1553         loadmodel->brushq1.edges = out;
1554         loadmodel->brushq1.numedges = count;
1555
1556         for ( i=0 ; i<count ; i++, in++, out++)
1557         {
1558                 out->v[0] = (unsigned short)LittleShort(in->v[0]);
1559                 out->v[1] = (unsigned short)LittleShort(in->v[1]);
1560         }
1561 }
1562
1563 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
1564 {
1565         texinfo_t *in;
1566         mtexinfo_t *out;
1567         int i, j, k, count, miptex;
1568
1569         in = (void *)(mod_base + l->fileofs);
1570         if (l->filelen % sizeof(*in))
1571                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
1572         count = l->filelen / sizeof(*in);
1573         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
1574
1575         loadmodel->brushq1.texinfo = out;
1576         loadmodel->brushq1.numtexinfo = count;
1577
1578         for (i = 0;i < count;i++, in++, out++)
1579         {
1580                 for (k = 0;k < 2;k++)
1581                         for (j = 0;j < 4;j++)
1582                                 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
1583
1584                 miptex = LittleLong(in->miptex);
1585                 out->flags = LittleLong(in->flags);
1586
1587                 out->texture = NULL;
1588                 if (loadmodel->brush.data_textures)
1589                 {
1590                         if ((unsigned int) miptex >= (unsigned int) loadmodel->brush.num_textures)
1591                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->brush.num_textures);
1592                         else
1593                                 out->texture = loadmodel->brush.data_textures + miptex;
1594                 }
1595                 if (out->flags & TEX_SPECIAL)
1596                 {
1597                         // if texture chosen is NULL or the shader needs a lightmap,
1598                         // force to notexture water shader
1599                         if (out->texture == NULL || out->texture->basematerialflags & MATERIALFLAG_WALL)
1600                                 out->texture = loadmodel->brush.data_textures + (loadmodel->brush.num_textures - 1);
1601                 }
1602                 else
1603                 {
1604                         // if texture chosen is NULL, force to notexture
1605                         if (out->texture == NULL)
1606                                 out->texture = loadmodel->brush.data_textures + (loadmodel->brush.num_textures - 2);
1607                 }
1608         }
1609 }
1610
1611 #if 0
1612 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
1613 {
1614         int             i, j;
1615         float   *v;
1616
1617         mins[0] = mins[1] = mins[2] = 9999;
1618         maxs[0] = maxs[1] = maxs[2] = -9999;
1619         v = verts;
1620         for (i = 0;i < numverts;i++)
1621         {
1622                 for (j = 0;j < 3;j++, v++)
1623                 {
1624                         if (*v < mins[j])
1625                                 mins[j] = *v;
1626                         if (*v > maxs[j])
1627                                 maxs[j] = *v;
1628                 }
1629         }
1630 }
1631
1632 #define MAX_SUBDIVPOLYTRIANGLES 4096
1633 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
1634
1635 static int subdivpolyverts, subdivpolytriangles;
1636 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
1637 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
1638
1639 static int subdivpolylookupvert(vec3_t v)
1640 {
1641         int i;
1642         for (i = 0;i < subdivpolyverts;i++)
1643                 if (subdivpolyvert[i][0] == v[0]
1644                  && subdivpolyvert[i][1] == v[1]
1645                  && subdivpolyvert[i][2] == v[2])
1646                         return i;
1647         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
1648                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
1649         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
1650         return subdivpolyverts++;
1651 }
1652
1653 static void SubdividePolygon(int numverts, float *verts)
1654 {
1655         int             i, i1, i2, i3, f, b, c, p;
1656         vec3_t  mins, maxs, front[256], back[256];
1657         float   m, *pv, *cv, dist[256], frac;
1658
1659         if (numverts > 250)
1660                 Host_Error("SubdividePolygon: ran out of verts in buffer");
1661
1662         BoundPoly(numverts, verts, mins, maxs);
1663
1664         for (i = 0;i < 3;i++)
1665         {
1666                 m = (mins[i] + maxs[i]) * 0.5;
1667                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
1668                 if (maxs[i] - m < 8)
1669                         continue;
1670                 if (m - mins[i] < 8)
1671                         continue;
1672
1673                 // cut it
1674                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
1675                         dist[c] = cv[i] - m;
1676
1677                 f = b = 0;
1678                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
1679                 {
1680                         if (dist[p] >= 0)
1681                         {
1682                                 VectorCopy(pv, front[f]);
1683                                 f++;
1684                         }
1685                         if (dist[p] <= 0)
1686                         {
1687                                 VectorCopy(pv, back[b]);
1688                                 b++;
1689                         }
1690                         if (dist[p] == 0 || dist[c] == 0)
1691                                 continue;
1692                         if ((dist[p] > 0) != (dist[c] > 0) )
1693                         {
1694                                 // clip point
1695                                 frac = dist[p] / (dist[p] - dist[c]);
1696                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
1697                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
1698                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
1699                                 f++;
1700                                 b++;
1701                         }
1702                 }
1703
1704                 SubdividePolygon(f, front[0]);
1705                 SubdividePolygon(b, back[0]);
1706                 return;
1707         }
1708
1709         i1 = subdivpolylookupvert(verts);
1710         i2 = subdivpolylookupvert(verts + 3);
1711         for (i = 2;i < numverts;i++)
1712         {
1713                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
1714                 {
1715                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
1716                         return;
1717                 }
1718
1719                 i3 = subdivpolylookupvert(verts + i * 3);
1720                 subdivpolyindex[subdivpolytriangles][0] = i1;
1721                 subdivpolyindex[subdivpolytriangles][1] = i2;
1722                 subdivpolyindex[subdivpolytriangles][2] = i3;
1723                 i2 = i3;
1724                 subdivpolytriangles++;
1725         }
1726 }
1727
1728 //Breaks a polygon up along axial 64 unit
1729 //boundaries so that turbulent and sky warps
1730 //can be done reasonably.
1731 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
1732 {
1733         int i, j;
1734         surfvertex_t *v;
1735         surfmesh_t *mesh;
1736
1737         subdivpolytriangles = 0;
1738         subdivpolyverts = 0;
1739         SubdividePolygon(surface->mesh.num_vertices, surface->mesh.data_vertex3f);
1740         if (subdivpolytriangles < 1)
1741                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?\n");
1742
1743         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
1744         mesh->num_vertices = subdivpolyverts;
1745         mesh->num_triangles = subdivpolytriangles;
1746         mesh->vertex = (surfvertex_t *)(mesh + 1);
1747         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
1748         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
1749
1750         for (i = 0;i < mesh->num_triangles;i++)
1751                 for (j = 0;j < 3;j++)
1752                         mesh->index[i*3+j] = subdivpolyindex[i][j];
1753
1754         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
1755         {
1756                 VectorCopy(subdivpolyvert[i], v->v);
1757                 v->st[0] = DotProduct(v->v, surface->texinfo->vecs[0]);
1758                 v->st[1] = DotProduct(v->v, surface->texinfo->vecs[1]);
1759         }
1760 }
1761 #endif
1762
1763 static void Mod_Q1BSP_LoadFaces(lump_t *l)
1764 {
1765         dface_t *in;
1766         msurface_t *surface;
1767         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris;
1768         float texmins[2], texmaxs[2], val;
1769
1770         in = (void *)(mod_base + l->fileofs);
1771         if (l->filelen % sizeof(*in))
1772                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
1773         count = l->filelen / sizeof(*in);
1774         loadmodel->brush.data_surfaces = Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
1775
1776         loadmodel->brush.num_surfaces = count;
1777
1778         totalverts = 0;
1779         totaltris = 0;
1780         for (surfacenum = 0, in = (void *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
1781         {
1782                 numedges = LittleShort(in->numedges);
1783                 totalverts += numedges;
1784                 totaltris += numedges - 2;
1785         }
1786
1787         // TODO: split up into multiple meshes as needed to avoid exceeding 65536
1788         // vertex limit
1789         loadmodel->nummeshes = 1;
1790         loadmodel->meshlist = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *));
1791         loadmodel->meshlist[0] = Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, 0, 0, true, true, false);
1792
1793         totalverts = 0;
1794         totaltris = 0;
1795         for (surfacenum = 0, in = (void *)(mod_base + l->fileofs), surface = loadmodel->brush.data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
1796         {
1797                 // FIXME: validate edges, texinfo, etc?
1798                 firstedge = LittleLong(in->firstedge);
1799                 numedges = LittleShort(in->numedges);
1800                 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)
1801                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)\n", firstedge, numedges, loadmodel->brushq1.numsurfedges);
1802                 i = LittleShort(in->texinfo);
1803                 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
1804                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)\n", i, loadmodel->brushq1.numtexinfo);
1805                 surface->texinfo = loadmodel->brushq1.texinfo + i;
1806                 surface->texture = surface->texinfo->texture;
1807
1808                 planenum = LittleShort(in->planenum);
1809                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
1810                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)\n", planenum, loadmodel->brush.num_planes);
1811
1812                 //surface->flags = surface->texture->flags;
1813                 //if (LittleShort(in->side))
1814                 //      surface->flags |= SURF_PLANEBACK;
1815                 //surface->plane = loadmodel->brush.data_planes + planenum;
1816
1817                 surface->mesh.num_vertices = numedges;
1818                 surface->mesh.num_triangles = numedges - 2;
1819                 surface->mesh.data_vertex3f = loadmodel->meshlist[0]->data_vertex3f + totalverts * 3;
1820                 surface->mesh.data_texcoordtexture2f = loadmodel->meshlist[0]->data_texcoordtexture2f + totalverts * 2;
1821                 surface->mesh.data_texcoordlightmap2f = loadmodel->meshlist[0]->data_texcoordlightmap2f + totalverts * 2;
1822                 surface->mesh.data_texcoorddetail2f = loadmodel->meshlist[0]->data_texcoorddetail2f + totalverts * 2;
1823                 surface->mesh.data_svector3f = loadmodel->meshlist[0]->data_svector3f + totalverts * 3;
1824                 surface->mesh.data_tvector3f = loadmodel->meshlist[0]->data_tvector3f + totalverts * 3;
1825                 surface->mesh.data_normal3f = loadmodel->meshlist[0]->data_normal3f + totalverts * 3;
1826                 surface->mesh.data_lightmapoffsets = loadmodel->meshlist[0]->data_lightmapoffsets + totalverts;
1827                 surface->mesh.data_element3i = loadmodel->meshlist[0]->data_element3i + totaltris * 3;
1828                 surface->mesh.data_neighbor3i = loadmodel->meshlist[0]->data_neighbor3i + totaltris * 3;
1829                 totalverts += numedges;
1830                 totaltris += numedges - 2;
1831
1832                 // convert edges back to a normal polygon
1833                 for (i = 0;i < surface->mesh.num_vertices;i++)
1834                 {
1835                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
1836                         float s, t;
1837                         if (lindex > 0)
1838                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, surface->mesh.data_vertex3f + i * 3);
1839                         else
1840                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, surface->mesh.data_vertex3f + i * 3);
1841                         s = DotProduct((surface->mesh.data_vertex3f + i * 3), surface->texinfo->vecs[0]) + surface->texinfo->vecs[0][3];
1842                         t = DotProduct((surface->mesh.data_vertex3f + i * 3), surface->texinfo->vecs[1]) + surface->texinfo->vecs[1][3];
1843                         surface->mesh.data_texcoordtexture2f[i * 2 + 0] = s / surface->texture->width;
1844                         surface->mesh.data_texcoordtexture2f[i * 2 + 1] = t / surface->texture->height;
1845                         surface->mesh.data_texcoorddetail2f[i * 2 + 0] = s * (1.0f / 16.0f);
1846                         surface->mesh.data_texcoorddetail2f[i * 2 + 1] = t * (1.0f / 16.0f);
1847                         surface->mesh.data_texcoordlightmap2f[i * 2 + 0] = 0;
1848                         surface->mesh.data_texcoordlightmap2f[i * 2 + 1] = 0;
1849                         surface->mesh.data_lightmapoffsets[i] = 0;
1850                 }
1851
1852                 for (i = 0;i < surface->mesh.num_triangles;i++)
1853                 {
1854                         surface->mesh.data_element3i[i * 3 + 0] = 0;
1855                         surface->mesh.data_element3i[i * 3 + 1] = i + 1;
1856                         surface->mesh.data_element3i[i * 3 + 2] = i + 2;
1857                 }
1858
1859                 // compile additional data about the surface geometry
1860                 Mod_BuildTriangleNeighbors(surface->mesh.data_neighbor3i, surface->mesh.data_element3i, surface->mesh.num_triangles);
1861                 Mod_BuildTextureVectorsAndNormals(surface->mesh.num_vertices, surface->mesh.num_triangles, surface->mesh.data_vertex3f, surface->mesh.data_texcoordtexture2f, surface->mesh.data_element3i, surface->mesh.data_svector3f, surface->mesh.data_tvector3f, surface->mesh.data_normal3f);
1862                 BoxFromPoints(surface->mins, surface->maxs, surface->mesh.num_vertices, surface->mesh.data_vertex3f);
1863
1864                 // generate surface extents information
1865                 texmins[0] = texmaxs[0] = DotProduct(surface->mesh.data_vertex3f, surface->texinfo->vecs[0]) + surface->texinfo->vecs[0][3];
1866                 texmins[1] = texmaxs[1] = DotProduct(surface->mesh.data_vertex3f, surface->texinfo->vecs[1]) + surface->texinfo->vecs[1][3];
1867                 for (i = 1;i < surface->mesh.num_vertices;i++)
1868                 {
1869                         for (j = 0;j < 2;j++)
1870                         {
1871                                 val = DotProduct(surface->mesh.data_vertex3f + i * 3, surface->texinfo->vecs[j]) + surface->texinfo->vecs[j][3];
1872                                 texmins[j] = min(texmins[j], val);
1873                                 texmaxs[j] = max(texmaxs[j], val);
1874                         }
1875                 }
1876                 for (i = 0;i < 2;i++)
1877                 {
1878                         surface->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
1879                         surface->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->texturemins[i];
1880                 }
1881
1882                 smax = surface->extents[0] >> 4;
1883                 tmax = surface->extents[1] >> 4;
1884                 ssize = (surface->extents[0] >> 4) + 1;
1885                 tsize = (surface->extents[1] >> 4) + 1;
1886
1887                 // lighting info
1888                 for (i = 0;i < MAXLIGHTMAPS;i++)
1889                         surface->styles[i] = in->styles[i];
1890                 // force lightmap upload on first time seeing the surface
1891                 surface->cached_dlight = true;
1892                 surface->lightmaptexturestride = 0;
1893                 surface->lightmaptexture = NULL;
1894                 i = LittleLong(in->lightofs);
1895                 if (i == -1)
1896                 {
1897                         surface->samples = NULL;
1898                         // give non-lightmapped water a 1x white lightmap
1899                         if ((surface->texture->basematerialflags & MATERIALFLAG_WATER) && (surface->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
1900                         {
1901                                 surface->samples = Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
1902                                 surface->styles[0] = 0;
1903                                 memset(surface->samples, 128, ssize * tsize * 3);
1904                         }
1905                 }
1906                 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
1907                         surface->samples = loadmodel->brushq1.lightdata + i;
1908                 else // LordHavoc: white lighting (bsp version 29)
1909                         surface->samples = loadmodel->brushq1.lightdata + (i * 3);
1910
1911                 if (!(surface->texinfo->flags & TEX_SPECIAL) || surface->samples)
1912                 {
1913                         int i, iu, iv;
1914                         float u, v, ubase, vbase, uscale, vscale;
1915
1916                         if (ssize > 256 || tsize > 256)
1917                                 Host_Error("Bad surface extents");
1918                         // stainmap for permanent marks on walls
1919                         surface->stainsamples = Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
1920                         // clear to white
1921                         memset(surface->stainsamples, 255, ssize * tsize * 3);
1922
1923                         if (r_miplightmaps.integer)
1924                         {
1925                                 surface->lightmaptexturestride = ssize;
1926                                 surface->lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, NULL, surface->lightmaptexturestride, tsize, NULL, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, TEXF_MIPMAP | TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
1927                         }
1928                         else
1929                         {
1930                                 surface->lightmaptexturestride = R_CompatibleFragmentWidth(ssize, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, 0);
1931                                 surface->lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, NULL, surface->lightmaptexturestride, tsize, NULL, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, TEXF_FRAGMENT | TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
1932                         }
1933                         R_FragmentLocation(surface->lightmaptexture, NULL, NULL, &ubase, &vbase, &uscale, &vscale);
1934                         uscale = (uscale - ubase) / ssize;
1935                         vscale = (vscale - vbase) / tsize;
1936
1937                         for (i = 0;i < surface->mesh.num_vertices;i++)
1938                         {
1939                                 u = ((DotProduct((surface->mesh.data_vertex3f + i * 3), surface->texinfo->vecs[0]) + surface->texinfo->vecs[0][3]) + 8 - surface->texturemins[0]) * (1.0 / 16.0);
1940                                 v = ((DotProduct((surface->mesh.data_vertex3f + i * 3), surface->texinfo->vecs[1]) + surface->texinfo->vecs[1][3]) + 8 - surface->texturemins[1]) * (1.0 / 16.0);
1941                                 surface->mesh.data_texcoordlightmap2f[i * 2 + 0] = u * uscale + ubase;
1942                                 surface->mesh.data_texcoordlightmap2f[i * 2 + 1] = v * vscale + vbase;
1943                                 // LordHavoc: calc lightmap data offset for vertex lighting to use
1944                                 iu = (int) u;
1945                                 iv = (int) v;
1946                                 surface->mesh.data_lightmapoffsets[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
1947                         }
1948                 }
1949         }
1950 }
1951
1952 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
1953 {
1954         //if (node->parent)
1955         //      Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion\n");
1956         node->parent = parent;
1957         if (node->plane)
1958         {
1959                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
1960                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
1961         }
1962 }
1963
1964 static void Mod_Q1BSP_LoadNodes(lump_t *l)
1965 {
1966         int                     i, j, count, p;
1967         dnode_t         *in;
1968         mnode_t         *out;
1969
1970         in = (void *)(mod_base + l->fileofs);
1971         if (l->filelen % sizeof(*in))
1972                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
1973         count = l->filelen / sizeof(*in);
1974         out = Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1975
1976         loadmodel->brush.data_nodes = out;
1977         loadmodel->brush.num_nodes = count;
1978
1979         for ( i=0 ; i<count ; i++, in++, out++)
1980         {
1981                 for (j=0 ; j<3 ; j++)
1982                 {
1983                         out->mins[j] = LittleShort(in->mins[j]);
1984                         out->maxs[j] = LittleShort(in->maxs[j]);
1985                 }
1986
1987                 p = LittleLong(in->planenum);
1988                 out->plane = loadmodel->brush.data_planes + p;
1989
1990                 out->firstsurface = LittleShort(in->firstface);
1991                 out->numsurfaces = LittleShort(in->numfaces);
1992
1993                 for (j=0 ; j<2 ; j++)
1994                 {
1995                         p = LittleShort(in->children[j]);
1996                         if (p >= 0)
1997                                 out->children[j] = loadmodel->brush.data_nodes + p;
1998                         else
1999                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + (-1 - p));
2000                 }
2001         }
2002
2003         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);      // sets nodes and leafs
2004 }
2005
2006 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2007 {
2008         dleaf_t *in;
2009         mleaf_t *out;
2010         int i, j, count, p;
2011
2012         in = (void *)(mod_base + l->fileofs);
2013         if (l->filelen % sizeof(*in))
2014                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2015         count = l->filelen / sizeof(*in);
2016         out = Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2017
2018         loadmodel->brush.data_leafs = out;
2019         loadmodel->brush.num_leafs = count;
2020         // get visleafs from the submodel data
2021         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2022         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2023         loadmodel->brush.data_pvsclusters = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2024         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2025
2026         for ( i=0 ; i<count ; i++, in++, out++)
2027         {
2028                 for (j=0 ; j<3 ; j++)
2029                 {
2030                         out->mins[j] = LittleShort(in->mins[j]);
2031                         out->maxs[j] = LittleShort(in->maxs[j]);
2032                 }
2033
2034                 // FIXME: this function could really benefit from some error checking
2035
2036                 out->contents = LittleLong(in->contents);
2037
2038                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + LittleShort(in->firstmarksurface);
2039                 out->numleafsurfaces = LittleShort(in->nummarksurfaces);
2040                 if (out->firstleafsurface < 0 || LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2041                 {
2042                         Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", out->firstleafsurface, out->firstleafsurface + out->numleafsurfaces, 0, loadmodel->brush.num_leafsurfaces);
2043                         out->firstleafsurface = NULL;
2044                         out->numleafsurfaces = 0;
2045                 }
2046
2047                 out->clusterindex = i - 1;
2048                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2049                         out->clusterindex = -1;
2050
2051                 p = LittleLong(in->visofs);
2052                 // ignore visofs errors on leaf 0 (solid)
2053                 if (p >= 0 && out->clusterindex >= 0)
2054                 {
2055                         if (p >= loadmodel->brushq1.num_compressedpvs)
2056                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2057                         else
2058                                 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);
2059                 }
2060
2061                 for (j = 0;j < 4;j++)
2062                         out->ambient_sound_level[j] = in->ambient_level[j];
2063
2064                 // FIXME: Insert caustics here
2065         }
2066 }
2067
2068 static void Mod_Q1BSP_LoadClipnodes(lump_t *l)
2069 {
2070         dclipnode_t *in, *out;
2071         int                     i, count;
2072         hull_t          *hull;
2073
2074         in = (void *)(mod_base + l->fileofs);
2075         if (l->filelen % sizeof(*in))
2076                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2077         count = l->filelen / sizeof(*in);
2078         out = Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2079
2080         loadmodel->brushq1.clipnodes = out;
2081         loadmodel->brushq1.numclipnodes = count;
2082
2083         if (loadmodel->brush.ishlbsp)
2084         {
2085                 hull = &loadmodel->brushq1.hulls[1];
2086                 hull->clipnodes = out;
2087                 hull->firstclipnode = 0;
2088                 hull->lastclipnode = count-1;
2089                 hull->planes = loadmodel->brush.data_planes;
2090                 hull->clip_mins[0] = -16;
2091                 hull->clip_mins[1] = -16;
2092                 hull->clip_mins[2] = -36;
2093                 hull->clip_maxs[0] = 16;
2094                 hull->clip_maxs[1] = 16;
2095                 hull->clip_maxs[2] = 36;
2096                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2097
2098                 hull = &loadmodel->brushq1.hulls[2];
2099                 hull->clipnodes = out;
2100                 hull->firstclipnode = 0;
2101                 hull->lastclipnode = count-1;
2102                 hull->planes = loadmodel->brush.data_planes;
2103                 hull->clip_mins[0] = -32;
2104                 hull->clip_mins[1] = -32;
2105                 hull->clip_mins[2] = -32;
2106                 hull->clip_maxs[0] = 32;
2107                 hull->clip_maxs[1] = 32;
2108                 hull->clip_maxs[2] = 32;
2109                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2110
2111                 hull = &loadmodel->brushq1.hulls[3];
2112                 hull->clipnodes = out;
2113                 hull->firstclipnode = 0;
2114                 hull->lastclipnode = count-1;
2115                 hull->planes = loadmodel->brush.data_planes;
2116                 hull->clip_mins[0] = -16;
2117                 hull->clip_mins[1] = -16;
2118                 hull->clip_mins[2] = -18;
2119                 hull->clip_maxs[0] = 16;
2120                 hull->clip_maxs[1] = 16;
2121                 hull->clip_maxs[2] = 18;
2122                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2123         }
2124         else
2125         {
2126                 hull = &loadmodel->brushq1.hulls[1];
2127                 hull->clipnodes = out;
2128                 hull->firstclipnode = 0;
2129                 hull->lastclipnode = count-1;
2130                 hull->planes = loadmodel->brush.data_planes;
2131                 hull->clip_mins[0] = -16;
2132                 hull->clip_mins[1] = -16;
2133                 hull->clip_mins[2] = -24;
2134                 hull->clip_maxs[0] = 16;
2135                 hull->clip_maxs[1] = 16;
2136                 hull->clip_maxs[2] = 32;
2137                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2138
2139                 hull = &loadmodel->brushq1.hulls[2];
2140                 hull->clipnodes = out;
2141                 hull->firstclipnode = 0;
2142                 hull->lastclipnode = count-1;
2143                 hull->planes = loadmodel->brush.data_planes;
2144                 hull->clip_mins[0] = -32;
2145                 hull->clip_mins[1] = -32;
2146                 hull->clip_mins[2] = -24;
2147                 hull->clip_maxs[0] = 32;
2148                 hull->clip_maxs[1] = 32;
2149                 hull->clip_maxs[2] = 64;
2150                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2151         }
2152
2153         for (i=0 ; i<count ; i++, out++, in++)
2154         {
2155                 out->planenum = LittleLong(in->planenum);
2156                 out->children[0] = LittleShort(in->children[0]);
2157                 out->children[1] = LittleShort(in->children[1]);
2158                 if (out->children[0] >= count || out->children[1] >= count)
2159                         Host_Error("Corrupt clipping hull(out of range child)\n");
2160         }
2161 }
2162
2163 //Duplicate the drawing hull structure as a clipping hull
2164 static void Mod_Q1BSP_MakeHull0(void)
2165 {
2166         mnode_t         *in;
2167         dclipnode_t *out;
2168         int                     i;
2169         hull_t          *hull;
2170
2171         hull = &loadmodel->brushq1.hulls[0];
2172
2173         in = loadmodel->brush.data_nodes;
2174         out = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(dclipnode_t));
2175
2176         hull->clipnodes = out;
2177         hull->firstclipnode = 0;
2178         hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2179         hull->planes = loadmodel->brush.data_planes;
2180
2181         for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2182         {
2183                 out->planenum = in->plane - loadmodel->brush.data_planes;
2184                 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2185                 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2186         }
2187 }
2188
2189 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2190 {
2191         int i, j;
2192         short *in;
2193
2194         in = (void *)(mod_base + l->fileofs);
2195         if (l->filelen % sizeof(*in))
2196                 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2197         loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2198         loadmodel->brush.data_leafsurfaces = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2199
2200         for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2201         {
2202                 j = (unsigned) LittleShort(in[i]);
2203                 if (j >= loadmodel->brush.num_surfaces)
2204                         Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2205                 loadmodel->brush.data_leafsurfaces[i] = j;
2206         }
2207 }
2208
2209 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2210 {
2211         int             i;
2212         int             *in;
2213
2214         in = (void *)(mod_base + l->fileofs);
2215         if (l->filelen % sizeof(*in))
2216                 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2217         loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2218         loadmodel->brushq1.surfedges = Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2219
2220         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2221                 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2222 }
2223
2224
2225 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2226 {
2227         int                     i;
2228         mplane_t        *out;
2229         dplane_t        *in;
2230
2231         in = (void *)(mod_base + l->fileofs);
2232         if (l->filelen % sizeof(*in))
2233                 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2234
2235         loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2236         loadmodel->brush.data_planes = out = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2237
2238         for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2239         {
2240                 out->normal[0] = LittleFloat(in->normal[0]);
2241                 out->normal[1] = LittleFloat(in->normal[1]);
2242                 out->normal[2] = LittleFloat(in->normal[2]);
2243                 out->dist = LittleFloat(in->dist);
2244
2245                 PlaneClassify(out);
2246         }
2247 }
2248
2249 static void Mod_Q1BSP_LoadMapBrushes(void)
2250 {
2251 #if 0
2252 // unfinished
2253         int submodel, numbrushes;
2254         qboolean firstbrush;
2255         char *text, *maptext;
2256         char mapfilename[MAX_QPATH];
2257         FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2258         strlcat (mapfilename, ".map", sizeof (mapfilename));
2259         maptext = (qbyte*) FS_LoadFile(mapfilename, tempmempool, false);
2260         if (!maptext)
2261                 return;
2262         text = maptext;
2263         if (!COM_ParseToken(&data, false))
2264                 return; // error
2265         submodel = 0;
2266         for (;;)
2267         {
2268                 if (!COM_ParseToken(&data, false))
2269                         break;
2270                 if (com_token[0] != '{')
2271                         return; // error
2272                 // entity
2273                 firstbrush = true;
2274                 numbrushes = 0;
2275                 maxbrushes = 256;
2276                 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2277                 for (;;)
2278                 {
2279                         if (!COM_ParseToken(&data, false))
2280                                 return; // error
2281                         if (com_token[0] == '}')
2282                                 break; // end of entity
2283                         if (com_token[0] == '{')
2284                         {
2285                                 // brush
2286                                 if (firstbrush)
2287                                 {
2288                                         if (submodel)
2289                                         {
2290                                                 if (submodel > loadmodel->brush.numsubmodels)
2291                                                 {
2292                                                         Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2293                                                         model = NULL;
2294                                                 }
2295                                                 else
2296                                                         model = loadmodel->brush.submodels[submodel];
2297                                         }
2298                                         else
2299                                                 model = loadmodel;
2300                                 }
2301                                 for (;;)
2302                                 {
2303                                         if (!COM_ParseToken(&data, false))
2304                                                 return; // error
2305                                         if (com_token[0] == '}')
2306                                                 break; // end of brush
2307                                         // each brush face should be this format:
2308                                         // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2309                                         // FIXME: support hl .map format
2310                                         for (pointnum = 0;pointnum < 3;pointnum++)
2311                                         {
2312                                                 COM_ParseToken(&data, false);
2313                                                 for (componentnum = 0;componentnum < 3;componentnum++)
2314                                                 {
2315                                                         COM_ParseToken(&data, false);
2316                                                         point[pointnum][componentnum] = atof(com_token);
2317                                                 }
2318                                                 COM_ParseToken(&data, false);
2319                                         }
2320                                         COM_ParseToken(&data, false);
2321                                         strlcpy(facetexture, com_token, sizeof(facetexture));
2322                                         COM_ParseToken(&data, false);
2323                                         //scroll_s = atof(com_token);
2324                                         COM_ParseToken(&data, false);
2325                                         //scroll_t = atof(com_token);
2326                                         COM_ParseToken(&data, false);
2327                                         //rotate = atof(com_token);
2328                                         COM_ParseToken(&data, false);
2329                                         //scale_s = atof(com_token);
2330                                         COM_ParseToken(&data, false);
2331                                         //scale_t = atof(com_token);
2332                                         TriangleNormal(point[0], point[1], point[2], planenormal);
2333                                         VectorNormalizeDouble(planenormal);
2334                                         planedist = DotProduct(point[0], planenormal);
2335                                         //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2336                                 }
2337                                 continue;
2338                         }
2339                 }
2340         }
2341 #endif
2342 }
2343
2344
2345 #define MAX_PORTALPOINTS 64
2346
2347 typedef struct portal_s
2348 {
2349         mplane_t plane;
2350         mnode_t *nodes[2];              // [0] = front side of plane
2351         struct portal_s *next[2];
2352         int numpoints;
2353         double points[3*MAX_PORTALPOINTS];
2354         struct portal_s *chain; // all portals are linked into a list
2355 }
2356 portal_t;
2357
2358 static portal_t *portalchain;
2359
2360 /*
2361 ===========
2362 AllocPortal
2363 ===========
2364 */
2365 static portal_t *AllocPortal(void)
2366 {
2367         portal_t *p;
2368         p = Mem_Alloc(loadmodel->mempool, sizeof(portal_t));
2369         p->chain = portalchain;
2370         portalchain = p;
2371         return p;
2372 }
2373
2374 static void FreePortal(portal_t *p)
2375 {
2376         Mem_Free(p);
2377 }
2378
2379 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2380 {
2381         // process only nodes (leafs already had their box calculated)
2382         if (!node->plane)
2383                 return;
2384
2385         // calculate children first
2386         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2387         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2388
2389         // make combined bounding box from children
2390         node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2391         node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2392         node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2393         node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2394         node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2395         node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2396 }
2397
2398 static void Mod_Q1BSP_FinalizePortals(void)
2399 {
2400         int i, j, numportals, numpoints;
2401         portal_t *p, *pnext;
2402         mportal_t *portal;
2403         mvertex_t *point;
2404         mleaf_t *leaf, *endleaf;
2405
2406         // recalculate bounding boxes for all leafs(because qbsp is very sloppy)
2407         leaf = loadmodel->brush.data_leafs;
2408         endleaf = leaf + loadmodel->brush.num_leafs;
2409         for (;leaf < endleaf;leaf++)
2410         {
2411                 VectorSet(leaf->mins,  2000000000,  2000000000,  2000000000);
2412                 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2413         }
2414         p = portalchain;
2415         while (p)
2416         {
2417                 if (p->numpoints >= 3)
2418                 {
2419                         for (i = 0;i < 2;i++)
2420                         {
2421                                 leaf = (mleaf_t *)p->nodes[i];
2422                                 for (j = 0;j < p->numpoints;j++)
2423                                 {
2424                                         if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
2425                                         if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
2426                                         if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
2427                                         if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
2428                                         if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
2429                                         if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
2430                                 }
2431                         }
2432                 }
2433                 p = p->chain;
2434         }
2435
2436         Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes);
2437
2438         // tally up portal and point counts
2439         p = portalchain;
2440         numportals = 0;
2441         numpoints = 0;
2442         while (p)
2443         {
2444                 // note: this check must match the one below or it will usually corrupt memory
2445                 // 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
2446                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2447                 {
2448                         numportals += 2;
2449                         numpoints += p->numpoints * 2;
2450                 }
2451                 p = p->chain;
2452         }
2453         loadmodel->brush.data_portals = Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
2454         loadmodel->brush.num_portals = numportals;
2455         loadmodel->brush.data_portalpoints = (void *)((qbyte *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
2456         loadmodel->brush.num_portalpoints = numpoints;
2457         // clear all leaf portal chains
2458         for (i = 0;i < loadmodel->brush.num_leafs;i++)
2459                 loadmodel->brush.data_leafs[i].portals = NULL;
2460         // process all portals in the global portal chain, while freeing them
2461         portal = loadmodel->brush.data_portals;
2462         point = loadmodel->brush.data_portalpoints;
2463         p = portalchain;
2464         portalchain = NULL;
2465         while (p)
2466         {
2467                 pnext = p->chain;
2468
2469                 // note: this check must match the one above or it will usually corrupt memory
2470                 // 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
2471                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2472                 {
2473                         // first make the back to front portal(forward portal)
2474                         portal->points = point;
2475                         portal->numpoints = p->numpoints;
2476                         portal->plane.dist = p->plane.dist;
2477                         VectorCopy(p->plane.normal, portal->plane.normal);
2478                         portal->here = (mleaf_t *)p->nodes[1];
2479                         portal->past = (mleaf_t *)p->nodes[0];
2480                         // copy points
2481                         for (j = 0;j < portal->numpoints;j++)
2482                         {
2483                                 VectorCopy(p->points + j*3, point->position);
2484                                 point++;
2485                         }
2486                         BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
2487                         PlaneClassify(&portal->plane);
2488
2489                         // link into leaf's portal chain
2490                         portal->next = portal->here->portals;
2491                         portal->here->portals = portal;
2492
2493                         // advance to next portal
2494                         portal++;
2495
2496                         // then make the front to back portal(backward portal)
2497                         portal->points = point;
2498                         portal->numpoints = p->numpoints;
2499                         portal->plane.dist = -p->plane.dist;
2500                         VectorNegate(p->plane.normal, portal->plane.normal);
2501                         portal->here = (mleaf_t *)p->nodes[0];
2502                         portal->past = (mleaf_t *)p->nodes[1];
2503                         // copy points
2504                         for (j = portal->numpoints - 1;j >= 0;j--)
2505                         {
2506                                 VectorCopy(p->points + j*3, point->position);
2507                                 point++;
2508                         }
2509                         BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
2510                         PlaneClassify(&portal->plane);
2511
2512                         // link into leaf's portal chain
2513                         portal->next = portal->here->portals;
2514                         portal->here->portals = portal;
2515
2516                         // advance to next portal
2517                         portal++;
2518                 }
2519                 FreePortal(p);
2520                 p = pnext;
2521         }
2522 }
2523
2524 /*
2525 =============
2526 AddPortalToNodes
2527 =============
2528 */
2529 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
2530 {
2531         if (!front)
2532                 Host_Error("AddPortalToNodes: NULL front node");
2533         if (!back)
2534                 Host_Error("AddPortalToNodes: NULL back node");
2535         if (p->nodes[0] || p->nodes[1])
2536                 Host_Error("AddPortalToNodes: already included");
2537         // 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
2538
2539         p->nodes[0] = front;
2540         p->next[0] = (portal_t *)front->portals;
2541         front->portals = (mportal_t *)p;
2542
2543         p->nodes[1] = back;
2544         p->next[1] = (portal_t *)back->portals;
2545         back->portals = (mportal_t *)p;
2546 }
2547
2548 /*
2549 =============
2550 RemovePortalFromNode
2551 =============
2552 */
2553 static void RemovePortalFromNodes(portal_t *portal)
2554 {
2555         int i;
2556         mnode_t *node;
2557         void **portalpointer;
2558         portal_t *t;
2559         for (i = 0;i < 2;i++)
2560         {
2561                 node = portal->nodes[i];
2562
2563                 portalpointer = (void **) &node->portals;
2564                 while (1)
2565                 {
2566                         t = *portalpointer;
2567                         if (!t)
2568                                 Host_Error("RemovePortalFromNodes: portal not in leaf");
2569
2570                         if (t == portal)
2571                         {
2572                                 if (portal->nodes[0] == node)
2573                                 {
2574                                         *portalpointer = portal->next[0];
2575                                         portal->nodes[0] = NULL;
2576                                 }
2577                                 else if (portal->nodes[1] == node)
2578                                 {
2579                                         *portalpointer = portal->next[1];
2580                                         portal->nodes[1] = NULL;
2581                                 }
2582                                 else
2583                                         Host_Error("RemovePortalFromNodes: portal not bounding leaf");
2584                                 break;
2585                         }
2586
2587                         if (t->nodes[0] == node)
2588                                 portalpointer = (void **) &t->next[0];
2589                         else if (t->nodes[1] == node)
2590                                 portalpointer = (void **) &t->next[1];
2591                         else
2592                                 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
2593                 }
2594         }
2595 }
2596
2597 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
2598 {
2599         int i, side;
2600         mnode_t *front, *back, *other_node;
2601         mplane_t clipplane, *plane;
2602         portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
2603         int numfrontpoints, numbackpoints;
2604         double frontpoints[3*MAX_PORTALPOINTS], backpoints[3*MAX_PORTALPOINTS];
2605
2606         // if a leaf, we're done
2607         if (!node->plane)
2608                 return;
2609
2610         plane = node->plane;
2611
2612         front = node->children[0];
2613         back = node->children[1];
2614         if (front == back)
2615                 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
2616
2617         // create the new portal by generating a polygon for the node plane,
2618         // and clipping it by all of the other portals(which came from nodes above this one)
2619         nodeportal = AllocPortal();
2620         nodeportal->plane = *plane;
2621
2622         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);
2623         nodeportal->numpoints = 4;
2624         side = 0;       // shut up compiler warning
2625         for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
2626         {
2627                 clipplane = portal->plane;
2628                 if (portal->nodes[0] == portal->nodes[1])
2629                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
2630                 if (portal->nodes[0] == node)
2631                         side = 0;
2632                 else if (portal->nodes[1] == node)
2633                 {
2634                         clipplane.dist = -clipplane.dist;
2635                         VectorNegate(clipplane.normal, clipplane.normal);
2636                         side = 1;
2637                 }
2638                 else
2639                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
2640
2641                 for (i = 0;i < nodeportal->numpoints*3;i++)
2642                         frontpoints[i] = nodeportal->points[i];
2643                 PolygonD_Divide(nodeportal->numpoints, frontpoints, clipplane.normal[0], clipplane.normal[1], clipplane.normal[2], clipplane.dist, 1.0/32.0, MAX_PORTALPOINTS, nodeportal->points, &nodeportal->numpoints, 0, NULL, NULL);
2644                 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
2645                         break;
2646         }
2647
2648         if (nodeportal->numpoints < 3)
2649         {
2650                 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
2651                 nodeportal->numpoints = 0;
2652         }
2653         else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
2654         {
2655                 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
2656                 nodeportal->numpoints = 0;
2657         }
2658         else
2659         {
2660                 AddPortalToNodes(nodeportal, front, back);
2661
2662                 // split the portals of this node along this node's plane and assign them to the children of this node
2663                 // (migrating the portals downward through the tree)
2664                 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
2665                 {
2666                         if (portal->nodes[0] == portal->nodes[1])
2667                                 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
2668                         if (portal->nodes[0] == node)
2669                                 side = 0;
2670                         else if (portal->nodes[1] == node)
2671                                 side = 1;
2672                         else
2673                                 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
2674                         nextportal = portal->next[side];
2675
2676                         other_node = portal->nodes[!side];
2677                         RemovePortalFromNodes(portal);
2678
2679                         // cut the portal into two portals, one on each side of the node plane
2680                         PolygonD_Divide(portal->numpoints, portal->points, plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, 1.0/32.0, MAX_PORTALPOINTS, frontpoints, &numfrontpoints, MAX_PORTALPOINTS, backpoints, &numbackpoints);
2681
2682                         if (!numfrontpoints)
2683                         {
2684                                 if (side == 0)
2685                                         AddPortalToNodes(portal, back, other_node);
2686                                 else
2687                                         AddPortalToNodes(portal, other_node, back);
2688                                 continue;
2689                         }
2690                         if (!numbackpoints)
2691                         {
2692                                 if (side == 0)
2693                                         AddPortalToNodes(portal, front, other_node);
2694                                 else
2695                                         AddPortalToNodes(portal, other_node, front);
2696                                 continue;
2697                         }
2698
2699                         // the portal is split
2700                         splitportal = AllocPortal();
2701                         temp = splitportal->chain;
2702                         *splitportal = *portal;
2703                         splitportal->chain = temp;
2704                         for (i = 0;i < numbackpoints*3;i++)
2705                                 splitportal->points[i] = backpoints[i];
2706                         splitportal->numpoints = numbackpoints;
2707                         for (i = 0;i < numfrontpoints*3;i++)
2708                                 portal->points[i] = frontpoints[i];
2709                         portal->numpoints = numfrontpoints;
2710
2711                         if (side == 0)
2712                         {
2713                                 AddPortalToNodes(portal, front, other_node);
2714                                 AddPortalToNodes(splitportal, back, other_node);
2715                         }
2716                         else
2717                         {
2718                                 AddPortalToNodes(portal, other_node, front);
2719                                 AddPortalToNodes(splitportal, other_node, back);
2720                         }
2721                 }
2722         }
2723
2724         Mod_Q1BSP_RecursiveNodePortals(front);
2725         Mod_Q1BSP_RecursiveNodePortals(back);
2726 }
2727
2728 static void Mod_Q1BSP_MakePortals(void)
2729 {
2730         portalchain = NULL;
2731         Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes);
2732         Mod_Q1BSP_FinalizePortals();
2733 }
2734
2735 static void Mod_Q1BSP_BuildLightmapUpdateChains(mempool_t *mempool, model_t *model)
2736 {
2737         int i, j, stylecounts[256], totalcount, remapstyles[256];
2738         msurface_t *surface;
2739         memset(stylecounts, 0, sizeof(stylecounts));
2740         for (i = 0;i < model->nummodelsurfaces;i++)
2741         {
2742                 surface = model->brush.data_surfaces + model->firstmodelsurface + i;
2743                 for (j = 0;j < MAXLIGHTMAPS;j++)
2744                         stylecounts[surface->styles[j]]++;
2745         }
2746         totalcount = 0;
2747         model->brushq1.light_styles = 0;
2748         for (i = 0;i < 255;i++)
2749         {
2750                 if (stylecounts[i])
2751                 {
2752                         remapstyles[i] = model->brushq1.light_styles++;
2753                         totalcount += stylecounts[i] + 1;
2754                 }
2755         }
2756         if (!totalcount)
2757                 return;
2758         model->brushq1.light_style = Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(qbyte));
2759         model->brushq1.light_stylevalue = Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(int));
2760         model->brushq1.light_styleupdatechains = Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(msurface_t **));
2761         model->brushq1.light_styleupdatechainsbuffer = Mem_Alloc(mempool, totalcount * sizeof(msurface_t *));
2762         model->brushq1.light_styles = 0;
2763         for (i = 0;i < 255;i++)
2764                 if (stylecounts[i])
2765                         model->brushq1.light_style[model->brushq1.light_styles++] = i;
2766         j = 0;
2767         for (i = 0;i < model->brushq1.light_styles;i++)
2768         {
2769                 model->brushq1.light_styleupdatechains[i] = model->brushq1.light_styleupdatechainsbuffer + j;
2770                 j += stylecounts[model->brushq1.light_style[i]] + 1;
2771         }
2772         for (i = 0;i < model->nummodelsurfaces;i++)
2773         {
2774                 surface = model->brush.data_surfaces + model->firstmodelsurface + i;
2775                 for (j = 0;j < MAXLIGHTMAPS;j++)
2776                         if (surface->styles[j] != 255)
2777                                 *model->brushq1.light_styleupdatechains[remapstyles[surface->styles[j]]]++ = surface;
2778         }
2779         j = 0;
2780         for (i = 0;i < model->brushq1.light_styles;i++)
2781         {
2782                 *model->brushq1.light_styleupdatechains[i] = NULL;
2783                 model->brushq1.light_styleupdatechains[i] = model->brushq1.light_styleupdatechainsbuffer + j;
2784                 j += stylecounts[model->brushq1.light_style[i]] + 1;
2785         }
2786 }
2787
2788 //Returns PVS data for a given point
2789 //(note: can return NULL)
2790 static qbyte *Mod_Q1BSP_GetPVS(model_t *model, const vec3_t p)
2791 {
2792         mnode_t *node;
2793         Mod_CheckLoaded(model);
2794         node = model->brush.data_nodes;
2795         while (node->plane)
2796                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
2797         if (((mleaf_t *)node)->clusterindex >= 0)
2798                 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
2799         else
2800                 return NULL;
2801 }
2802
2803 static void Mod_Q1BSP_FatPVS_RecursiveBSPNode(model_t *model, const vec3_t org, vec_t radius, qbyte *pvsbuffer, int pvsbytes, mnode_t *node)
2804 {
2805         while (node->plane)
2806         {
2807                 float d = PlaneDiff(org, node->plane);
2808                 if (d > radius)
2809                         node = node->children[0];
2810                 else if (d < -radius)
2811                         node = node->children[1];
2812                 else
2813                 {
2814                         // go down both sides
2815                         Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
2816                         node = node->children[1];
2817                 }
2818         }
2819         // if this leaf is in a cluster, accumulate the pvs bits
2820         if (((mleaf_t *)node)->clusterindex >= 0)
2821         {
2822                 int i;
2823                 qbyte *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
2824                 for (i = 0;i < pvsbytes;i++)
2825                         pvsbuffer[i] |= pvs[i];
2826         }
2827 }
2828
2829 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
2830 //of the given point.
2831 static int Mod_Q1BSP_FatPVS(model_t *model, const vec3_t org, vec_t radius, qbyte *pvsbuffer, int pvsbufferlength)
2832 {
2833         int bytes = model->brush.num_pvsclusterbytes;
2834         bytes = min(bytes, pvsbufferlength);
2835         if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
2836         {
2837                 memset(pvsbuffer, 0xFF, bytes);
2838                 return bytes;
2839         }
2840         memset(pvsbuffer, 0, bytes);
2841         Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes);
2842         return bytes;
2843 }
2844
2845 static void Mod_Q1BSP_RoundUpToHullSize(model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
2846 {
2847         vec3_t size;
2848         const hull_t *hull;
2849
2850         VectorSubtract(inmaxs, inmins, size);
2851         if (cmodel->brush.ishlbsp)
2852         {
2853                 if (size[0] < 3)
2854                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2855                 else if (size[0] <= 32)
2856                 {
2857                         if (size[2] < 54) // pick the nearest of 36 or 72
2858                                 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
2859                         else
2860                                 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
2861                 }
2862                 else
2863                         hull = &cmodel->brushq1.hulls[2]; // 64x64x64
2864         }
2865         else
2866         {
2867                 if (size[0] < 3)
2868                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2869                 else if (size[0] <= 32)
2870                         hull = &cmodel->brushq1.hulls[1]; // 32x32x56
2871                 else
2872                         hull = &cmodel->brushq1.hulls[2]; // 64x64x88
2873         }
2874         VectorCopy(inmins, outmins);
2875         VectorAdd(inmins, hull->clip_size, outmaxs);
2876 }
2877
2878 extern void R_Q1BSP_DrawSky(entity_render_t *ent);
2879 extern void R_Q1BSP_Draw(entity_render_t *ent);
2880 extern void R_Q1BSP_GetLightInfo(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, vec3_t outmins, vec3_t outmaxs, int *outclusterlist, qbyte *outclusterpvs, int *outnumclusterspointer, int *outsurfacelist, qbyte *outsurfacepvs, int *outnumsurfacespointer);
2881 extern void R_Q1BSP_DrawShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, int numsurfaces, const int *surfacelist, const vec3_t lightmins, const vec3_t lightmaxs);
2882 extern void R_Q1BSP_DrawLight(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativeeyeorigin, float lightradius, float *lightcolor, const matrix4x4_t *matrix_modeltolight, const matrix4x4_t *matrix_modeltoattenuationxyz, const matrix4x4_t *matrix_modeltoattenuationz, rtexture_t *lightcubemap, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int numsurfaces, const int *surfacelist);
2883 void Mod_Q1BSP_Load(model_t *mod, void *buffer)
2884 {
2885         int i, j, k;
2886         dheader_t *header;
2887         dmodel_t *bm;
2888         mempool_t *mainmempool;
2889         float dist, modelyawradius, modelradius, *vec;
2890         msurface_t *surface;
2891         int numshadowmeshtriangles;
2892
2893         mod->type = mod_brushq1;
2894
2895         header = (dheader_t *)buffer;
2896
2897         i = LittleLong(header->version);
2898         if (i != BSPVERSION && i != 30)
2899                 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife))", mod->name, i, BSPVERSION);
2900         mod->brush.ishlbsp = i == 30;
2901
2902         mod->soundfromcenter = true;
2903         mod->TraceBox = Mod_Q1BSP_TraceBox;
2904         mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
2905         mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
2906         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
2907         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
2908         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
2909         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
2910         mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
2911         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
2912         mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
2913         mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
2914         mod->brushq1.PointInLeaf = Mod_Q1BSP_PointInLeaf;
2915
2916         if (loadmodel->isworldmodel)
2917                 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
2918
2919 // swap all the lumps
2920         mod_base = (qbyte *)header;
2921
2922         header->version = LittleLong(header->version);
2923         for (i = 0;i < HEADER_LUMPS;i++)
2924         {
2925                 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
2926                 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
2927         }
2928
2929 // load into heap
2930
2931         // store which lightmap format to use
2932         mod->brushq1.lightmaprgba = r_lightmaprgba.integer;
2933
2934         Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
2935         Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
2936         Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
2937         Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
2938         Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
2939         Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
2940         Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
2941         Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
2942         Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
2943         Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
2944         Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
2945         // load submodels before leafs because they contain the number of vis leafs
2946         Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS]);
2947         Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
2948         Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
2949         Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES]);
2950
2951         if (!mod->brushq1.lightdata)
2952                 mod->brush.LightPoint = NULL;
2953
2954         if (mod->brushq1.data_compressedpvs)
2955                 Mem_Free(mod->brushq1.data_compressedpvs);
2956         mod->brushq1.data_compressedpvs = NULL;
2957         mod->brushq1.num_compressedpvs = 0;
2958
2959         Mod_Q1BSP_MakeHull0();
2960         Mod_Q1BSP_MakePortals();
2961
2962         mod->numframes = 2;             // regular and alternate animation
2963         mod->numskins = 1;
2964
2965         mainmempool = mod->mempool;
2966
2967         Mod_Q1BSP_LoadLightList();
2968
2969         // make a single combined shadow mesh to allow optimized shadow volume creation
2970         numshadowmeshtriangles = 0;
2971         for (j = 0, surface = loadmodel->brush.data_surfaces;j < loadmodel->brush.num_surfaces;j++, surface++)
2972         {
2973                 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
2974                 numshadowmeshtriangles += surface->mesh.num_triangles;
2975         }
2976         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
2977         for (j = 0, surface = loadmodel->brush.data_surfaces;j < loadmodel->brush.num_surfaces;j++, surface++)
2978                 Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, surface->mesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->mesh.num_triangles, surface->mesh.data_element3i);
2979         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true);
2980         Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
2981
2982         if (loadmodel->brush.numsubmodels)
2983                 loadmodel->brush.submodels = Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
2984
2985         if (loadmodel->isworldmodel)
2986         {
2987                 // clear out any stale submodels or worldmodels lying around
2988                 // if we did this clear before now, an error might abort loading and
2989                 // leave things in a bad state
2990                 Mod_RemoveStaleWorldModels(loadmodel);
2991         }
2992
2993         // LordHavoc: to clear the fog around the original quake submodel code, I
2994         // will explain:
2995         // first of all, some background info on the submodels:
2996         // model 0 is the map model (the world, named maps/e1m1.bsp for example)
2997         // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
2998         // now the weird for loop itself:
2999         // the loop functions in an odd way, on each iteration it sets up the
3000         // current 'mod' model (which despite the confusing code IS the model of
3001         // the number i), at the end of the loop it duplicates the model to become
3002         // the next submodel, and loops back to set up the new submodel.
3003
3004         // LordHavoc: now the explanation of my sane way (which works identically):
3005         // set up the world model, then on each submodel copy from the world model
3006         // and set up the submodel with the respective model info.
3007         for (i = 0;i < mod->brush.numsubmodels;i++)
3008         {
3009                 // LordHavoc: this code was originally at the end of this loop, but
3010                 // has been transformed to something more readable at the start here.
3011
3012                 if (i > 0)
3013                 {
3014                         char name[10];
3015                         // LordHavoc: only register submodels if it is the world
3016                         // (prevents external bsp models from replacing world submodels with
3017                         //  their own)
3018                         if (!loadmodel->isworldmodel)
3019                                 continue;
3020                         // duplicate the basic information
3021                         sprintf(name, "*%i", i);
3022                         mod = Mod_FindName(name);
3023                         // copy the base model to this one
3024                         *mod = *loadmodel;
3025                         // rename the clone back to its proper name
3026                         strcpy(mod->name, name);
3027                         // textures and memory belong to the main model
3028                         mod->texturepool = NULL;
3029                         mod->mempool = NULL;
3030                 }
3031
3032                 mod->brush.submodel = i;
3033
3034                 if (loadmodel->brush.submodels)
3035                         loadmodel->brush.submodels[i] = mod;
3036
3037                 bm = &mod->brushq1.submodels[i];
3038
3039                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3040                 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3041                 {
3042                         mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3043                         mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3044                 }
3045
3046                 mod->firstmodelsurface = bm->firstface;
3047                 mod->nummodelsurfaces = bm->numfaces;
3048
3049                 // make the model surface list (used by shadowing/lighting)
3050                 mod->surfacelist = Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->surfacelist));
3051                 for (j = 0;j < mod->nummodelsurfaces;j++)
3052                         mod->surfacelist[j] = mod->firstmodelsurface + j;
3053
3054                 // this gets altered below if sky is used
3055                 mod->DrawSky = NULL;
3056                 mod->Draw = R_Q1BSP_Draw;
3057                 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3058                 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3059                 mod->DrawLight = R_Q1BSP_DrawLight;
3060                 if (i != 0)
3061                 {
3062                         mod->brush.GetPVS = NULL;
3063                         mod->brush.FatPVS = NULL;
3064                         mod->brush.BoxTouchingPVS = NULL;
3065                         mod->brush.BoxTouchingVisibleLeafs = NULL;
3066                         mod->brush.LightPoint = NULL;
3067                         mod->brush.AmbientSoundLevelsForPoint = NULL;
3068                 }
3069                 Mod_Q1BSP_BuildLightmapUpdateChains(loadmodel->mempool, mod);
3070                 if (mod->nummodelsurfaces)
3071                 {
3072                         // LordHavoc: calculate bmodel bounding box rather than trusting what it says
3073                         mod->normalmins[0] = mod->normalmins[1] = mod->normalmins[2] = 1000000000.0f;
3074                         mod->normalmaxs[0] = mod->normalmaxs[1] = mod->normalmaxs[2] = -1000000000.0f;
3075                         modelyawradius = 0;
3076                         modelradius = 0;
3077                         for (j = 0, surface = &mod->brush.data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3078                         {
3079                                 // we only need to have a drawsky function if it is used(usually only on world model)
3080                                 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3081                                         mod->DrawSky = R_Q1BSP_DrawSky;
3082                                 // calculate bounding shapes
3083                                 for (k = 0, vec = surface->mesh.data_vertex3f;k < surface->mesh.num_vertices;k++, vec += 3)
3084                                 {
3085                                         if (mod->normalmins[0] > vec[0]) mod->normalmins[0] = vec[0];
3086                                         if (mod->normalmins[1] > vec[1]) mod->normalmins[1] = vec[1];
3087                                         if (mod->normalmins[2] > vec[2]) mod->normalmins[2] = vec[2];
3088                                         if (mod->normalmaxs[0] < vec[0]) mod->normalmaxs[0] = vec[0];
3089                                         if (mod->normalmaxs[1] < vec[1]) mod->normalmaxs[1] = vec[1];
3090                                         if (mod->normalmaxs[2] < vec[2]) mod->normalmaxs[2] = vec[2];
3091                                         dist = vec[0]*vec[0]+vec[1]*vec[1];
3092                                         if (modelyawradius < dist)
3093                                                 modelyawradius = dist;
3094                                         dist += vec[2]*vec[2];
3095                                         if (modelradius < dist)
3096                                                 modelradius = dist;
3097                                 }
3098                         }
3099                         modelyawradius = sqrt(modelyawradius);
3100                         modelradius = sqrt(modelradius);
3101                         mod->yawmins[0] = mod->yawmins[1] = - (mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius);
3102                         mod->yawmins[2] = mod->normalmins[2];
3103                         mod->yawmaxs[2] = mod->normalmaxs[2];
3104                         mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3105                         mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3106                         mod->radius = modelradius;
3107                         mod->radius2 = modelradius * modelradius;
3108                 }
3109                 else
3110                 {
3111                         // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3112                         Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3113                 }
3114                 //mod->brushq1.num_visleafs = bm->visleafs;
3115         }
3116
3117         Mod_Q1BSP_LoadMapBrushes();
3118
3119         //Mod_Q1BSP_ProcessLightList();
3120
3121         if (developer.integer)
3122                 Con_Printf("Some stats for q1bsp model \"%s\": %i faces, %i nodes, %i leafs, %i visleafs, %i visleafportals\n", loadmodel->name, loadmodel->brush.num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brushq1.submodels[i].visleafs, loadmodel->brush.num_portals);
3123 }
3124
3125 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3126 {
3127 }
3128
3129 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3130 {
3131 /*
3132         d_t *in;
3133         m_t *out;
3134         int i, count;
3135
3136         in = (void *)(mod_base + l->fileofs);
3137         if (l->filelen % sizeof(*in))
3138                 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3139         count = l->filelen / sizeof(*in);
3140         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3141
3142         loadmodel-> = out;
3143         loadmodel->num = count;
3144
3145         for (i = 0;i < count;i++, in++, out++)
3146         {
3147         }
3148 */
3149 }
3150
3151 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3152 {
3153 /*
3154         d_t *in;
3155         m_t *out;
3156         int i, count;
3157
3158         in = (void *)(mod_base + l->fileofs);
3159         if (l->filelen % sizeof(*in))
3160                 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3161         count = l->filelen / sizeof(*in);
3162         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3163
3164         loadmodel-> = out;
3165         loadmodel->num = count;
3166
3167         for (i = 0;i < count;i++, in++, out++)
3168         {
3169         }
3170 */
3171 }
3172
3173 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3174 {
3175 /*
3176         d_t *in;
3177         m_t *out;
3178         int i, count;
3179
3180         in = (void *)(mod_base + l->fileofs);
3181         if (l->filelen % sizeof(*in))
3182                 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3183         count = l->filelen / sizeof(*in);
3184         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3185
3186         loadmodel-> = out;
3187         loadmodel->num = count;
3188
3189         for (i = 0;i < count;i++, in++, out++)
3190         {
3191         }
3192 */
3193 }
3194
3195 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3196 {
3197 /*
3198         d_t *in;
3199         m_t *out;
3200         int i, count;
3201
3202         in = (void *)(mod_base + l->fileofs);
3203         if (l->filelen % sizeof(*in))
3204                 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3205         count = l->filelen / sizeof(*in);
3206         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3207
3208         loadmodel-> = out;
3209         loadmodel->num = count;
3210
3211         for (i = 0;i < count;i++, in++, out++)
3212         {
3213         }
3214 */
3215 }
3216
3217 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3218 {
3219 /*
3220         d_t *in;
3221         m_t *out;
3222         int i, count;
3223
3224         in = (void *)(mod_base + l->fileofs);
3225         if (l->filelen % sizeof(*in))
3226                 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3227         count = l->filelen / sizeof(*in);
3228         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3229
3230         loadmodel-> = out;
3231         loadmodel->num = count;
3232
3233         for (i = 0;i < count;i++, in++, out++)
3234         {
3235         }
3236 */
3237 }
3238
3239 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3240 {
3241 /*
3242         d_t *in;
3243         m_t *out;
3244         int i, count;
3245
3246         in = (void *)(mod_base + l->fileofs);
3247         if (l->filelen % sizeof(*in))
3248                 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3249         count = l->filelen / sizeof(*in);
3250         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3251
3252         loadmodel-> = out;
3253         loadmodel->num = count;
3254
3255         for (i = 0;i < count;i++, in++, out++)
3256         {
3257         }
3258 */
3259 }
3260
3261 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3262 {
3263 /*
3264         d_t *in;
3265         m_t *out;
3266         int i, count;
3267
3268         in = (void *)(mod_base + l->fileofs);
3269         if (l->filelen % sizeof(*in))
3270                 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3271         count = l->filelen / sizeof(*in);
3272         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3273
3274         loadmodel-> = out;
3275         loadmodel->num = count;
3276
3277         for (i = 0;i < count;i++, in++, out++)
3278         {
3279         }
3280 */
3281 }
3282
3283 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3284 {
3285 /*
3286         d_t *in;
3287         m_t *out;
3288         int i, count;
3289
3290         in = (void *)(mod_base + l->fileofs);
3291         if (l->filelen % sizeof(*in))
3292                 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3293         count = l->filelen / sizeof(*in);
3294         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3295
3296         loadmodel-> = out;
3297         loadmodel->num = count;
3298
3299         for (i = 0;i < count;i++, in++, out++)
3300         {
3301         }
3302 */
3303 }
3304
3305 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3306 {
3307 /*
3308         d_t *in;
3309         m_t *out;
3310         int i, count;
3311
3312         in = (void *)(mod_base + l->fileofs);
3313         if (l->filelen % sizeof(*in))
3314                 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3315         count = l->filelen / sizeof(*in);
3316         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3317
3318         loadmodel-> = out;
3319         loadmodel->num = count;
3320
3321         for (i = 0;i < count;i++, in++, out++)
3322         {
3323         }
3324 */
3325 }
3326
3327 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3328 {
3329 /*
3330         d_t *in;
3331         m_t *out;
3332         int i, count;
3333
3334         in = (void *)(mod_base + l->fileofs);
3335         if (l->filelen % sizeof(*in))
3336                 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3337         count = l->filelen / sizeof(*in);
3338         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3339
3340         loadmodel-> = out;
3341         loadmodel->num = count;
3342
3343         for (i = 0;i < count;i++, in++, out++)
3344         {
3345         }
3346 */
3347 }
3348
3349 static void Mod_Q2BSP_LoadEdges(lump_t *l)
3350 {
3351 /*
3352         d_t *in;
3353         m_t *out;
3354         int i, count;
3355
3356         in = (void *)(mod_base + l->fileofs);
3357         if (l->filelen % sizeof(*in))
3358                 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
3359         count = l->filelen / sizeof(*in);
3360         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3361
3362         loadmodel-> = out;
3363         loadmodel->num = count;
3364
3365         for (i = 0;i < count;i++, in++, out++)
3366         {
3367         }
3368 */
3369 }
3370
3371 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
3372 {
3373 /*
3374         d_t *in;
3375         m_t *out;
3376         int i, count;
3377
3378         in = (void *)(mod_base + l->fileofs);
3379         if (l->filelen % sizeof(*in))
3380                 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
3381         count = l->filelen / sizeof(*in);
3382         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3383
3384         loadmodel-> = out;
3385         loadmodel->num = count;
3386
3387         for (i = 0;i < count;i++, in++, out++)
3388         {
3389         }
3390 */
3391 }
3392
3393 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
3394 {
3395 /*
3396         d_t *in;
3397         m_t *out;
3398         int i, count;
3399
3400         in = (void *)(mod_base + l->fileofs);
3401         if (l->filelen % sizeof(*in))
3402                 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
3403         count = l->filelen / sizeof(*in);
3404         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3405
3406         loadmodel-> = out;
3407         loadmodel->num = count;
3408
3409         for (i = 0;i < count;i++, in++, out++)
3410         {
3411         }
3412 */
3413 }
3414
3415 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
3416 {
3417 /*
3418         d_t *in;
3419         m_t *out;
3420         int i, count;
3421
3422         in = (void *)(mod_base + l->fileofs);
3423         if (l->filelen % sizeof(*in))
3424                 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
3425         count = l->filelen / sizeof(*in);
3426         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3427
3428         loadmodel-> = out;
3429         loadmodel->num = count;
3430
3431         for (i = 0;i < count;i++, in++, out++)
3432         {
3433         }
3434 */
3435 }
3436
3437 static void Mod_Q2BSP_LoadAreas(lump_t *l)
3438 {
3439 /*
3440         d_t *in;
3441         m_t *out;
3442         int i, count;
3443
3444         in = (void *)(mod_base + l->fileofs);
3445         if (l->filelen % sizeof(*in))
3446                 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
3447         count = l->filelen / sizeof(*in);
3448         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3449
3450         loadmodel-> = out;
3451         loadmodel->num = count;
3452
3453         for (i = 0;i < count;i++, in++, out++)
3454         {
3455         }
3456 */
3457 }
3458
3459 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
3460 {
3461 /*
3462         d_t *in;
3463         m_t *out;
3464         int i, count;
3465
3466         in = (void *)(mod_base + l->fileofs);
3467         if (l->filelen % sizeof(*in))
3468                 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
3469         count = l->filelen / sizeof(*in);
3470         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3471
3472         loadmodel-> = out;
3473         loadmodel->num = count;
3474
3475         for (i = 0;i < count;i++, in++, out++)
3476         {
3477         }
3478 */
3479 }
3480
3481 static void Mod_Q2BSP_LoadModels(lump_t *l)
3482 {
3483 /*
3484         d_t *in;
3485         m_t *out;
3486         int i, count;
3487
3488         in = (void *)(mod_base + l->fileofs);
3489         if (l->filelen % sizeof(*in))
3490                 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
3491         count = l->filelen / sizeof(*in);
3492         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3493
3494         loadmodel-> = out;
3495         loadmodel->num = count;
3496
3497         for (i = 0;i < count;i++, in++, out++)
3498         {
3499         }
3500 */
3501 }
3502
3503 void static Mod_Q2BSP_Load(model_t *mod, void *buffer)
3504 {
3505         int i;
3506         q2dheader_t *header;
3507
3508         Host_Error("Mod_Q2BSP_Load: not yet implemented\n");
3509
3510         mod->type = mod_brushq2;
3511
3512         header = (q2dheader_t *)buffer;
3513
3514         i = LittleLong(header->version);
3515         if (i != Q2BSPVERSION)
3516                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
3517         mod->brush.ishlbsp = false;
3518         if (loadmodel->isworldmodel)
3519                 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
3520
3521         mod_base = (qbyte *)header;
3522
3523         // swap all the lumps
3524         for (i = 0;i < (int) sizeof(*header) / 4;i++)
3525                 ((int *)header)[i] = LittleLong(((int *)header)[i]);
3526
3527         // store which lightmap format to use
3528         mod->brushq1.lightmaprgba = r_lightmaprgba.integer;
3529
3530         Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
3531         Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
3532         Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
3533         Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
3534         Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
3535         Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
3536         Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
3537         Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
3538         Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
3539         Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
3540         Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
3541         Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
3542         Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
3543         Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
3544         Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
3545         Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
3546         Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
3547         // LordHavoc: must go last because this makes the submodels
3548         Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
3549 }
3550
3551 static int Mod_Q3BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents);
3552 static int Mod_Q3BSP_NativeContentsFromSuperContents(model_t *model, int supercontents);
3553
3554 static void Mod_Q3BSP_LoadEntities(lump_t *l)
3555 {
3556         const char *data;
3557         char key[128], value[4096];
3558         float v[3];
3559         loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
3560         loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
3561         loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
3562         if (!l->filelen)
3563                 return;
3564         loadmodel->brush.entities = Mem_Alloc(loadmodel->mempool, l->filelen);
3565         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
3566         data = loadmodel->brush.entities;
3567         // some Q3 maps override the lightgrid_cellsize with a worldspawn key
3568         if (data && COM_ParseToken(&data, false) && com_token[0] == '{')
3569         {
3570                 while (1)
3571                 {
3572                         if (!COM_ParseToken(&data, false))
3573                                 break; // error
3574                         if (com_token[0] == '}')
3575                                 break; // end of worldspawn
3576                         if (com_token[0] == '_')
3577                                 strcpy(key, com_token + 1);
3578                         else
3579                                 strcpy(key, com_token);
3580                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
3581                                 key[strlen(key)-1] = 0;
3582                         if (!COM_ParseToken(&data, false))
3583                                 break; // error
3584                         strcpy(value, com_token);
3585                         if (!strcmp("gridsize", key))
3586                         {
3587                                 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
3588                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
3589                         }
3590                 }
3591         }
3592 }
3593
3594 static void Mod_Q3BSP_LoadTextures(lump_t *l)
3595 {
3596         q3dtexture_t *in;
3597         texture_t *out;
3598         int i, count;
3599         int j, c;
3600         fssearch_t *search;
3601         char *f;
3602         const char *text;
3603         int flags, flags2, numparameters, passnumber;
3604         char shadername[Q3PATHLENGTH];
3605         char sky[Q3PATHLENGTH];
3606         char firstpasstexturename[Q3PATHLENGTH];
3607         char parameter[4][Q3PATHLENGTH];
3608
3609         in = (void *)(mod_base + l->fileofs);
3610         if (l->filelen % sizeof(*in))
3611                 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
3612         count = l->filelen / sizeof(*in);
3613         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3614
3615         loadmodel->brush.data_textures = out;
3616         loadmodel->brush.num_textures = count;
3617
3618         for (i = 0;i < count;i++, in++, out++)
3619         {
3620                 strlcpy (out->name, in->name, sizeof (out->name));
3621                 out->surfaceflags = LittleLong(in->surfaceflags);
3622                 out->supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in->contents));
3623                 out->surfaceparms = -1;
3624         }
3625
3626         // do a quick parse of shader files to get surfaceparms
3627         if ((search = FS_Search("scripts/*.shader", true, false)))
3628         {
3629                 for (i = 0;i < search->numfilenames;i++)
3630                 {
3631                         if ((f = FS_LoadFile(search->filenames[i], tempmempool, false)))
3632                         {
3633                                 text = f;
3634                                 while (COM_ParseToken(&text, false))
3635                                 {
3636                                         strlcpy (shadername, com_token, sizeof (shadername));
3637                                         flags = 0;
3638                                         flags2 = 0;
3639                                         sky[0] = 0;
3640                                         passnumber = 0;
3641                                         firstpasstexturename[0] = 0;
3642                                         if (COM_ParseToken(&text, false) && !strcasecmp(com_token, "{"))
3643                                         {
3644                                                 while (COM_ParseToken(&text, false))
3645                                                 {
3646                                                         if (!strcasecmp(com_token, "}"))
3647                                                                 break;
3648                                                         else if (!strcasecmp(com_token, "{"))
3649                                                         {
3650                                                                 while (COM_ParseToken(&text, false))
3651                                                                 {
3652                                                                         if (!strcasecmp(com_token, "}"))
3653                                                                                 break;
3654                                                                         if (!strcasecmp(com_token, "\n"))
3655                                                                                 continue;
3656                                                                         numparameters = 0;
3657                                                                         for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
3658                                                                         {
3659                                                                                 if (j < 4)
3660                                                                                 {
3661                                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
3662                                                                                         numparameters = j + 1;
3663                                                                                 }
3664                                                                                 if (!COM_ParseToken(&text, true))
3665                                                                                         break;
3666                                                                         }
3667                                                                         if (developer.integer >= 2)
3668                                                                         {
3669                                                                                 Con_Printf("%s %i: ", shadername, passnumber);
3670                                                                                 for (j = 0;j < numparameters;j++)
3671                                                                                         Con_Printf(" %s", parameter[j]);
3672                                                                                 Con_Print("\n");
3673                                                                         }
3674                                                                         if (passnumber == 0 && numparameters >= 1)
3675                                                                         {
3676                                                                                 if (!strcasecmp(parameter[0], "blendfunc"))
3677                                                                                 {
3678                                                                                         if (numparameters == 2 && !strcasecmp(parameter[1], "add"))
3679                                                                                                 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3680                                                                                         else if (numparameters == 3 && !strcasecmp(parameter[1], "gl_one") && !strcasecmp(parameter[2], "gl_one"))
3681                                                                                                 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3682                                                                                         else if (numparameters == 3 && !strcasecmp(parameter[1], "gl_src_alpha") && !strcasecmp(parameter[2], "gl_one"))
3683                                                                                                 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3684                                                                                 }
3685                                                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
3686                                                                                         strlcpy(firstpasstexturename, parameter[1], sizeof(firstpasstexturename));
3687                                                                                 else if (numparameters >= 3 && !strcasecmp(parameter[0], "animmap"))
3688                                                                                         strlcpy(firstpasstexturename, parameter[2], sizeof(firstpasstexturename));
3689                                                                         }
3690                                                                         if (!strcasecmp(parameter[0], "alphafunc"))
3691                                                                                 flags2 |= Q3TEXTUREFLAG_ALPHATEST;
3692                                                                         // break out a level if it was }
3693                                                                         if (!strcasecmp(com_token, "}"))
3694                                                                                 break;
3695                                                                 }
3696                                                                 passnumber++;
3697                                                                 continue;
3698                                                         }
3699                                                         numparameters = 0;
3700                                                         for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
3701                                                         {
3702                                                                 if (j < 4)
3703                                                                 {
3704                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
3705                                                                         numparameters = j + 1;
3706                                                                 }
3707                                                                 if (!COM_ParseToken(&text, true))
3708                                                                         break;
3709                                                         }
3710                                                         if (i == 0 && !strcasecmp(com_token, "}"))
3711                                                                 break;
3712                                                         if (developer.integer >= 2)
3713                                                         {
3714                                                                 Con_Printf("%s: ", shadername);
3715                                                                 for (j = 0;j < numparameters;j++)
3716                                                                         Con_Printf(" %s", parameter[j]);
3717                                                                 Con_Print("\n");
3718                                                         }
3719                                                         if (numparameters < 1)
3720                                                                 continue;
3721                                                         if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
3722                                                         {
3723                                                                 if (!strcasecmp(parameter[1], "alphashadow"))
3724                                                                         flags |= Q3SURFACEPARM_ALPHASHADOW;
3725                                                                 else if (!strcasecmp(parameter[1], "areaportal"))
3726                                                                         flags |= Q3SURFACEPARM_AREAPORTAL;
3727                                                                 else if (!strcasecmp(parameter[1], "clusterportal"))
3728                                                                         flags |= Q3SURFACEPARM_CLUSTERPORTAL;
3729                                                                 else if (!strcasecmp(parameter[1], "detail"))
3730                                                                         flags |= Q3SURFACEPARM_DETAIL;
3731                                                                 else if (!strcasecmp(parameter[1], "donotenter"))
3732                                                                         flags |= Q3SURFACEPARM_DONOTENTER;
3733                                                                 else if (!strcasecmp(parameter[1], "fog"))
3734                                                                         flags |= Q3SURFACEPARM_FOG;
3735                                                                 else if (!strcasecmp(parameter[1], "lava"))
3736                                                                         flags |= Q3SURFACEPARM_LAVA;
3737                                                                 else if (!strcasecmp(parameter[1], "lightfilter"))
3738                                                                         flags |= Q3SURFACEPARM_LIGHTFILTER;
3739                                                                 else if (!strcasecmp(parameter[1], "metalsteps"))
3740                                                                         flags |= Q3SURFACEPARM_METALSTEPS;
3741                                                                 else if (!strcasecmp(parameter[1], "nodamage"))
3742                                                                         flags |= Q3SURFACEPARM_NODAMAGE;
3743                                                                 else if (!strcasecmp(parameter[1], "nodlight"))
3744                                                                         flags |= Q3SURFACEPARM_NODLIGHT;
3745                                                                 else if (!strcasecmp(parameter[1], "nodraw"))
3746                                                                         flags |= Q3SURFACEPARM_NODRAW;
3747                                                                 else if (!strcasecmp(parameter[1], "nodrop"))
3748                                                                         flags |= Q3SURFACEPARM_NODROP;
3749                                                                 else if (!strcasecmp(parameter[1], "noimpact"))
3750                                                                         flags |= Q3SURFACEPARM_NOIMPACT;
3751                                                                 else if (!strcasecmp(parameter[1], "nolightmap"))
3752                                                                         flags |= Q3SURFACEPARM_NOLIGHTMAP;
3753                                                                 else if (!strcasecmp(parameter[1], "nomarks"))
3754                                                                         flags |= Q3SURFACEPARM_NOMARKS;
3755                                                                 else if (!strcasecmp(parameter[1], "nomipmaps"))
3756                                                                         flags |= Q3SURFACEPARM_NOMIPMAPS;
3757                                                                 else if (!strcasecmp(parameter[1], "nonsolid"))
3758                                                                         flags |= Q3SURFACEPARM_NONSOLID;
3759                                                                 else if (!strcasecmp(parameter[1], "origin"))
3760                                                                         flags |= Q3SURFACEPARM_ORIGIN;
3761                                                                 else if (!strcasecmp(parameter[1], "playerclip"))
3762                                                                         flags |= Q3SURFACEPARM_PLAYERCLIP;
3763                                                                 else if (!strcasecmp(parameter[1], "sky"))
3764                                                                         flags |= Q3SURFACEPARM_SKY;
3765                                                                 else if (!strcasecmp(parameter[1], "slick"))
3766                                                                         flags |= Q3SURFACEPARM_SLICK;
3767                                                                 else if (!strcasecmp(parameter[1], "slime"))
3768                                                                         flags |= Q3SURFACEPARM_SLIME;
3769                                                                 else if (!strcasecmp(parameter[1], "structural"))
3770                                                                         flags |= Q3SURFACEPARM_STRUCTURAL;
3771                                                                 else if (!strcasecmp(parameter[1], "trans"))
3772                                                                         flags |= Q3SURFACEPARM_TRANS;
3773                                                                 else if (!strcasecmp(parameter[1], "water"))
3774                                                                         flags |= Q3SURFACEPARM_WATER;
3775                                                                 else if (!strcasecmp(parameter[1], "pointlight"))
3776                                                                         flags |= Q3SURFACEPARM_POINTLIGHT;
3777                                                                 else
3778                                                                         Con_Printf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[i], parameter[1]);
3779                                                         }
3780                                                         else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
3781                                                                 strlcpy(sky, parameter[1], sizeof(sky));
3782                                                         else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
3783                                                         {
3784                                                                 if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
3785                                                                         strlcpy(sky, parameter[1], sizeof(sky));
3786                                                         }
3787                                                         else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
3788                                                         {
3789                                                                 if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
3790                                                                         flags2 |= Q3TEXTUREFLAG_TWOSIDED;
3791                                                         }
3792                                                         else if (!strcasecmp(parameter[0], "nomipmaps"))
3793                                                                 flags2 |= Q3TEXTUREFLAG_NOMIPMAPS;
3794                                                         else if (!strcasecmp(parameter[0], "nopicmip"))
3795                                                                 flags2 |= Q3TEXTUREFLAG_NOPICMIP;
3796                                                         else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
3797                                                         {
3798                                                                 if (!strcasecmp(parameter[1], "autosprite") && numparameters == 2)
3799                                                                         flags2 |= Q3TEXTUREFLAG_AUTOSPRITE;
3800                                                                 if (!strcasecmp(parameter[1], "autosprite2") && numparameters == 2)
3801                                                                         flags2 |= Q3TEXTUREFLAG_AUTOSPRITE2;
3802                                                         }
3803                                                 }
3804                                                 // force transparent render path for a number of odd
3805                                                 // shader effects to avoid bogging down the normal
3806                                                 // render path unnecessarily
3807                                                 if (flags2 & (Q3TEXTUREFLAG_ADDITIVE | Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2 | Q3TEXTUREFLAG_ALPHATEST))
3808                                                         flags |= Q3SURFACEPARM_TRANS;
3809                                                 // add shader to list (shadername and flags)
3810                                                 // actually here we just poke into the texture settings
3811                                                 for (j = 0, out = loadmodel->brush.data_textures;j < loadmodel->brush.num_textures;j++, out++)
3812                                                 {
3813                                                         if (!strcasecmp(out->name, shadername))
3814                                                         {
3815                                                                 out->surfaceparms = flags;
3816                                                                 out->textureflags = flags2;
3817                                                                 out->basematerialflags = 0;
3818                                                                 if (out->surfaceparms & Q3SURFACEPARM_NODRAW)
3819                                                                         out->basematerialflags |= MATERIALFLAG_NODRAW;
3820                                                                 else if (out->surfaceparms & Q3SURFACEPARM_SKY)
3821                                                                         out->basematerialflags |= MATERIALFLAG_SKY;
3822                                                                 else if (out->surfaceparms & Q3SURFACEPARM_LAVA)
3823                                                                         out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_FULLBRIGHT;
3824                                                                 else if (out->surfaceparms & Q3SURFACEPARM_SLIME)
3825                                                                         out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_WATERALPHA;
3826                                                                 else if (out->surfaceparms & Q3SURFACEPARM_WATER)
3827                                                                         out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_WATERALPHA;
3828                                                                 else
3829                                                                         out->basematerialflags |= MATERIALFLAG_WALL;
3830                                                                 if (out->surfaceparms & Q3SURFACEPARM_TRANS)
3831                                                                         out->basematerialflags |= MATERIALFLAG_TRANSPARENT;
3832                                                                 if (out->textureflags & Q3TEXTUREFLAG_ADDITIVE)
3833                                                                         out->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_TRANSPARENT;
3834                                                                 strlcpy(out->firstpasstexturename, firstpasstexturename, sizeof(out->firstpasstexturename));
3835                                                                 if ((flags & Q3SURFACEPARM_SKY) && sky[0])
3836                                                                 {
3837                                                                         // quake3 seems to append a _ to the skybox name, so this must do so as well
3838                                                                         dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", sky);
3839                                                                 }
3840                                                         }
3841                                                 }
3842                                         }
3843                                         else
3844                                         {
3845                                                 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[i], com_token);
3846                                                 goto parseerror;
3847                                         }
3848                                 }
3849 parseerror:
3850                                 Mem_Free(f);
3851                         }
3852                 }
3853         }
3854
3855         c = 0;
3856         for (j = 0, out = loadmodel->brush.data_textures;j < loadmodel->brush.num_textures;j++, out++)
3857         {
3858                 if (out->surfaceparms == -1)
3859                 {
3860                         c++;
3861                         Con_DPrintf("%s: No shader found for texture \"%s\"\n", loadmodel->name, out->name);
3862                         out->surfaceparms = 0;
3863                         if (out->surfaceflags & Q3SURFACEFLAG_NODRAW)
3864                                 out->basematerialflags |= MATERIALFLAG_NODRAW;
3865                         else if (out->surfaceflags & Q3SURFACEFLAG_SKY)
3866                                 out->basematerialflags |= MATERIALFLAG_SKY;
3867                         else
3868                                 out->basematerialflags |= MATERIALFLAG_WALL;
3869                         // these are defaults
3870                         //if (!strncmp(out->name, "textures/skies/", 15))
3871                         //      out->surfaceparms |= Q3SURFACEPARM_SKY;
3872                         //if (!strcmp(out->name, "caulk") || !strcmp(out->name, "common/caulk") || !strcmp(out->name, "textures/common/caulk")
3873                         // || !strcmp(out->name, "nodraw") || !strcmp(out->name, "common/nodraw") || !strcmp(out->name, "textures/common/nodraw"))
3874                         //      out->surfaceparms |= Q3SURFACEPARM_NODRAW;
3875                         //if (R_TextureHasAlpha(out->skin.base))
3876                         //      out->surfaceparms |= Q3SURFACEPARM_TRANS;
3877                 }
3878                 if (!Mod_LoadSkinFrame(&out->skin, out->name, (((out->textureflags & Q3TEXTUREFLAG_NOMIPMAPS) || (out->surfaceparms & Q3SURFACEPARM_NOMIPMAPS)) ? 0 : TEXF_MIPMAP) | TEXF_ALPHA | TEXF_PRECACHE | (out->textureflags & Q3TEXTUREFLAG_NOPICMIP ? 0 : TEXF_PICMIP), false, false, true))
3879                         if (!Mod_LoadSkinFrame(&out->skin, out->firstpasstexturename, (((out->textureflags & Q3TEXTUREFLAG_NOMIPMAPS) || (out->surfaceparms & Q3SURFACEPARM_NOMIPMAPS)) ? 0 : TEXF_MIPMAP) | TEXF_ALPHA | TEXF_PRECACHE | (out->textureflags & Q3TEXTUREFLAG_NOPICMIP ? 0 : TEXF_PICMIP), false, false, true))
3880                                 Con_Printf("%s: texture loading for shader \"%s\" failed (first layer \"%s\" not found either)\n", loadmodel->name, out->name, out->firstpasstexturename);
3881                 if (out->skin.fog)
3882                         out->basematerialflags |= (MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT);
3883                 // no animation
3884                 out->currentframe = out;
3885         }
3886         if (c)
3887                 Con_DPrintf("%s: %i textures missing shaders\n", loadmodel->name, c);
3888 }
3889
3890 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
3891 {
3892         q3dplane_t *in;
3893         mplane_t *out;
3894         int i, count;
3895
3896         in = (void *)(mod_base + l->fileofs);
3897         if (l->filelen % sizeof(*in))
3898                 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3899         count = l->filelen / sizeof(*in);
3900         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3901
3902         loadmodel->brush.data_planes = out;
3903         loadmodel->brush.num_planes = count;
3904
3905         for (i = 0;i < count;i++, in++, out++)
3906         {
3907                 out->normal[0] = LittleLong(in->normal[0]);
3908                 out->normal[1] = LittleLong(in->normal[1]);
3909                 out->normal[2] = LittleLong(in->normal[2]);
3910                 out->dist = LittleLong(in->dist);
3911                 PlaneClassify(out);
3912         }
3913 }
3914
3915 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
3916 {
3917         q3dbrushside_t *in;
3918         q3mbrushside_t *out;
3919         int i, n, count;
3920
3921         in = (void *)(mod_base + l->fileofs);
3922         if (l->filelen % sizeof(*in))
3923                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
3924         count = l->filelen / sizeof(*in);
3925         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3926
3927         loadmodel->brush.data_brushsides = out;
3928         loadmodel->brush.num_brushsides = count;
3929
3930         for (i = 0;i < count;i++, in++, out++)
3931         {
3932                 n = LittleLong(in->planeindex);
3933                 if (n < 0 || n >= loadmodel->brush.num_planes)
3934                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)\n", n, loadmodel->brush.num_planes);
3935                 out->plane = loadmodel->brush.data_planes + n;
3936                 n = LittleLong(in->textureindex);
3937                 if (n < 0 || n >= loadmodel->brush.num_textures)
3938                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)\n", n, loadmodel->brush.num_textures);
3939                 out->texture = loadmodel->brush.data_textures + n;
3940         }
3941 }
3942
3943 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
3944 {
3945         q3dbrush_t *in;
3946         q3mbrush_t *out;
3947         int i, j, n, c, count, maxplanes;
3948         mplane_t *planes;
3949
3950         in = (void *)(mod_base + l->fileofs);
3951         if (l->filelen % sizeof(*in))
3952                 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
3953         count = l->filelen / sizeof(*in);
3954         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3955
3956         loadmodel->brush.data_brushes = out;
3957         loadmodel->brush.num_brushes = count;
3958
3959         maxplanes = 0;
3960         planes = NULL;
3961
3962         for (i = 0;i < count;i++, in++, out++)
3963         {
3964                 n = LittleLong(in->firstbrushside);
3965                 c = LittleLong(in->numbrushsides);
3966                 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
3967                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)\n", n, n + c, loadmodel->brush.num_brushsides);
3968                 out->firstbrushside = loadmodel->brush.data_brushsides + n;
3969                 out->numbrushsides = c;
3970                 n = LittleLong(in->textureindex);
3971                 if (n < 0 || n >= loadmodel->brush.num_textures)
3972                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)\n", n, loadmodel->brush.num_textures);
3973                 out->texture = loadmodel->brush.data_textures + n;
3974
3975                 // make a list of mplane_t structs to construct a colbrush from
3976                 if (maxplanes < out->numbrushsides)
3977                 {
3978                         maxplanes = out->numbrushsides;
3979                         if (planes)
3980                                 Mem_Free(planes);
3981                         planes = Mem_Alloc(tempmempool, sizeof(mplane_t) * maxplanes);
3982                 }
3983                 for (j = 0;j < out->numbrushsides;j++)
3984                 {
3985                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
3986                         planes[j].dist = out->firstbrushside[j].plane->dist;
3987                 }
3988                 // make the colbrush from the planes
3989                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents);
3990         }
3991         if (planes)
3992                 Mem_Free(planes);
3993 }
3994
3995 static void Mod_Q3BSP_LoadEffects(lump_t *l)
3996 {
3997         q3deffect_t *in;
3998         q3deffect_t *out;
3999         int i, n, count;
4000
4001         in = (void *)(mod_base + l->fileofs);
4002         if (l->filelen % sizeof(*in))
4003                 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4004         count = l->filelen / sizeof(*in);
4005         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4006
4007         loadmodel->brushq3.data_effects = out;
4008         loadmodel->brushq3.num_effects = count;
4009
4010         for (i = 0;i < count;i++, in++, out++)
4011         {
4012                 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4013                 n = LittleLong(in->brushindex);
4014                 if (n < 0 || n >= loadmodel->brush.num_brushes)
4015                         Host_Error("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes)\n", n, loadmodel->brush.num_brushes);
4016                 out->brushindex = n;
4017                 out->unknown = LittleLong(in->unknown);
4018         }
4019 }
4020
4021 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4022 {
4023         q3dvertex_t *in;
4024         int i, count;
4025
4026         in = (void *)(mod_base + l->fileofs);
4027         if (l->filelen % sizeof(*in))
4028                 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4029         loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4030         loadmodel->brushq3.data_vertex3f = Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 2 + 2 + 4)));
4031         loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_vertex3f + count * 3;
4032         loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4033         loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4034
4035         for (i = 0;i < count;i++, in++)
4036         {
4037                 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4038                 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4039                 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4040                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4041                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4042                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4043                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4044                 // svector/tvector are calculated later in face loading
4045                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4046                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4047                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4048                 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4049         }
4050 }
4051
4052 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4053 {
4054         int *in;
4055         int *out;
4056         int i, count;
4057
4058         in = (void *)(mod_base + l->fileofs);
4059         if (l->filelen % sizeof(int[3]))
4060                 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4061         count = l->filelen / sizeof(*in);
4062         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4063
4064         loadmodel->brushq3.num_triangles = count / 3;
4065         loadmodel->brushq3.data_element3i = out;
4066
4067         for (i = 0;i < count;i++, in++, out++)
4068         {
4069                 *out = LittleLong(*in);
4070                 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4071                 {
4072                         Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4073                         *out = 0;
4074                 }
4075         }
4076 }
4077
4078 static void Mod_Q3BSP_LoadLightmaps(lump_t *l)
4079 {
4080         q3dlightmap_t *in;
4081         rtexture_t **out;
4082         int i, count;
4083
4084         if (!l->filelen)
4085                 return;
4086         in = (void *)(mod_base + l->fileofs);
4087         if (l->filelen % sizeof(*in))
4088                 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4089         count = l->filelen / sizeof(*in);
4090         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4091
4092         loadmodel->brushq3.data_lightmaps = out;
4093         loadmodel->brushq3.num_lightmaps = count;
4094
4095         for (i = 0;i < count;i++, in++, out++)
4096                 *out = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", i), 128, 128, in->rgb, TEXTYPE_RGB, TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
4097 }
4098
4099 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4100 {
4101         q3dface_t *in, *oldin;
4102         msurface_t *out, *oldout;
4103         int i, oldi, j, n, count, invalidelements, patchsize[2], finalwidth, finalheight, xtess, ytess, finalvertices, finaltriangles, firstvertex, firstelement, type, oldnumtriangles, oldnumtriangles2, meshnum, meshvertices, meshtriangles, numvertices, numtriangles;
4104         //int *originalelement3i;
4105         //int *originalneighbor3i;
4106         float *originalvertex3f;
4107         //float *originalsvector3f;
4108         //float *originaltvector3f;
4109         //float *originalnormal3f;
4110         float *originalcolor4f;
4111         float *originaltexcoordtexture2f;
4112         float *originaltexcoordlightmap2f;
4113         float *v;
4114         surfmesh_t *mesh, *tempmeshlist[1024];
4115
4116         in = (void *)(mod_base + l->fileofs);
4117         if (l->filelen % sizeof(*in))
4118                 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4119         count = l->filelen / sizeof(*in);
4120         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4121
4122         loadmodel->brush.data_surfaces = out;
4123         loadmodel->brush.num_surfaces = count;
4124
4125         i = 0;
4126         for (meshnum = 0;i < count;meshnum++)
4127         {
4128                 oldi = i;
4129                 oldin = in;
4130                 oldout = out;
4131                 meshvertices = 0;
4132                 meshtriangles = 0;
4133                 for (;i < count;i++, in++, out++)
4134                 {
4135                         // check face type first
4136                         type = LittleLong(in->type);
4137                         if (type != Q3FACETYPE_POLYGON
4138                          && type != Q3FACETYPE_PATCH
4139                          && type != Q3FACETYPE_MESH
4140                          && type != Q3FACETYPE_FLARE)
4141                         {
4142                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4143                                 continue;
4144                         }
4145
4146                         n = LittleLong(in->textureindex);
4147                         if (n < 0 || n >= loadmodel->brush.num_textures)
4148                         {
4149                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->brush.num_textures);
4150                                 continue;
4151                         }
4152                         out->texture = loadmodel->brush.data_textures + n;
4153                         n = LittleLong(in->effectindex);
4154                         if (n < -1 || n >= loadmodel->brushq3.num_effects)
4155                         {
4156                                 if (developer.integer >= 2)
4157                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4158                                 n = -1;
4159                         }
4160                         if (n == -1)
4161                                 out->effect = NULL;
4162                         else
4163                                 out->effect = loadmodel->brushq3.data_effects + n;
4164                         n = LittleLong(in->lightmapindex);
4165                         if (n >= loadmodel->brushq3.num_lightmaps)
4166                         {
4167                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_lightmaps);
4168                                 n = -1;
4169                         }
4170                         else if (n < 0)
4171                                 n = -1;
4172                         if (n == -1)
4173                                 out->lightmaptexture = NULL;
4174                         else
4175                                 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n];
4176
4177                         firstvertex = LittleLong(in->firstvertex);
4178                         numvertices = LittleLong(in->numvertices);
4179                         firstelement = LittleLong(in->firstelement);
4180                         numtriangles = LittleLong(in->numelements) / 3;
4181                         if (numtriangles * 3 != LittleLong(in->numelements))
4182                         {
4183                                 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));
4184                                 continue;
4185                         }
4186                         if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4187                         {
4188                                 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);
4189                                 continue;
4190                         }
4191                         if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4192                         {
4193                                 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);
4194                                 continue;
4195                         }
4196                         switch(type)
4197                         {
4198                         case Q3FACETYPE_POLYGON:
4199                         case Q3FACETYPE_MESH:
4200                                 // no processing necessary
4201                                 break;
4202                         case Q3FACETYPE_PATCH:
4203                                 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4204                                 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4205                                 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))
4206                                 {
4207                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
4208                                         continue;
4209                                 }
4210                                 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4211                                 // convert patch to Q3FACETYPE_MESH
4212                                 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4213                                 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4214                                 // bound to user settings
4215                                 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4216                                 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4217                                 // bound to sanity settings
4218                                 xtess = bound(1, xtess, 1024);
4219                                 ytess = bound(1, ytess, 1024);
4220                                 // bound to user limit on vertices
4221                                 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_maxvertices.integer, 262144))
4222                                 {
4223                                         if (xtess > ytess)
4224                                                 xtess--;
4225                                         else
4226                                                 ytess--;
4227                                 }
4228                                 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4229                                 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4230                                 numvertices = finalwidth * finalheight;
4231                                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4232                                 break;
4233                         case Q3FACETYPE_FLARE:
4234                                 if (developer.integer >= 2)
4235                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
4236                                 // don't render it
4237                                 continue;
4238                         }
4239                         out->mesh.num_vertices = numvertices;
4240                         out->mesh.num_triangles = numtriangles;
4241                         if (meshvertices + out->mesh.num_vertices > 65536)
4242                                 break;
4243                         meshvertices += out->mesh.num_vertices;
4244                         meshtriangles += out->mesh.num_triangles;
4245                 }
4246
4247                 i = oldi;
4248                 in = oldin;
4249                 out = oldout;
4250                 mesh = tempmeshlist[meshnum] = Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, 0, 0, false, false, true);
4251                 meshvertices = 0;
4252                 meshtriangles = 0;
4253                 for (;i < count && meshvertices + out->mesh.num_vertices <= mesh->num_vertices;i++, in++, out++)
4254                 {
4255                         if (out->mesh.num_vertices < 3 || out->mesh.num_triangles < 1)
4256                                 continue;
4257
4258                         type = LittleLong(in->type);
4259                         firstvertex = LittleLong(in->firstvertex);
4260                         firstelement = LittleLong(in->firstelement);
4261                         out->mesh.data_vertex3f = mesh->data_vertex3f + meshvertices * 3;
4262                         out->mesh.data_svector3f = mesh->data_svector3f + meshvertices * 3;
4263                         out->mesh.data_tvector3f = mesh->data_tvector3f + meshvertices * 3;
4264                         out->mesh.data_normal3f = mesh->data_normal3f + meshvertices * 3;
4265                         out->mesh.data_texcoordtexture2f = mesh->data_texcoordtexture2f + meshvertices * 2;
4266                         out->mesh.data_texcoordlightmap2f = mesh->data_texcoordlightmap2f + meshvertices * 2;
4267                         out->mesh.data_lightmapcolor4f = mesh->data_lightmapcolor4f + meshvertices * 4;
4268                         out->mesh.data_element3i = mesh->data_element3i + meshtriangles * 3;
4269                         out->mesh.data_neighbor3i = mesh->data_neighbor3i + meshtriangles * 3;
4270                         switch(type)
4271                         {
4272                         case Q3FACETYPE_POLYGON:
4273                         case Q3FACETYPE_MESH:
4274                                 // no processing necessary
4275                                 for (j = 0;j < out->mesh.num_vertices;j++)
4276                                 {
4277                                         out->mesh.data_vertex3f[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
4278                                         out->mesh.data_vertex3f[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
4279                                         out->mesh.data_vertex3f[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
4280                                         out->mesh.data_texcoordtexture2f[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
4281                                         out->mesh.data_texcoordtexture2f[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
4282                                         out->mesh.data_texcoordlightmap2f[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
4283                                         out->mesh.data_texcoordlightmap2f[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
4284                                         out->mesh.data_lightmapcolor4f[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
4285                                         out->mesh.data_lightmapcolor4f[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
4286                                         out->mesh.data_lightmapcolor4f[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
4287                                         out->mesh.data_lightmapcolor4f[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
4288                                 }
4289                                 for (j = 0;j < out->mesh.num_triangles*3;j++)
4290                                         out->mesh.data_element3i[j] = loadmodel->brushq3.data_element3i[firstelement + j];
4291                                 break;
4292                         case Q3FACETYPE_PATCH:
4293                                 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4294                                 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4295                                 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4296                                 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
4297                                 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
4298                                 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
4299                                 // convert patch to Q3FACETYPE_MESH
4300                                 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4301                                 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4302                                 // bound to user settings
4303                                 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4304                                 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4305                                 // bound to sanity settings
4306                                 xtess = bound(1, xtess, 1024);
4307                                 ytess = bound(1, ytess, 1024);
4308                                 // bound to user limit on vertices
4309                                 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_maxvertices.integer, 262144))
4310                                 {
4311                                         if (xtess > ytess)
4312                                                 xtess--;
4313                                         else
4314                                                 ytess--;
4315                                 }
4316                                 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4317                                 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4318                                 finalvertices = finalwidth * finalheight;
4319                                 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4320                                 type = Q3FACETYPE_MESH;
4321                                 // generate geometry
4322                                 // (note: normals are skipped because they get recalculated)
4323                                 Q3PatchTesselateFloat(3, sizeof(float[3]), out->mesh.data_vertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
4324                                 Q3PatchTesselateFloat(2, sizeof(float[2]), out->mesh.data_texcoordtexture2f, patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
4325                                 Q3PatchTesselateFloat(2, sizeof(float[2]), out->mesh.data_texcoordlightmap2f, patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
4326                                 Q3PatchTesselateFloat(4, sizeof(float[4]), out->mesh.data_lightmapcolor4f, patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
4327                                 Q3PatchTriangleElements(out->mesh.data_element3i, finalwidth, finalheight);
4328                                 out->mesh.num_triangles = Mod_RemoveDegenerateTriangles(out->mesh.num_triangles, out->mesh.data_element3i, out->mesh.data_element3i, out->mesh.data_vertex3f);
4329                                 if (developer.integer >= 2)
4330                                 {
4331                                         if (out->mesh.num_triangles < finaltriangles)
4332                                                 Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles, %i degenerate triangles removed (leaving %i)\n", patchsize[0], patchsize[1], out->mesh.num_vertices, finaltriangles, finaltriangles - out->mesh.num_triangles, out->mesh.num_triangles);
4333                                         else
4334                                                 Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles\n", patchsize[0], patchsize[1], out->mesh.num_vertices, out->mesh.num_triangles);
4335                                 }
4336                                 // q3map does not put in collision brushes for curves... ugh
4337                                 // build the lower quality collision geometry
4338                                 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4339                                 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4340                                 // bound to user settings
4341                                 xtess = bound(r_subdivisions_collision_mintess.integer, xtess, r_subdivisions_collision_maxtess.integer);
4342                                 ytess = bound(r_subdivisions_collision_mintess.integer, ytess, r_subdivisions_collision_maxtess.integer);
4343                                 // bound to sanity settings
4344                                 xtess = bound(1, xtess, 1024);
4345                                 ytess = bound(1, ytess, 1024);
4346                                 // bound to user limit on vertices
4347                                 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_collision_maxvertices.integer, 262144))
4348                                 {
4349                                         if (xtess > ytess)
4350                                                 xtess--;
4351                                         else
4352                                                 ytess--;
4353                                 }
4354                                 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4355                                 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4356                                 finalvertices = finalwidth * finalheight;
4357                                 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4358
4359                                 out->mesh.data_collisionvertex3f = Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
4360                                 out->mesh.data_collisionelement3i = Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
4361                                 out->mesh.num_collisionvertices = finalvertices;
4362                                 out->mesh.num_collisiontriangles = finaltriangles;
4363                                 Q3PatchTesselateFloat(3, sizeof(float[3]), out->mesh.data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
4364                                 Q3PatchTriangleElements(out->mesh.data_collisionelement3i, finalwidth, finalheight);
4365
4366                                 //Mod_SnapVertices(3, out->mesh.num_vertices, out->mesh.data_vertex3f, 0.25);
4367                                 Mod_SnapVertices(3, out->mesh.num_collisionvertices, out->mesh.data_collisionvertex3f, 1);
4368
4369                                 oldnumtriangles = out->mesh.num_triangles;
4370                                 oldnumtriangles2 = out->mesh.num_collisiontriangles;
4371                                 out->mesh.num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->mesh.num_collisiontriangles, out->mesh.data_collisionelement3i, out->mesh.data_collisionelement3i, out->mesh.data_collisionvertex3f);
4372                                 if (developer.integer)
4373                                         Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve became %i:%i vertices / %i:%i triangles (%i:%i degenerate)\n", patchsize[0], patchsize[1], out->mesh.num_vertices, out->mesh.num_collisionvertices, oldnumtriangles, oldnumtriangles2, oldnumtriangles - out->mesh.num_triangles, oldnumtriangles2 - out->mesh.num_collisiontriangles);
4374                                 break;
4375                         default:
4376                                 break;
4377                         }
4378                         meshvertices += out->mesh.num_vertices;
4379                         meshtriangles += out->mesh.num_triangles;
4380                         for (j = 0, invalidelements = 0;j < out->mesh.num_triangles * 3;j++)
4381                                 if (out->mesh.data_element3i[j] < 0 || out->mesh.data_element3i[j] >= out->mesh.num_vertices)
4382                                         invalidelements++;
4383                         if (invalidelements)
4384                         {
4385                                 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->mesh.num_vertices, firstelement, out->mesh.num_triangles * 3);
4386                                 for (j = 0;j < out->mesh.num_triangles * 3;j++)
4387                                 {
4388                                         Con_Printf(" %i", out->mesh.data_element3i[j]);
4389                                         if (out->mesh.data_element3i[j] < 0 || out->mesh.data_element3i[j] >= out->mesh.num_vertices)
4390                                                 out->mesh.data_element3i[j] = 0;
4391                                 }
4392                                 Con_Print("\n");
4393                         }
4394                         // for shadow volumes
4395                         Mod_BuildTriangleNeighbors(out->mesh.data_neighbor3i, out->mesh.data_element3i, out->mesh.num_triangles);
4396                         // for per pixel lighting
4397                         Mod_BuildTextureVectorsAndNormals(out->mesh.num_vertices, out->mesh.num_triangles, out->mesh.data_vertex3f, out->mesh.data_texcoordtexture2f, out->mesh.data_element3i, out->mesh.data_svector3f, out->mesh.data_tvector3f, out->mesh.data_normal3f);
4398                         // calculate a bounding box
4399                         VectorClear(out->mins);
4400                         VectorClear(out->maxs);
4401                         if (out->mesh.num_vertices)
4402                         {
4403                                 VectorCopy(out->mesh.data_vertex3f, out->mins);
4404                                 VectorCopy(out->mesh.data_vertex3f, out->maxs);
4405                                 for (j = 1, v = out->mesh.data_vertex3f + 3;j < out->mesh.num_vertices;j++, v += 3)
4406                                 {
4407                                         out->mins[0] = min(out->mins[0], v[0]);
4408                                         out->maxs[0] = max(out->maxs[0], v[0]);
4409                                         out->mins[1] = min(out->mins[1], v[1]);
4410                                         out->maxs[1] = max(out->maxs[1], v[1]);
4411                                         out->mins[2] = min(out->mins[2], v[2]);
4412                                         out->maxs[2] = max(out->maxs[2], v[2]);
4413                                 }
4414                                 out->mins[0] -= 1.0f;
4415                                 out->mins[1] -= 1.0f;
4416                                 out->mins[2] -= 1.0f;
4417                                 out->maxs[0] += 1.0f;
4418                                 out->maxs[1] += 1.0f;
4419                                 out->maxs[2] += 1.0f;
4420                         }
4421                         // set lightmap styles for consistency with q1bsp
4422                         out->styles[0] = 0;
4423                         out->styles[1] = 255;
4424                         out->styles[2] = 255;
4425                         out->styles[3] = 255;
4426                 }
4427         }
4428
4429         // now store the completed list of meshes
4430         loadmodel->nummeshes = meshnum;
4431         if (loadmodel->nummeshes)
4432         {
4433                 loadmodel->meshlist = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *) * loadmodel->nummeshes);
4434                 memcpy(loadmodel->meshlist, tempmeshlist, sizeof(surfmesh_t *) * loadmodel->nummeshes);
4435         }
4436
4437         // free the no longer needed vertex data
4438         loadmodel->brushq3.num_vertices = 0;
4439         Mem_Free(loadmodel->brushq3.data_vertex3f);
4440         loadmodel->brushq3.data_vertex3f = NULL;
4441         loadmodel->brushq3.data_texcoordtexture2f = NULL;
4442         loadmodel->brushq3.data_texcoordlightmap2f = NULL;
4443         loadmodel->brushq3.data_color4f = NULL;
4444         // free the no longer needed triangle data
4445         loadmodel->brushq3.num_triangles = 0;
4446         Mem_Free(loadmodel->brushq3.data_element3i);
4447         loadmodel->brushq3.data_element3i = NULL;
4448 }
4449
4450 static void Mod_Q3BSP_LoadModels(lump_t *l)
4451 {
4452         q3dmodel_t *in;
4453         q3dmodel_t *out;
4454         int i, j, n, c, count;
4455
4456         in = (void *)(mod_base + l->fileofs);
4457         if (l->filelen % sizeof(*in))
4458                 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
4459         count = l->filelen / sizeof(*in);
4460         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4461
4462         loadmodel->brushq3.data_models = out;
4463         loadmodel->brushq3.num_models = count;
4464
4465         for (i = 0;i < count;i++, in++, out++)
4466         {
4467                 for (j = 0;j < 3;j++)
4468                 {
4469                         out->mins[j] = LittleFloat(in->mins[j]);
4470                         out->maxs[j] = LittleFloat(in->maxs[j]);
4471                 }
4472                 n = LittleLong(in->firstface);
4473                 c = LittleLong(in->numfaces);
4474                 if (n < 0 || n + c > loadmodel->brush.num_surfaces)
4475                         Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)\n", n, n + c, loadmodel->brush.num_surfaces);
4476                 out->firstface = n;
4477                 out->numfaces = c;
4478                 n = LittleLong(in->firstbrush);
4479                 c = LittleLong(in->numbrushes);
4480                 if (n < 0 || n + c > loadmodel->brush.num_brushes)
4481                         Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)\n", n, n + c, loadmodel->brush.num_brushes);
4482                 out->firstbrush = n;
4483                 out->numbrushes = c;
4484         }
4485 }
4486
4487 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
4488 {
4489         int *in;
4490         int *out;
4491         int i, n, count;
4492
4493         in = (void *)(mod_base + l->fileofs);
4494         if (l->filelen % sizeof(*in))
4495                 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4496         count = l->filelen / sizeof(*in);
4497         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4498
4499         loadmodel->brush.data_leafbrushes = out;
4500         loadmodel->brush.num_leafbrushes = count;
4501
4502         for (i = 0;i < count;i++, in++, out++)
4503         {
4504                 n = LittleLong(*in);
4505                 if (n < 0 || n >= loadmodel->brush.num_brushes)
4506                         Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)\n", n, loadmodel->brush.num_brushes);
4507                 *out = n;
4508         }
4509 }
4510
4511 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
4512 {
4513         int *in;
4514         int *out;
4515         int i, n, count;
4516
4517         in = (void *)(mod_base + l->fileofs);
4518         if (l->filelen % sizeof(*in))
4519                 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4520         count = l->filelen / sizeof(*in);
4521         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4522
4523         loadmodel->brush.data_leafsurfaces = out;
4524         loadmodel->brush.num_leafsurfaces = count;
4525
4526         for (i = 0;i < count;i++, in++, out++)
4527         {
4528                 n = LittleLong(*in);
4529                 if (n < 0 || n >= loadmodel->brush.num_surfaces)
4530                         Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)\n", n, loadmodel->brush.num_surfaces);
4531                 *out = n;
4532         }
4533 }
4534
4535 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
4536 {
4537         q3dleaf_t *in;
4538         mleaf_t *out;
4539         int i, j, n, c, count;
4540
4541         in = (void *)(mod_base + l->fileofs);
4542         if (l->filelen % sizeof(*in))
4543                 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4544         count = l->filelen / sizeof(*in);
4545         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4546
4547         loadmodel->brush.data_leafs = out;
4548         loadmodel->brush.num_leafs = count;
4549
4550         for (i = 0;i < count;i++, in++, out++)
4551         {
4552                 out->parent = NULL;
4553                 out->plane = NULL;
4554                 out->clusterindex = LittleLong(in->clusterindex);
4555                 out->areaindex = LittleLong(in->areaindex);
4556                 for (j = 0;j < 3;j++)
4557                 {
4558                         // yes the mins/maxs are ints
4559                         out->mins[j] = LittleLong(in->mins[j]) - 1;
4560                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
4561                 }
4562                 n = LittleLong(in->firstleafface);
4563                 c = LittleLong(in->numleaffaces);
4564                 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
4565                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)\n", n, n + c, loadmodel->brush.num_leafsurfaces);
4566                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
4567                 out->numleafsurfaces = c;
4568                 n = LittleLong(in->firstleafbrush);
4569                 c = LittleLong(in->numleafbrushes);
4570                 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
4571                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)\n", n, n + c, loadmodel->brush.num_leafbrushes);
4572                 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
4573                 out->numleafbrushes = c;
4574         }
4575 }
4576
4577 static void Mod_Q3BSP_LoadNodes(lump_t *l)
4578 {
4579         q3dnode_t *in;
4580         mnode_t *out;
4581         int i, j, n, count;
4582
4583         in = (void *)(mod_base + l->fileofs);
4584         if (l->filelen % sizeof(*in))
4585                 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4586         count = l->filelen / sizeof(*in);
4587         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4588
4589         loadmodel->brush.data_nodes = out;
4590         loadmodel->brush.num_nodes = count;
4591
4592         for (i = 0;i < count;i++, in++, out++)
4593         {
4594                 out->parent = NULL;
4595                 n = LittleLong(in->planeindex);
4596                 if (n < 0 || n >= loadmodel->brush.num_planes)
4597                         Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)\n", n, loadmodel->brush.num_planes);
4598                 out->plane = loadmodel->brush.data_planes + n;
4599                 for (j = 0;j < 2;j++)
4600                 {
4601                         n = LittleLong(in->childrenindex[j]);
4602                         if (n >= 0)
4603                         {
4604                                 if (n >= loadmodel->brush.num_nodes)
4605                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)\n", n, loadmodel->brush.num_nodes);
4606                                 out->children[j] = loadmodel->brush.data_nodes + n;
4607                         }
4608                         else
4609                         {
4610                                 n = -1 - n;
4611                                 if (n >= loadmodel->brush.num_leafs)
4612                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)\n", n, loadmodel->brush.num_leafs);
4613                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
4614                         }
4615                 }
4616                 for (j = 0;j < 3;j++)
4617                 {
4618                         // yes the mins/maxs are ints
4619                         out->mins[j] = LittleLong(in->mins[j]) - 1;
4620                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
4621                 }
4622         }
4623
4624         // set the parent pointers
4625         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
4626 }
4627
4628 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
4629 {
4630         q3dlightgrid_t *in;
4631         q3dlightgrid_t *out;
4632         int count;
4633
4634         in = (void *)(mod_base + l->fileofs);
4635         if (l->filelen % sizeof(*in))
4636                 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
4637         loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
4638         loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
4639         loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
4640         loadmodel->brushq3.num_lightgrid_imins[0] = ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
4641         loadmodel->brushq3.num_lightgrid_imins[1] = ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
4642         loadmodel->brushq3.num_lightgrid_imins[2] = ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
4643         loadmodel->brushq3.num_lightgrid_imaxs[0] = floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
4644         loadmodel->brushq3.num_lightgrid_imaxs[1] = floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
4645         loadmodel->brushq3.num_lightgrid_imaxs[2] = floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
4646         loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
4647         loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
4648         loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
4649         count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
4650         if (l->filelen)
4651         {
4652                 if (l->filelen < count * (int)sizeof(*in))
4653                         Host_Error("Mod_Q3BSP_LoadLightGrid: invalid lightgrid lump size %i bytes, should be %i bytes (%ix%ix%i)\n", l->filelen, count * sizeof(*in), loadmodel->brushq3.num_lightgrid_dimensions[0], loadmodel->brushq3.num_lightgrid_dimensions[1], loadmodel->brushq3.num_lightgrid_dimensions[2]);
4654                 if (l->filelen != count * (int)sizeof(*in))
4655                         Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", count * sizeof(*in), l->filelen);
4656         }
4657
4658         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4659         loadmodel->brushq3.data_lightgrid = out;
4660         loadmodel->brushq3.num_lightgrid = count;
4661
4662         // no swapping or validation necessary
4663         if (l->filelen)
4664                 memcpy(out, in, count * (int)sizeof(*out));
4665         else
4666         {
4667                 // no data, fill with white
4668                 int i;
4669                 for (i = 0;i < count;i++)
4670                 {
4671                         out[i].ambientrgb[0] = 128;
4672                         out[i].ambientrgb[1] = 128;
4673                         out[i].ambientrgb[2] = 128;
4674                         out[i].diffusergb[0] = 0;
4675                         out[i].diffusergb[1] = 0;
4676                         out[i].diffusergb[2] = 0;
4677                         out[i].diffusepitch = 0;
4678                         out[i].diffuseyaw = 0;
4679                 }
4680         }
4681
4682         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]);
4683         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]);
4684 }
4685
4686 static void Mod_Q3BSP_LoadPVS(lump_t *l)
4687 {
4688         q3dpvs_t *in;
4689         int totalchains;
4690
4691         if (l->filelen == 0)
4692         {
4693                 int i;
4694                 // unvised maps often have cluster indices even without pvs, so check
4695                 // leafs to find real number of clusters
4696                 loadmodel->brush.num_pvsclusters = 1;
4697                 for (i = 0;i < loadmodel->brush.num_leafs;i++)
4698                         loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
4699
4700                 // create clusters
4701                 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
4702                 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
4703                 loadmodel->brush.data_pvsclusters = Mem_Alloc(loadmodel->mempool, totalchains);
4704                 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
4705                 return;
4706         }
4707
4708         in = (void *)(mod_base + l->fileofs);
4709         if (l->filelen < 9)
4710                 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
4711
4712         loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
4713         loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
4714         if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
4715                 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8\n", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
4716         totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
4717         if (l->filelen < totalchains + (int)sizeof(*in))
4718                 Host_Error("Mod_Q3BSP_LoadPVS: lump too small ((numclusters = %i) * (chainlength = %i) + sizeof(q3dpvs_t) == %i bytes, lump is %i bytes)\n", loadmodel->brush.num_pvsclusters, loadmodel->brush.num_pvsclusterbytes, totalchains + sizeof(*in), l->filelen);
4719
4720         loadmodel->brush.data_pvsclusters = Mem_Alloc(loadmodel->mempool, totalchains);
4721         memcpy(loadmodel->brush.data_pvsclusters, (qbyte *)(in + 1), totalchains);
4722 }
4723
4724 static void Mod_Q3BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
4725 {
4726         int i, j, k, index[3];
4727         float transformed[3], blend1, blend2, blend, yaw, pitch, sinpitch;
4728         q3dlightgrid_t *a, *s;
4729         // FIXME: write this
4730         if (!model->brushq3.num_lightgrid)
4731         {
4732                 ambientcolor[0] = 1;
4733                 ambientcolor[1] = 1;
4734                 ambientcolor[2] = 1;
4735                 return;
4736         }
4737         Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
4738         //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
4739         //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
4740         transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
4741         transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
4742         transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
4743         index[0] = (int)floor(transformed[0]);
4744         index[1] = (int)floor(transformed[1]);
4745         index[2] = (int)floor(transformed[2]);
4746         //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
4747         // now lerp the values
4748         VectorClear(diffusenormal);
4749         a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
4750         for (k = 0;k < 2;k++)
4751         {
4752                 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
4753                 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
4754                         continue;
4755                 for (j = 0;j < 2;j++)
4756                 {
4757                         blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
4758                         if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
4759                                 continue;
4760                         for (i = 0;i < 2;i++)
4761                         {
4762                                 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0])));
4763                                 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
4764                                         continue;
4765                                 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
4766                                 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
4767                                 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
4768                                 pitch = s->diffusepitch * M_PI / 128;
4769                                 yaw = s->diffuseyaw * M_PI / 128;
4770                                 sinpitch = sin(pitch);
4771                                 diffusenormal[0] += blend * (cos(yaw) * sinpitch);
4772                                 diffusenormal[1] += blend * (sin(yaw) * sinpitch);
4773                                 diffusenormal[2] += blend * (cos(pitch));
4774                                 //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)));
4775                         }
4776                 }
4777         }
4778         VectorNormalize(diffusenormal);
4779         //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]);
4780 }
4781
4782 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, model_t *model, mnode_t *node, const vec3_t point, int markframe)
4783 {
4784         int i;
4785         mleaf_t *leaf;
4786         colbrushf_t *brush;
4787         // find which leaf the point is in
4788         while (node->plane)
4789                 node = node->children[DotProduct(point, node->plane->normal) < node->plane->dist];
4790         // point trace the brushes
4791         leaf = (mleaf_t *)node;
4792         for (i = 0;i < leaf->numleafbrushes;i++)
4793         {
4794                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
4795                 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
4796                 {
4797                         brush->markframe = markframe;
4798                         Collision_TracePointBrushFloat(trace, point, brush);
4799                 }
4800         }
4801         // can't do point traces on curves (they have no thickness)
4802 }
4803
4804 static void Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace_t *trace, 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)
4805 {
4806         int i, startside, endside;
4807         float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
4808         mleaf_t *leaf;
4809         msurface_t *surface;
4810         colbrushf_t *brush;
4811         if (startfrac > trace->realfraction)
4812                 return;
4813         // note: all line fragments past first impact fraction are ignored
4814         if (VectorCompare(start, end))
4815         {
4816                 // find which leaf the point is in
4817                 while (node->plane)
4818                         node = node->children[DotProduct(start, node->plane->normal) < node->plane->dist];
4819         }
4820         else
4821         {
4822                 // find which nodes the line is in and recurse for them
4823                 while (node->plane)
4824                 {
4825                         // recurse down node sides
4826                         dist1 = PlaneDiff(start, node->plane);
4827                         dist2 = PlaneDiff(end, node->plane);
4828                         startside = dist1 < 0;
4829                         endside = dist2 < 0;
4830                         if (startside == endside)
4831                         {
4832                                 // most of the time the line fragment is on one side of the plane
4833                                 node = node->children[startside];
4834                         }
4835                         else
4836                         {
4837                                 // line crosses node plane, split the line
4838                                 midfrac = dist1 / (dist1 - dist2);
4839                                 VectorLerp(start, midfrac, end, mid);
4840                                 // take the near side first
4841                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
4842                                 if (midfrac <= trace->realfraction)
4843                                         Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
4844                                 return;
4845                         }
4846                 }
4847         }
4848         // hit a leaf
4849         nodesegmentmins[0] = min(start[0], end[0]);
4850         nodesegmentmins[1] = min(start[1], end[1]);
4851         nodesegmentmins[2] = min(start[2], end[2]);
4852         nodesegmentmaxs[0] = max(start[0], end[0]);
4853         nodesegmentmaxs[1] = max(start[1], end[1]);
4854         nodesegmentmaxs[2] = max(start[2], end[2]);
4855         // line trace the brushes
4856         leaf = (mleaf_t *)node;
4857         for (i = 0;i < leaf->numleafbrushes;i++)
4858         {
4859                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
4860                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
4861                 {
4862                         brush->markframe = markframe;
4863                         Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
4864                         if (startfrac > trace->realfraction)
4865                                 return;
4866                 }
4867         }
4868         // can't do point traces on curves (they have no thickness)
4869         if (mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
4870         {
4871                 // line trace the curves
4872                 for (i = 0;i < leaf->numleafsurfaces;i++)
4873                 {
4874                         surface = model->brush.data_surfaces + leaf->firstleafsurface[i];
4875                         if (surface->mesh.num_collisiontriangles && surface->collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
4876                         {
4877                                 surface->collisionmarkframe = markframe;
4878                                 Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->mesh.num_collisiontriangles, surface->mesh.data_collisionelement3i, surface->mesh.data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
4879                                 if (startfrac > trace->realfraction)
4880                                         return;
4881                         }
4882                 }
4883         }
4884 }
4885
4886 static void Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace_t *trace, 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)
4887 {
4888         int i;
4889         //int sides;
4890         float nodesegmentmins[3], nodesegmentmaxs[3];
4891         mleaf_t *leaf;
4892         colbrushf_t *brush;
4893         msurface_t *surface;
4894         /*
4895                 // find which nodes the line is in and recurse for them
4896                 while (node->plane)
4897                 {
4898                         // recurse down node sides
4899                         int startside, endside;
4900                         float dist1near, dist1far, dist2near, dist2far;
4901                         BoxPlaneCornerDistances(thisbrush_start->mins, thisbrush_start->maxs, node->plane, &dist1near, &dist1far);
4902                         BoxPlaneCornerDistances(thisbrush_end->mins, thisbrush_end->maxs, node->plane, &dist2near, &dist2far);
4903                         startside = dist1near < 0;
4904                         startside = dist1near < 0 ? (dist1far < 0 ? 1 : 2) : (dist1far < 0 ? 2 : 0);
4905                         endside = dist2near < 0 ? (dist2far < 0 ? 1 : 2) : (dist2far < 0 ? 2 : 0);
4906                         if (startside == 2 || endside == 2)
4907                         {
4908                                 // brushes cross plane
4909                                 // do not clip anything, just take both sides
4910                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
4911                                 node = node->children[1];
4912                                 continue;
4913                         }
4914                         if (startside == 0)
4915                         {
4916                                 if (endside == 0)
4917                                 {
4918                                         node = node->children[0];
4919                                         continue;
4920                                 }
4921                                 else
4922                                 {
4923                                         //midf0 = dist1near / (dist1near - dist2near);
4924                                         //midf1 = dist1far / (dist1far - dist2far);
4925                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
4926                                         node = node->children[1];
4927                                         continue;
4928                                 }
4929                         }
4930                         else
4931                         {
4932                                 if (endside == 0)
4933                                 {
4934                                         //midf0 = dist1near / (dist1near - dist2near);
4935                                         //midf1 = dist1far / (dist1far - dist2far);
4936                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
4937                                         node = node->children[1];
4938                                         continue;
4939                                 }
4940                                 else
4941                                 {
4942                                         node = node->children[1];
4943                                         continue;
4944                                 }
4945                         }
4946
4947                         if (dist1near <  0 && dist2near <  0 && dist1far <  0 && dist2far <  0){node = node->children[1];continue;}
4948                         if (dist1near <  0 && dist2near <  0 && dist1far <  0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4949                         if (dist1near <  0 && dist2near <  0 && dist1far >= 0 && dist2far <  0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4950                         if (dist1near <  0 && dist2near <  0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4951                         if (dist1near <  0 && dist2near >= 0 && dist1far <  0 && dist2far <  0){node = node->children[1];continue;}
4952                         if (dist1near <  0 && dist2near >= 0 && dist1far <  0 && dist2far >= 0){}
4953                         if (dist1near <  0 && dist2near >= 0 && dist1far >= 0 && dist2far <  0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4954                         if (dist1near <  0 && dist2near >= 0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4955                         if (dist1near >= 0 && dist2near <  0 && dist1far <  0 && dist2far <  0){node = node->children[1];continue;}
4956                         if (dist1near >= 0 && dist2near <  0 && dist1far <  0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4957                         if (dist1near >= 0 && dist2near <  0 && dist1far >= 0 && dist2far <  0){}
4958                         if (dist1near >= 0 && dist2near <  0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4959                         if (dist1near >= 0 && dist2near >= 0 && dist1far <  0 && dist2far <  0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4960                         if (dist1near >= 0 && dist2near >= 0 && dist1far <  0 && dist2far >= 0){node = node->children[0];continue;}
4961                         if (dist1near >= 0 && dist2near >= 0 && dist1far >= 0 && dist2far <  0){node = node->children[0];continue;}
4962                         if (dist1near >= 0 && dist2near >= 0 && dist1far >= 0 && dist2far >= 0){node = node->children[0];continue;}
4963                         {
4964                                 if (dist2near < 0) // d1n<0 && d2n<0
4965                                 {
4966                                         if (dist2near < 0) // d1n<0 && d2n<0
4967                                         {
4968                                                 if (dist2near < 0) // d1n<0 && d2n<0
4969                                                 {
4970                                                 }
4971                                                 else // d1n<0 && d2n>0
4972                                                 {
4973                                                 }
4974                                         }
4975                                         else // d1n<0 && d2n>0
4976                                         {
4977                                                 if (dist2near < 0) // d1n<0 && d2n<0
4978                                                 {
4979                                                 }
4980                                                 else // d1n<0 && d2n>0
4981                                                 {
4982                                                 }
4983                                         }
4984                                 }
4985                                 else // d1n<0 && d2n>0
4986                                 {
4987                                 }
4988                         }
4989                         else // d1n>0
4990                         {
4991                                 if (dist2near < 0) // d1n>0 && d2n<0
4992                                 {
4993                                 }
4994                                 else // d1n>0 && d2n>0
4995                                 {
4996                                 }
4997                         }
4998                         if (dist1near < 0 == dist1far < 0 == dist2near < 0 == dist2far < 0)
4999                         {
5000                                 node = node->children[startside];
5001                                 continue;
5002                         }
5003                         if (dist1near < dist2near)
5004                         {
5005                                 // out
5006                                 if (dist1near >= 0)
5007                                 {
5008                                         node = node->children[0];
5009                                         continue;
5010                                 }
5011                                 if (dist2far < 0)
5012                                 {
5013                                         node = node->children[1];
5014                                         continue;
5015                                 }
5016                                 // dist1near < 0 && dist2far >= 0
5017                         }
5018                         else
5019                         {
5020                                 // in
5021                         }
5022                         startside = dist1near < 0 ? (dist1far < 0 ? 1 : 2) : (dist1far < 0 ? 2 : 0);
5023                         endside = dist2near < 0 ? (dist2far < 0 ? 1 : 2) : (dist2far < 0 ? 2 : 0);
5024                         if (startside == 2 || endside == 2)
5025                         {
5026                                 // brushes cross plane
5027                                 // do not clip anything, just take both sides
5028                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5029                                 node = node->children[1];
5030                         }
5031                         else if (startside == endside)
5032                                 node = node->children[startside];
5033                         else if (startside == 0) // endside = 1 (start infront, end behind)
5034                         {
5035                         }
5036                         else // startside == 1 endside = 0 (start behind, end infront)
5037                         {
5038                         }
5039                         == endside)
5040                         {
5041                                 if (startside < 2)
5042                                         node = node->children[startside];
5043                                 else
5044                                 {
5045                                         // start and end brush cross plane
5046                                 }
5047                         }
5048                         else
5049                         {
5050                         }
5051                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5052                                 node = node->children[1];
5053                         else if (dist1near < 0 && dist1far < 0 && dist2near >= 0 && dist2far >= 0)
5054                         else if (dist1near >= 0 && dist1far >= 0 && dist2near < 0 && dist2far < 0)
5055                         else if (dist1near >= 0 && dist1far >= 0 && dist2near >= 0 && dist2far >= 0)
5056                                 node = node->children[0];
5057                         else
5058                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5059                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5060                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5061                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5062                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5063                         {
5064                         }
5065                         else if (dist1near >= 0 && dist1far >= 0)
5066                         {
5067                         }
5068                         else // mixed (lying on plane)
5069                         {
5070                         }
5071                         {
5072                                 if (dist2near < 0 && dist2far < 0)
5073                                 {
5074                                 }
5075                                 else
5076                                         node = node->children[1];
5077                         }
5078                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5079                                 node = node->children[0];
5080                         else if (dist1near >= 0 && dist1far >= 0 && dist2near >= 0 && dist2far >= 0)
5081                                 node = node->children[1];
5082                         else
5083                         {
5084                                 // both sides
5085                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5086                                 node = node->children[1];
5087                         }
5088                         sides = dist1near || dist1near < 0 | dist1far < 0 | dist2near < 0 | dist
5089                         startside = dist1 < 0;
5090                         endside = dist2 < 0;
5091                         if (startside == endside)
5092                         {
5093                                 // most of the time the line fragment is on one side of the plane
5094                                 node = node->children[startside];
5095                         }
5096                         else
5097                         {
5098                                 // line crosses node plane, split the line
5099                                 midfrac = dist1 / (dist1 - dist2);
5100                                 VectorLerp(start, midfrac, end, mid);
5101                                 // take the near side first
5102                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5103                                 if (midfrac <= trace->fraction)
5104                                         Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5105                                 return;
5106                         }
5107                 }
5108         */
5109 #if 1
5110         for (;;)
5111         {
5112                 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5113                 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5114                 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5115                 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5116                 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5117                 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5118                 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5119                         return;
5120                 if (!node->plane)
5121                         break;
5122                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5123                 node = node->children[1];
5124         }
5125 #elif 0
5126         // FIXME: could be made faster by copying TraceLine code and making it use
5127         // box plane distances...  (variant on the BoxOnPlaneSide code)
5128         for (;;)
5129         {
5130                 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5131                 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5132                 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5133                 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5134                 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5135                 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5136                 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5137                         return;
5138                 if (!node->plane)
5139                         break;
5140                 if (mod_q3bsp_debugtracebrush.integer == 2)
5141                 {
5142                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5143                         node = node->children[1];
5144                         continue;
5145                 }
5146                 else if (mod_q3bsp_debugtracebrush.integer == 1)
5147                 {
5148                         // recurse down node sides
5149                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5150                         if (sides == 3)
5151                         {
5152                                 // segment box crosses plane
5153                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5154                                 node = node->children[1];
5155                                 continue;
5156                         }
5157                         // take whichever side the segment box is on
5158                         node = node->children[sides - 1];
5159                         continue;
5160                 }
5161                 else
5162                 {
5163                         // recurse down node sides
5164                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5165                         if (sides == 3)
5166                         {
5167                                 // segment box crosses plane
5168                                 // now check start and end brush boxes to handle a lot of 'diagonal' cases more efficiently...
5169                                 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, node->plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, node->plane);
5170                                 if (sides == 3)
5171                                 {
5172                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5173                                         node = node->children[1];
5174                                         continue;
5175                                 }
5176                         }
5177                         // take whichever side the segment box is on
5178                         node = node->children[sides - 1];
5179                         continue;
5180                 }
5181                 return;
5182         }
5183 #else
5184         // FIXME: could be made faster by copying TraceLine code and making it use
5185         // box plane distances...  (variant on the BoxOnPlaneSide code)
5186         for (;;)
5187         {
5188                 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5189                 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5190                 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5191                 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5192                 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5193                 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5194                 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5195                         return;
5196                 if (!node->plane)
5197                         break;
5198                 if (mod_q3bsp_debugtracebrush.integer == 2)
5199                 {
5200                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5201                         node = node->children[1];
5202                 }
5203                 else if (mod_q3bsp_debugtracebrush.integer == 1)
5204                 {
5205                         // recurse down node sides
5206                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5207                         if (sides == 3)
5208                         {
5209                                 // segment box crosses plane
5210                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5211                                 node = node->children[1];
5212                         }
5213                         else
5214                         {
5215                                 // take whichever side the segment box is on
5216                                 node = node->children[sides - 1];
5217                         }
5218                 }
5219                 else
5220                 {
5221                         // recurse down node sides
5222                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5223                         if (sides == 3)
5224                         {
5225                                 // segment box crosses plane
5226                                 // now check start and end brush boxes to handle a lot of 'diagonal' cases more efficiently...
5227                                 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, node->plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, node->plane);
5228                                 if (sides == 3)
5229                                 {
5230                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5231                                         sides = 2;
5232                                 }
5233                         }
5234                         // take whichever side the segment box is on
5235                         node = node->children[sides - 1];
5236                 }
5237         }
5238 #endif
5239         // hit a leaf
5240         leaf = (mleaf_t *)node;
5241         for (i = 0;i < leaf->numleafbrushes;i++)
5242         {
5243                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
5244                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
5245                 {
5246                         brush->markframe = markframe;
5247                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
5248                 }
5249         }
5250         if (mod_q3bsp_curves_collisions.integer)
5251         {
5252                 for (i = 0;i < leaf->numleafsurfaces;i++)
5253                 {
5254                         surface = model->brush.data_surfaces + leaf->firstleafsurface[i];
5255                         if (surface->mesh.num_collisiontriangles && surface->collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
5256                         {
5257                                 surface->collisionmarkframe = markframe;
5258                                 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->mesh.num_collisiontriangles, surface->mesh.data_collisionelement3i, surface->mesh.data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5259                         }
5260                 }
5261         }
5262 }
5263
5264 static void Mod_Q3BSP_TraceBox(model_t *model, int frame, trace_t *trace, const vec3_t boxstartmins, const vec3_t boxstartmaxs, const vec3_t boxendmins, const vec3_t boxendmaxs, int hitsupercontentsmask)
5265 {
5266         int i;
5267         float segmentmins[3], segmentmaxs[3];
5268         colbrushf_t *thisbrush_start, *thisbrush_end;
5269         matrix4x4_t startmatrix, endmatrix;
5270         static int markframe = 0;
5271         msurface_t *surface;
5272         q3mbrush_t *brush;
5273         memset(trace, 0, sizeof(*trace));
5274         trace->fraction = 1;
5275         trace->realfraction = 1;
5276         trace->hitsupercontentsmask = hitsupercontentsmask;
5277         Matrix4x4_CreateIdentity(&startmatrix);
5278         Matrix4x4_CreateIdentity(&endmatrix);
5279         segmentmins[0] = min(boxstartmins[0], boxendmins[0]);
5280         segmentmins[1] = min(boxstartmins[1], boxendmins[1]);
5281         segmentmins[2] = min(boxstartmins[2], boxendmins[2]);
5282         segmentmaxs[0] = max(boxstartmaxs[0], boxendmaxs[0]);
5283         segmentmaxs[1] = max(boxstartmaxs[1], boxendmaxs[1]);
5284         segmentmaxs[2] = max(boxstartmaxs[2], boxendmaxs[2]);
5285         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxstartmins, boxstartmaxs) && VectorCompare(boxendmins, boxendmaxs))
5286         {
5287                 if (VectorCompare(boxstartmins, boxendmins))
5288                 {
5289                         // point trace
5290                         if (model->brush.submodel)
5291                         {
5292                                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5293                                         if (brush->colbrushf)
5294                                                 Collision_TracePointBrushFloat(trace, boxstartmins, brush->colbrushf);
5295                         }
5296                         else
5297                                 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, boxstartmins, ++markframe);
5298                 }
5299                 else
5300                 {
5301                         // line trace
5302                         if (model->brush.submodel)
5303                         {
5304                                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5305                                         if (brush->colbrushf)
5306                                                 Collision_TraceLineBrushFloat(trace, boxstartmins, boxendmins, brush->colbrushf, brush->colbrushf);
5307                                 if (mod_q3bsp_curves_collisions.integer)
5308                                         for (i = 0, surface = model->brush.data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
5309                                                 if (surface->mesh.num_collisiontriangles)
5310                                                         Collision_TraceLineTriangleMeshFloat(trace, boxstartmins, boxendmins, surface->mesh.num_collisiontriangles, surface->mesh.data_collisionelement3i, surface->mesh.data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5311                         }
5312                         else
5313                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, boxstartmins, boxendmins, 0, 1, boxstartmins, boxendmins, ++markframe, segmentmins, segmentmaxs);
5314                 }
5315         }
5316         else
5317         {
5318                 // box trace, performed as brush trace
5319                 thisbrush_start = Collision_BrushForBox(&startmatrix, boxstartmins, boxstartmaxs);
5320                 thisbrush_end = Collision_BrushForBox(&endmatrix, boxendmins, boxendmaxs);
5321                 if (model->brush.submodel)
5322                 {
5323                         for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5324                                 if (brush->colbrushf)
5325                                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush->colbrushf, brush->colbrushf);
5326                         if (mod_q3bsp_curves_collisions.integer)
5327                                 for (i = 0, surface = model->brush.data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
5328                                         if (surface->mesh.num_collisiontriangles)
5329                                                 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->mesh.num_collisiontriangles, surface->mesh.data_collisionelement3i, surface->mesh.data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5330                 }
5331                 else
5332                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, thisbrush_start, thisbrush_end, ++markframe, segmentmins, segmentmaxs);
5333         }
5334 }
5335
5336 static int Mod_Q3BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents)
5337 {
5338         int supercontents = 0;
5339         if (nativecontents & CONTENTSQ3_SOLID)
5340                 supercontents |= SUPERCONTENTS_SOLID;
5341         if (nativecontents & CONTENTSQ3_WATER)
5342                 supercontents |= SUPERCONTENTS_WATER;
5343         if (nativecontents & CONTENTSQ3_SLIME)
5344                 supercontents |= SUPERCONTENTS_SLIME;
5345         if (nativecontents & CONTENTSQ3_LAVA)
5346                 supercontents |= SUPERCONTENTS_LAVA;
5347         if (nativecontents & CONTENTSQ3_BODY)
5348                 supercontents |= SUPERCONTENTS_BODY;
5349         if (nativecontents & CONTENTSQ3_CORPSE)
5350                 supercontents |= SUPERCONTENTS_CORPSE;
5351         if (nativecontents & CONTENTSQ3_NODROP)
5352                 supercontents |= SUPERCONTENTS_NODROP;
5353         return supercontents;
5354 }
5355
5356 static int Mod_Q3BSP_NativeContentsFromSuperContents(model_t *model, int supercontents)
5357 {
5358         int nativecontents = 0;
5359         if (supercontents & SUPERCONTENTS_SOLID)
5360                 nativecontents |= CONTENTSQ3_SOLID;
5361         if (supercontents & SUPERCONTENTS_WATER)
5362                 nativecontents |= CONTENTSQ3_WATER;
5363         if (supercontents & SUPERCONTENTS_SLIME)
5364                 nativecontents |= CONTENTSQ3_SLIME;
5365         if (supercontents & SUPERCONTENTS_LAVA)
5366                 nativecontents |= CONTENTSQ3_LAVA;
5367         if (supercontents & SUPERCONTENTS_BODY)
5368                 nativecontents |= CONTENTSQ3_BODY;
5369         if (supercontents & SUPERCONTENTS_CORPSE)
5370                 nativecontents |= CONTENTSQ3_CORPSE;
5371         if (supercontents & SUPERCONTENTS_NODROP)
5372                 nativecontents |= CONTENTSQ3_NODROP;
5373         return nativecontents;
5374 }
5375
5376 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
5377 {
5378         int numleafs;
5379         while (node->plane)
5380         {
5381                 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
5382                 node = node->children[1];
5383         }
5384         numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
5385         if (loadmodel->brush.num_leafs < numleafs)
5386                 loadmodel->brush.num_leafs = numleafs;
5387 }
5388
5389 void Mod_Q3BSP_Load(model_t *mod, void *buffer)
5390 {
5391         int i, j, numshadowmeshtriangles;
5392         q3dheader_t *header;
5393         float corner[3], yawradius, modelradius;
5394         msurface_t *surface;
5395
5396         mod->type = mod_brushq3;
5397         mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
5398         mod->numskins = 1;
5399
5400         header = (q3dheader_t *)buffer;
5401
5402         i = LittleLong(header->version);
5403         if (i != Q3BSPVERSION)
5404                 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
5405         if (mod->isworldmodel)
5406                 Cvar_SetValue("halflifebsp", false);
5407
5408         mod->soundfromcenter = true;
5409         mod->TraceBox = Mod_Q3BSP_TraceBox;
5410         mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
5411         mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
5412         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
5413         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
5414         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
5415         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
5416         mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
5417         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
5418         mod->Draw = R_Q1BSP_Draw;
5419         mod->GetLightInfo = R_Q1BSP_GetLightInfo;
5420         mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
5421         mod->DrawLight = R_Q1BSP_DrawLight;
5422
5423         mod_base = (qbyte *)header;
5424
5425         // swap all the lumps
5426         header->ident = LittleLong(header->ident);
5427         header->version = LittleLong(header->version);
5428         for (i = 0;i < Q3HEADER_LUMPS;i++)
5429         {
5430                 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
5431                 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
5432         }
5433
5434         Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
5435         Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
5436         Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
5437         Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
5438         Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
5439         Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
5440         Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
5441         Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
5442         Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS]);
5443         Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
5444         Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
5445         Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
5446         Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
5447         Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
5448         Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
5449         Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
5450         Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
5451         loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
5452
5453         // make a single combined shadow mesh to allow optimized shadow volume creation
5454         numshadowmeshtriangles = 0;
5455         for (j = 0, surface = loadmodel->brush.data_surfaces;j < loadmodel->brush.num_surfaces;j++, surface++)
5456         {
5457                 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
5458                 numshadowmeshtriangles += surface->mesh.num_triangles;
5459         }
5460         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
5461         for (j = 0, surface = loadmodel->brush.data_surfaces;j < loadmodel->brush.num_surfaces;j++, surface++)
5462                 Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, surface->mesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->mesh.num_triangles, surface->mesh.data_element3i);
5463         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true);
5464         Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
5465
5466         loadmodel->brush.num_leafs = 0;
5467         Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
5468
5469         if (loadmodel->isworldmodel)
5470         {
5471                 // clear out any stale submodels or worldmodels lying around
5472                 // if we did this clear before now, an error might abort loading and
5473                 // leave things in a bad state
5474                 Mod_RemoveStaleWorldModels(loadmodel);
5475         }
5476
5477         mod = loadmodel;
5478         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
5479         {
5480                 if (i > 0)
5481                 {
5482                         char name[10];
5483                         // LordHavoc: only register submodels if it is the world
5484                         // (prevents external bsp models from replacing world submodels with
5485                         //  their own)
5486                         if (!loadmodel->isworldmodel)
5487                                 continue;
5488                         // duplicate the basic information
5489                         sprintf(name, "*%i", i);
5490                         mod = Mod_FindName(name);
5491                         *mod = *loadmodel;
5492                         strcpy(mod->name, name);
5493                         // textures and memory belong to the main model
5494                         mod->texturepool = NULL;
5495                         mod->mempool = NULL;
5496                         mod->brush.GetPVS = NULL;
5497                         mod->brush.FatPVS = NULL;
5498                         mod->brush.BoxTouchingPVS = NULL;
5499                         mod->brush.BoxTouchingVisibleLeafs = NULL;
5500                         mod->brush.LightPoint = NULL;
5501                         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
5502                 }
5503                 mod->brush.submodel = i;
5504
5505                 // make the model surface list (used by shadowing/lighting)
5506                 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
5507                 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
5508                 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
5509                 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
5510                 mod->surfacelist = Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->surfacelist));
5511                 for (j = 0;j < mod->nummodelsurfaces;j++)
5512                         mod->surfacelist[j] = mod->firstmodelsurface + j;
5513
5514                 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
5515                 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
5516                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5517                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5518                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5519                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
5520                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
5521                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5522                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5523                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
5524                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
5525                 mod->yawmins[2] = mod->normalmins[2];
5526                 mod->yawmaxs[2] = mod->normalmaxs[2];
5527                 mod->radius = modelradius;
5528                 mod->radius2 = modelradius * modelradius;
5529
5530                 for (j = 0;j < mod->nummodelsurfaces;j++)
5531                         if (mod->brush.data_surfaces[j + mod->firstmodelsurface].texture->surfaceflags & Q3SURFACEFLAG_SKY)
5532                                 break;
5533                 if (j < mod->nummodelsurfaces)
5534                         mod->DrawSky = R_Q1BSP_DrawSky;
5535         }
5536 }
5537
5538 void Mod_IBSP_Load(model_t *mod, void *buffer)
5539 {
5540         int i = LittleLong(((int *)buffer)[1]);
5541         if (i == Q3BSPVERSION)
5542                 Mod_Q3BSP_Load(mod,buffer);
5543         else if (i == Q2BSPVERSION)
5544                 Mod_Q2BSP_Load(mod,buffer);
5545         else
5546                 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i\n", i);
5547 }
5548
5549 void Mod_MAP_Load(model_t *mod, void *buffer)
5550 {
5551         Host_Error("Mod_MAP_Load: not yet implemented\n");
5552 }
5553