changed network entity pvs checking to cache the cluster list (updated whenever the...
[divverent/darkplaces.git] / model_brush.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24 #include "polygon.h"
25 #include "curves.h"
26 #include "wad.h"
27
28
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128"};
30 cvar_t halflifebsp = {0, "halflifebsp", "0"};
31 cvar_t mcbsp = {0, "mcbsp", "0"};
32 cvar_t r_novis = {0, "r_novis", "0"};
33 cvar_t r_miplightmaps = {CVAR_SAVE, "r_miplightmaps", "0"};
34 cvar_t r_lightmaprgba = {0, "r_lightmaprgba", "1"};
35 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0"};
36 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4"};
37 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "1"};
38 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024"};
39 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536"};
40 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15"};
41 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "1"};
42 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024"};
43 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225"};
44 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1"};
45 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1"};
46 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0"};
47
48 void Mod_BrushInit(void)
49 {
50 //      Cvar_RegisterVariable(&r_subdivide_size);
51         Cvar_RegisterVariable(&halflifebsp);
52         Cvar_RegisterVariable(&mcbsp);
53         Cvar_RegisterVariable(&r_novis);
54         Cvar_RegisterVariable(&r_miplightmaps);
55         Cvar_RegisterVariable(&r_lightmaprgba);
56         Cvar_RegisterVariable(&r_nosurftextures);
57         Cvar_RegisterVariable(&r_subdivisions_tolerance);
58         Cvar_RegisterVariable(&r_subdivisions_mintess);
59         Cvar_RegisterVariable(&r_subdivisions_maxtess);
60         Cvar_RegisterVariable(&r_subdivisions_maxvertices);
61         Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
62         Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
63         Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
64         Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
65         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
66         Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
67         Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
68 }
69
70 static mleaf_t *Mod_Q1BSP_PointInLeaf(model_t *model, const vec3_t p)
71 {
72         mnode_t *node;
73
74         if (model == NULL)
75                 return NULL;
76
77         Mod_CheckLoaded(model);
78
79         // LordHavoc: modified to start at first clip node,
80         // in other words: first node of the (sub)model
81         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
82         while (node->plane)
83                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
84
85         return (mleaf_t *)node;
86 }
87
88 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(model_t *model, const vec3_t p, qbyte *out, int outsize)
89 {
90         int i;
91         mleaf_t *leaf;
92         leaf = Mod_Q1BSP_PointInLeaf(model, p);
93         if (leaf)
94         {
95                 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
96                 if (i)
97                 {
98                         memcpy(out, leaf->ambient_sound_level, i);
99                         out += i;
100                         outsize -= i;
101                 }
102         }
103         if (outsize)
104                 memset(out, 0, outsize);
105 }
106
107 static int Mod_Q1BSP_FindBoxClusters(model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
108 {
109         int numclusters = 0, side, nodestackindex = 0;
110         mnode_t *node, *nodestack[1024];
111         if (!model->brush.num_pvsclusters)
112                 return -1;
113         node = model->brush.data_nodes;
114         for (;;)
115         {
116                 if (node->plane)
117                 {
118                         // node - recurse down the BSP tree
119                         side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
120                         if (side < 2)
121                         {
122                                 // box is on one side of plane, take that path
123                                 node = node->children[side];
124                         }
125                         else
126                         {
127                                 // box crosses plane, take one path and remember the other
128                                 if (nodestackindex < 1024)
129                                         nodestack[nodestackindex++] = node->children[0];
130                                 node = node->children[1];
131                         }
132                 }
133                 else
134                 {
135                         // leaf - check cluster bit
136                         if (numclusters < maxclusters)
137                                 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
138                         numclusters++;
139                         // try another path we didn't take earlier
140                         if (nodestackindex == 0)
141                                 break;
142                         node = nodestack[--nodestackindex];
143                 }
144         }
145         // return number of clusters found (even if more than the maxclusters)
146         return numclusters;
147 }
148
149 static int Mod_Q1BSP_BoxTouchingPVS(model_t *model, const qbyte *pvs, const vec3_t mins, const vec3_t maxs)
150 {
151         int clusterindex, side, nodestackindex = 0;
152         mnode_t *node, *nodestack[1024];
153         if (!model->brush.num_pvsclusters)
154                 return true;
155         node = model->brush.data_nodes;
156         for (;;)
157         {
158                 if (node->plane)
159                 {
160                         // node - recurse down the BSP tree
161                         side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
162                         if (side < 2)
163                         {
164                                 // box is on one side of plane, take that path
165                                 node = node->children[side];
166                         }
167                         else
168                         {
169                                 // box crosses plane, take one path and remember the other
170                                 if (nodestackindex < 1024)
171                                         nodestack[nodestackindex++] = node->children[0];
172                                 node = node->children[1];
173                         }
174                 }
175                 else
176                 {
177                         // leaf - check cluster bit
178                         clusterindex = ((mleaf_t *)node)->clusterindex;
179                         if (CHECKPVSBIT(pvs, clusterindex))
180                         {
181                                 // it is visible, return immediately with the news
182                                 return true;
183                         }
184                         else
185                         {
186                                 // nothing to see here, try another path we didn't take earlier
187                                 if (nodestackindex == 0)
188                                         break;
189                                 node = nodestack[--nodestackindex];
190                         }
191                 }
192         }
193         // it is not visible
194         return false;
195 }
196
197 static int Mod_Q1BSP_BoxTouchingLeafPVS(model_t *model, const qbyte *pvs, const vec3_t mins, const vec3_t maxs)
198 {
199         int clusterindex, side, nodestackindex = 0;
200         mnode_t *node, *nodestack[1024];
201         if (!model->brush.num_leafs)
202                 return true;
203         node = model->brush.data_nodes;
204         for (;;)
205         {
206                 if (node->plane)
207                 {
208                         // node - recurse down the BSP tree
209                         side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
210                         if (side < 2)
211                         {
212                                 // box is on one side of plane, take that path
213                                 node = node->children[side];
214                         }
215                         else
216                         {
217                                 // box crosses plane, take one path and remember the other
218                                 if (nodestackindex < 1024)
219                                         nodestack[nodestackindex++] = node->children[0];
220                                 node = node->children[1];
221                         }
222                 }
223                 else
224                 {
225                         // leaf - check cluster bit
226                         clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
227                         if (CHECKPVSBIT(pvs, clusterindex))
228                         {
229                                 // it is visible, return immediately with the news
230                                 return true;
231                         }
232                         else
233                         {
234                                 // nothing to see here, try another path we didn't take earlier
235                                 if (nodestackindex == 0)
236                                         break;
237                                 node = nodestack[--nodestackindex];
238                         }
239                 }
240         }
241         // it is not visible
242         return false;
243 }
244
245 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(model_t *model, const qbyte *visibleleafs, const vec3_t mins, const vec3_t maxs)
246 {
247         int side, nodestackindex = 0;
248         mnode_t *node, *nodestack[1024];
249         node = model->brush.data_nodes;
250         for (;;)
251         {
252                 if (node->plane)
253                 {
254                         // node - recurse down the BSP tree
255                         side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
256                         if (side < 2)
257                         {
258                                 // box is on one side of plane, take that path
259                                 node = node->children[side];
260                         }
261                         else
262                         {
263                                 // box crosses plane, take one path and remember the other
264                                 if (nodestackindex < 1024)
265                                         nodestack[nodestackindex++] = node->children[0];
266                                 node = node->children[1];
267                         }
268                 }
269                 else
270                 {
271                         // leaf - check if it is visible
272                         if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
273                         {
274                                 // it is visible, return immediately with the news
275                                 return true;
276                         }
277                         else
278                         {
279                                 // nothing to see here, try another path we didn't take earlier
280                                 if (nodestackindex == 0)
281                                         break;
282                                 node = nodestack[--nodestackindex];
283                         }
284                 }
285         }
286         // it is not visible
287         return false;
288 }
289
290 typedef struct findnonsolidlocationinfo_s
291 {
292         vec3_t center;
293         vec_t radius;
294         vec3_t nudge;
295         vec_t bestdist;
296         model_t *model;
297 }
298 findnonsolidlocationinfo_t;
299
300 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
301 {
302         int i, surfacenum, k, *tri, *mark;
303         float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
304         msurface_t *surface;
305         for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
306         {
307                 surface = info->model->data_surfaces + *mark;
308                 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
309                 {
310                         for (k = 0;k < surface->num_triangles;k++)
311                         {
312                                 tri = (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle) + k * 3;
313                                 VectorCopy((surface->groupmesh->data_vertex3f + tri[0] * 3), vert[0]);
314                                 VectorCopy((surface->groupmesh->data_vertex3f + tri[1] * 3), vert[1]);
315                                 VectorCopy((surface->groupmesh->data_vertex3f + tri[2] * 3), vert[2]);
316                                 VectorSubtract(vert[1], vert[0], edge[0]);
317                                 VectorSubtract(vert[2], vert[1], edge[1]);
318                                 CrossProduct(edge[1], edge[0], facenormal);
319                                 if (facenormal[0] || facenormal[1] || facenormal[2])
320                                 {
321                                         VectorNormalize(facenormal);
322                                         f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
323                                         if (f <= info->bestdist && f >= -info->bestdist)
324                                         {
325                                                 VectorSubtract(vert[0], vert[2], edge[2]);
326                                                 VectorNormalize(edge[0]);
327                                                 VectorNormalize(edge[1]);
328                                                 VectorNormalize(edge[2]);
329                                                 CrossProduct(facenormal, edge[0], edgenormal[0]);
330                                                 CrossProduct(facenormal, edge[1], edgenormal[1]);
331                                                 CrossProduct(facenormal, edge[2], edgenormal[2]);
332                                                 // face distance
333                                                 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
334                                                  && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
335                                                  && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
336                                                 {
337                                                         // we got lucky, the center is within the face
338                                                         dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
339                                                         if (dist < 0)
340                                                         {
341                                                                 dist = -dist;
342                                                                 if (info->bestdist > dist)
343                                                                 {
344                                                                         info->bestdist = dist;
345                                                                         VectorScale(facenormal, (info->radius - -dist), info->nudge);
346                                                                 }
347                                                         }
348                                                         else
349                                                         {
350                                                                 if (info->bestdist > dist)
351                                                                 {
352                                                                         info->bestdist = dist;
353                                                                         VectorScale(facenormal, (info->radius - dist), info->nudge);
354                                                                 }
355                                                         }
356                                                 }
357                                                 else
358                                                 {
359                                                         // check which edge or vertex the center is nearest
360                                                         for (i = 0;i < 3;i++)
361                                                         {
362                                                                 f = DotProduct(info->center, edge[i]);
363                                                                 if (f >= DotProduct(vert[0], edge[i])
364                                                                  && f <= DotProduct(vert[1], edge[i]))
365                                                                 {
366                                                                         // on edge
367                                                                         VectorMA(info->center, -f, edge[i], point);
368                                                                         dist = sqrt(DotProduct(point, point));
369                                                                         if (info->bestdist > dist)
370                                                                         {
371                                                                                 info->bestdist = dist;
372                                                                                 VectorScale(point, (info->radius / dist), info->nudge);
373                                                                         }
374                                                                         // skip both vertex checks
375                                                                         // (both are further away than this edge)
376                                                                         i++;
377                                                                 }
378                                                                 else
379                                                                 {
380                                                                         // not on edge, check first vertex of edge
381                                                                         VectorSubtract(info->center, vert[i], point);
382                                                                         dist = sqrt(DotProduct(point, point));
383                                                                         if (info->bestdist > dist)
384                                                                         {
385                                                                                 info->bestdist = dist;
386                                                                                 VectorScale(point, (info->radius / dist), info->nudge);
387                                                                         }
388                                                                 }
389                                                         }
390                                                 }
391                                         }
392                                 }
393                         }
394                 }
395         }
396 }
397
398 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
399 {
400         if (node->plane)
401         {
402                 float f = PlaneDiff(info->center, node->plane);
403                 if (f >= -info->bestdist)
404                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
405                 if (f <= info->bestdist)
406                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
407         }
408         else
409         {
410                 if (((mleaf_t *)node)->numleafsurfaces)
411                         Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
412         }
413 }
414
415 static void Mod_Q1BSP_FindNonSolidLocation(model_t *model, const vec3_t in, vec3_t out, float radius)
416 {
417         int i;
418         findnonsolidlocationinfo_t info;
419         if (model == NULL)
420         {
421                 VectorCopy(in, out);
422                 return;
423         }
424         VectorCopy(in, info.center);
425         info.radius = radius;
426         info.model = model;
427         i = 0;
428         do
429         {
430                 VectorClear(info.nudge);
431                 info.bestdist = radius;
432                 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
433                 VectorAdd(info.center, info.nudge, info.center);
434         }
435         while (info.bestdist < radius && ++i < 10);
436         VectorCopy(info.center, out);
437 }
438
439 int Mod_Q1BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents)
440 {
441         switch(nativecontents)
442         {
443                 case CONTENTS_EMPTY:
444                         return 0;
445                 case CONTENTS_SOLID:
446                         return SUPERCONTENTS_SOLID;
447                 case CONTENTS_WATER:
448                         return SUPERCONTENTS_WATER;
449                 case CONTENTS_SLIME:
450                         return SUPERCONTENTS_SLIME;
451                 case CONTENTS_LAVA:
452                         return SUPERCONTENTS_LAVA;
453                 case CONTENTS_SKY:
454                         return SUPERCONTENTS_SKY;
455         }
456         return 0;
457 }
458
459 int Mod_Q1BSP_NativeContentsFromSuperContents(model_t *model, int supercontents)
460 {
461         if (supercontents & SUPERCONTENTS_SOLID)
462                 return CONTENTS_SOLID;
463         if (supercontents & SUPERCONTENTS_SKY)
464                 return CONTENTS_SKY;
465         if (supercontents & SUPERCONTENTS_LAVA)
466                 return CONTENTS_LAVA;
467         if (supercontents & SUPERCONTENTS_SLIME)
468                 return CONTENTS_SLIME;
469         if (supercontents & SUPERCONTENTS_WATER)
470                 return CONTENTS_WATER;
471         return CONTENTS_EMPTY;
472 }
473
474 typedef struct RecursiveHullCheckTraceInfo_s
475 {
476         // the hull we're tracing through
477         const hull_t *hull;
478
479         // the trace structure to fill in
480         trace_t *trace;
481
482         // start, end, and end - start (in model space)
483         double start[3];
484         double end[3];
485         double dist[3];
486 }
487 RecursiveHullCheckTraceInfo_t;
488
489 // 1/32 epsilon to keep floating point happy
490 #define DIST_EPSILON (0.03125)
491
492 #define HULLCHECKSTATE_EMPTY 0
493 #define HULLCHECKSTATE_SOLID 1
494 #define HULLCHECKSTATE_DONE 2
495
496 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
497 {
498         // status variables, these don't need to be saved on the stack when
499         // recursing...  but are because this should be thread-safe
500         // (note: tracing against a bbox is not thread-safe, yet)
501         int ret;
502         mplane_t *plane;
503         double t1, t2;
504
505         // variables that need to be stored on the stack when recursing
506         dclipnode_t *node;
507         int side;
508         double midf, mid[3];
509
510         // LordHavoc: a goto!  everyone flee in terror... :)
511 loc0:
512         // check for empty
513         if (num < 0)
514         {
515                 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
516                 if (!t->trace->startfound)
517                 {
518                         t->trace->startfound = true;
519                         t->trace->startsupercontents |= num;
520                 }
521                 if (num & SUPERCONTENTS_LIQUIDSMASK)
522                         t->trace->inwater = true;
523                 if (num == 0)
524                         t->trace->inopen = true;
525                 if (num & t->trace->hitsupercontentsmask)
526                 {
527                         // if the first leaf is solid, set startsolid
528                         if (t->trace->allsolid)
529                                 t->trace->startsolid = true;
530 #if COLLISIONPARANOID >= 3
531                         Con_Print("S");
532 #endif
533                         return HULLCHECKSTATE_SOLID;
534                 }
535                 else
536                 {
537                         t->trace->allsolid = false;
538 #if COLLISIONPARANOID >= 3
539                         Con_Print("E");
540 #endif
541                         return HULLCHECKSTATE_EMPTY;
542                 }
543         }
544
545         // find the point distances
546         node = t->hull->clipnodes + num;
547
548         plane = t->hull->planes + node->planenum;
549         if (plane->type < 3)
550         {
551                 t1 = p1[plane->type] - plane->dist;
552                 t2 = p2[plane->type] - plane->dist;
553         }
554         else
555         {
556                 t1 = DotProduct (plane->normal, p1) - plane->dist;
557                 t2 = DotProduct (plane->normal, p2) - plane->dist;
558         }
559
560         if (t1 < 0)
561         {
562                 if (t2 < 0)
563                 {
564 #if COLLISIONPARANOID >= 3
565                         Con_Print("<");
566 #endif
567                         num = node->children[1];
568                         goto loc0;
569                 }
570                 side = 1;
571         }
572         else
573         {
574                 if (t2 >= 0)
575                 {
576 #if COLLISIONPARANOID >= 3
577                         Con_Print(">");
578 #endif
579                         num = node->children[0];
580                         goto loc0;
581                 }
582                 side = 0;
583         }
584
585         // the line intersects, find intersection point
586         // LordHavoc: this uses the original trace for maximum accuracy
587 #if COLLISIONPARANOID >= 3
588         Con_Print("M");
589 #endif
590         if (plane->type < 3)
591         {
592                 t1 = t->start[plane->type] - plane->dist;
593                 t2 = t->end[plane->type] - plane->dist;
594         }
595         else
596         {
597                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
598                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
599         }
600
601         midf = t1 / (t1 - t2);
602         midf = bound(p1f, midf, p2f);
603         VectorMA(t->start, midf, t->dist, mid);
604
605         // recurse both sides, front side first
606         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
607         // if this side is not empty, return what it is (solid or done)
608         if (ret != HULLCHECKSTATE_EMPTY)
609                 return ret;
610
611         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
612         // if other side is not solid, return what it is (empty or done)
613         if (ret != HULLCHECKSTATE_SOLID)
614                 return ret;
615
616         // front is air and back is solid, this is the impact point...
617         if (side)
618         {
619                 t->trace->plane.dist = -plane->dist;
620                 VectorNegate (plane->normal, t->trace->plane.normal);
621         }
622         else
623         {
624                 t->trace->plane.dist = plane->dist;
625                 VectorCopy (plane->normal, t->trace->plane.normal);
626         }
627
628         // calculate the true fraction
629         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
630         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
631         midf = t1 / (t1 - t2);
632         t->trace->realfraction = bound(0, midf, 1);
633
634         // calculate the return fraction which is nudged off the surface a bit
635         midf = (t1 - DIST_EPSILON) / (t1 - t2);
636         t->trace->fraction = bound(0, midf, 1);
637
638 #if COLLISIONPARANOID >= 3
639         Con_Print("D");
640 #endif
641         return HULLCHECKSTATE_DONE;
642 }
643
644 #if COLLISIONPARANOID < 2
645 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
646 {
647         while (num >= 0)
648                 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];
649         num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
650         t->trace->startsupercontents |= num;
651         if (num & SUPERCONTENTS_LIQUIDSMASK)
652                 t->trace->inwater = true;
653         if (num == 0)
654                 t->trace->inopen = true;
655         if (num & t->trace->hitsupercontentsmask)
656         {
657                 t->trace->allsolid = t->trace->startsolid = true;
658                 return HULLCHECKSTATE_SOLID;
659         }
660         else
661         {
662                 t->trace->allsolid = t->trace->startsolid = false;
663                 return HULLCHECKSTATE_EMPTY;
664         }
665 }
666 #endif
667
668 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)
669 {
670         // this function currently only supports same size start and end
671         double boxsize[3];
672         RecursiveHullCheckTraceInfo_t rhc;
673
674         memset(&rhc, 0, sizeof(rhc));
675         memset(trace, 0, sizeof(trace_t));
676         rhc.trace = trace;
677         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
678         rhc.trace->fraction = 1;
679         rhc.trace->realfraction = 1;
680         rhc.trace->allsolid = true;
681         VectorSubtract(boxstartmaxs, boxstartmins, boxsize);
682         if (boxsize[0] < 3)
683                 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
684         else if (model->brush.ismcbsp)
685         {
686                 if (boxsize[2] < 48) // pick the nearest of 40 or 56
687                         rhc.hull = &model->brushq1.hulls[2]; // 16x16x40
688                 else
689                         rhc.hull = &model->brushq1.hulls[1]; // 16x16x56
690         }
691         else if (model->brush.ishlbsp)
692         {
693                 // LordHavoc: this has to have a minor tolerance (the .1) because of
694                 // minor float precision errors from the box being transformed around
695                 if (boxsize[0] < 32.1)
696                 {
697                         if (boxsize[2] < 54) // pick the nearest of 36 or 72
698                                 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
699                         else
700                                 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
701                 }
702                 else
703                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
704         }
705         else
706         {
707                 // LordHavoc: this has to have a minor tolerance (the .1) because of
708                 // minor float precision errors from the box being transformed around
709                 if (boxsize[0] < 32.1)
710                         rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
711                 else
712                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
713         }
714         VectorSubtract(boxstartmins, rhc.hull->clip_mins, rhc.start);
715         VectorSubtract(boxendmins, rhc.hull->clip_mins, rhc.end);
716         VectorSubtract(rhc.end, rhc.start, rhc.dist);
717 #if COLLISIONPARANOID >= 2
718         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]);
719         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
720         Con_Print("\n");
721 #else
722         if (DotProduct(rhc.dist, rhc.dist))
723                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
724         else
725                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
726 #endif
727 }
728
729 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)
730 {
731 #if 1
732         colbrushf_t cbox;
733         colplanef_t cbox_planes[6];
734         cbox.supercontents = boxsupercontents;
735         cbox.numplanes = 6;
736         cbox.numpoints = 0;
737         cbox.numtriangles = 0;
738         cbox.planes = cbox_planes;
739         cbox.points = NULL;
740         cbox.elements = NULL;
741         cbox.markframe = 0;
742         cbox.mins[0] = 0;
743         cbox.mins[1] = 0;
744         cbox.mins[2] = 0;
745         cbox.maxs[0] = 0;
746         cbox.maxs[1] = 0;
747         cbox.maxs[2] = 0;
748         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];
749         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];
750         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];
751         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];
752         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];
753         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];
754         memset(trace, 0, sizeof(trace_t));
755         trace->hitsupercontentsmask = hitsupercontentsmask;
756         trace->fraction = 1;
757         trace->realfraction = 1;
758         Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
759 #else
760         RecursiveHullCheckTraceInfo_t rhc;
761         static hull_t box_hull;
762         static dclipnode_t box_clipnodes[6];
763         static mplane_t box_planes[6];
764         // fill in a default trace
765         memset(&rhc, 0, sizeof(rhc));
766         memset(trace, 0, sizeof(trace_t));
767         //To keep everything totally uniform, bounding boxes are turned into small
768         //BSP trees instead of being compared directly.
769         // create a temp hull from bounding box sizes
770         box_planes[0].dist = cmaxs[0] - mins[0];
771         box_planes[1].dist = cmins[0] - maxs[0];
772         box_planes[2].dist = cmaxs[1] - mins[1];
773         box_planes[3].dist = cmins[1] - maxs[1];
774         box_planes[4].dist = cmaxs[2] - mins[2];
775         box_planes[5].dist = cmins[2] - maxs[2];
776 #if COLLISIONPARANOID >= 3
777         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]);
778 #endif
779
780         if (box_hull.clipnodes == NULL)
781         {
782                 int i, side;
783
784                 //Set up the planes and clipnodes so that the six floats of a bounding box
785                 //can just be stored out and get a proper hull_t structure.
786
787                 box_hull.clipnodes = box_clipnodes;
788                 box_hull.planes = box_planes;
789                 box_hull.firstclipnode = 0;
790                 box_hull.lastclipnode = 5;
791
792                 for (i = 0;i < 6;i++)
793                 {
794                         box_clipnodes[i].planenum = i;
795
796                         side = i&1;
797
798                         box_clipnodes[i].children[side] = CONTENTS_EMPTY;
799                         if (i != 5)
800                                 box_clipnodes[i].children[side^1] = i + 1;
801                         else
802                                 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
803
804                         box_planes[i].type = i>>1;
805                         box_planes[i].normal[i>>1] = 1;
806                 }
807         }
808
809         // trace a line through the generated clipping hull
810         //rhc.boxsupercontents = boxsupercontents;
811         rhc.hull = &box_hull;
812         rhc.trace = trace;
813         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
814         rhc.trace->fraction = 1;
815         rhc.trace->realfraction = 1;
816         rhc.trace->allsolid = true;
817         VectorCopy(start, rhc.start);
818         VectorCopy(end, rhc.end);
819         VectorSubtract(rhc.end, rhc.start, rhc.dist);
820         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
821         //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
822         if (rhc.trace->startsupercontents)
823                 rhc.trace->startsupercontents = boxsupercontents;
824 #endif
825 }
826
827 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
828 {
829         int side, distz = endz - startz;
830         float front, back;
831         float mid;
832
833 loc0:
834         if (!node->plane)
835                 return false;           // didn't hit anything
836
837         switch (node->plane->type)
838         {
839         case PLANE_X:
840                 node = node->children[x < node->plane->dist];
841                 goto loc0;
842         case PLANE_Y:
843                 node = node->children[y < node->plane->dist];
844                 goto loc0;
845         case PLANE_Z:
846                 side = startz < node->plane->dist;
847                 if ((endz < node->plane->dist) == side)
848                 {
849                         node = node->children[side];
850                         goto loc0;
851                 }
852                 // found an intersection
853                 mid = node->plane->dist;
854                 break;
855         default:
856                 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
857                 front += startz * node->plane->normal[2];
858                 back += endz * node->plane->normal[2];
859                 side = front < node->plane->dist;
860                 if ((back < node->plane->dist) == side)
861                 {
862                         node = node->children[side];
863                         goto loc0;
864                 }
865                 // found an intersection
866                 mid = startz + distz * (front - node->plane->dist) / (front - back);
867                 break;
868         }
869
870         // go down front side
871         if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
872                 return true;    // hit something
873         else
874         {
875                 // check for impact on this node
876                 if (node->numsurfaces)
877                 {
878                         int i, ds, dt;
879                         msurface_t *surface;
880
881                         surface = model->data_surfaces + node->firstsurface;
882                         for (i = 0;i < node->numsurfaces;i++, surface++)
883                         {
884                                 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo->samples)
885                                         continue;       // no lightmaps
886
887                                 ds = (int) (x * surface->lightmapinfo->texinfo->vecs[0][0] + y * surface->lightmapinfo->texinfo->vecs[0][1] + mid * surface->lightmapinfo->texinfo->vecs[0][2] + surface->lightmapinfo->texinfo->vecs[0][3]) - surface->lightmapinfo->texturemins[0];
888                                 dt = (int) (x * surface->lightmapinfo->texinfo->vecs[1][0] + y * surface->lightmapinfo->texinfo->vecs[1][1] + mid * surface->lightmapinfo->texinfo->vecs[1][2] + surface->lightmapinfo->texinfo->vecs[1][3]) - surface->lightmapinfo->texturemins[1];
889
890                                 if (ds >= 0 && ds < surface->lightmapinfo->extents[0] && dt >= 0 && dt < surface->lightmapinfo->extents[1])
891                                 {
892                                         qbyte *lightmap;
893                                         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;
894                                         lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
895                                         lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
896                                         line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
897                                         size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
898
899                                         lightmap = surface->lightmapinfo->samples + ((dt>>4) * lmwidth + (ds>>4))*3; // LordHavoc: *3 for colored lighting
900
901                                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
902                                         {
903                                                 scale = d_lightstylevalue[surface->lightmapinfo->styles[maps]];
904                                                 r00 += lightmap[      0] * scale;g00 += lightmap[      1] * scale;b00 += lightmap[      2] * scale;
905                                                 r01 += lightmap[      3] * scale;g01 += lightmap[      4] * scale;b01 += lightmap[      5] * scale;
906                                                 r10 += lightmap[line3+0] * scale;g10 += lightmap[line3+1] * scale;b10 += lightmap[line3+2] * scale;
907                                                 r11 += lightmap[line3+3] * scale;g11 += lightmap[line3+4] * scale;b11 += lightmap[line3+5] * scale;
908                                                 lightmap += size3;
909                                         }
910
911 /*
912 LordHavoc: here's the readable version of the interpolation
913 code, not quite as easy for the compiler to optimize...
914
915 dsfrac is the X position in the lightmap pixel, * 16
916 dtfrac is the Y position in the lightmap pixel, * 16
917 r00 is top left corner, r01 is top right corner
918 r10 is bottom left corner, r11 is bottom right corner
919 g and b are the same layout.
920 r0 and r1 are the top and bottom intermediate results
921
922 first we interpolate the top two points, to get the top
923 edge sample
924
925         r0 = (((r01-r00) * dsfrac) >> 4) + r00;
926         g0 = (((g01-g00) * dsfrac) >> 4) + g00;
927         b0 = (((b01-b00) * dsfrac) >> 4) + b00;
928
929 then we interpolate the bottom two points, to get the
930 bottom edge sample
931
932         r1 = (((r11-r10) * dsfrac) >> 4) + r10;
933         g1 = (((g11-g10) * dsfrac) >> 4) + g10;
934         b1 = (((b11-b10) * dsfrac) >> 4) + b10;
935
936 then we interpolate the top and bottom samples to get the
937 middle sample (the one which was requested)
938
939         r = (((r1-r0) * dtfrac) >> 4) + r0;
940         g = (((g1-g0) * dtfrac) >> 4) + g0;
941         b = (((b1-b0) * dtfrac) >> 4) + b0;
942 */
943
944                                         ambientcolor[0] += (float) ((((((((r11-r10) * dsfrac) >> 4) + r10)-((((r01-r00) * dsfrac) >> 4) + r00)) * dtfrac) >> 4) + ((((r01-r00) * dsfrac) >> 4) + r00)) * (1.0f / 32768.0f);
945                                         ambientcolor[1] += (float) ((((((((g11-g10) * dsfrac) >> 4) + g10)-((((g01-g00) * dsfrac) >> 4) + g00)) * dtfrac) >> 4) + ((((g01-g00) * dsfrac) >> 4) + g00)) * (1.0f / 32768.0f);
946                                         ambientcolor[2] += (float) ((((((((b11-b10) * dsfrac) >> 4) + b10)-((((b01-b00) * dsfrac) >> 4) + b00)) * dtfrac) >> 4) + ((((b01-b00) * dsfrac) >> 4) + b00)) * (1.0f / 32768.0f);
947                                         return true; // success
948                                 }
949                         }
950                 }
951
952                 // go down back side
953                 node = node->children[side ^ 1];
954                 startz = mid;
955                 distz = endz - startz;
956                 goto loc0;
957         }
958 }
959
960 void Mod_Q1BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
961 {
962         Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2], p[2] - 65536);
963 }
964
965 static void Mod_Q1BSP_DecompressVis(const qbyte *in, const qbyte *inend, qbyte *out, qbyte *outend)
966 {
967         int c;
968         qbyte *outstart = out;
969         while (out < outend)
970         {
971                 if (in == inend)
972                 {
973                         Con_Printf("Mod_Q1BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
974                         return;
975                 }
976                 c = *in++;
977                 if (c)
978                         *out++ = c;
979                 else
980                 {
981                         if (in == inend)
982                         {
983                                 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);
984                                 return;
985                         }
986                         for (c = *in++;c > 0;c--)
987                         {
988                                 if (out == outend)
989                                 {
990                                         Con_Printf("Mod_Q1BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
991                                         return;
992                                 }
993                                 *out++ = 0;
994                         }
995                 }
996         }
997 }
998
999 /*
1000 =============
1001 R_Q1BSP_LoadSplitSky
1002
1003 A sky texture is 256*128, with the right side being a masked overlay
1004 ==============
1005 */
1006 void R_Q1BSP_LoadSplitSky (qbyte *src, int width, int height, int bytesperpixel)
1007 {
1008         int i, j;
1009         unsigned solidpixels[128*128], alphapixels[128*128];
1010
1011         // if sky isn't the right size, just use it as a solid layer
1012         if (width != 256 || height != 128)
1013         {
1014                 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);
1015                 loadmodel->brush.alphaskytexture = NULL;;
1016                 return;
1017         }
1018
1019         if (bytesperpixel == 4)
1020         {
1021                 for (i = 0;i < 128;i++)
1022                 {
1023                         for (j = 0;j < 128;j++)
1024                         {
1025                                 solidpixels[(i*128) + j] = ((unsigned *)src)[i*256+j+128];
1026                                 alphapixels[(i*128) + j] = ((unsigned *)src)[i*256+j];
1027                         }
1028                 }
1029         }
1030         else
1031         {
1032                 // make an average value for the back to avoid
1033                 // a fringe on the top level
1034                 int p, r, g, b;
1035                 union
1036                 {
1037                         unsigned int i;
1038                         unsigned char b[4];
1039                 }
1040                 rgba;
1041                 r = g = b = 0;
1042                 for (i = 0;i < 128;i++)
1043                 {
1044                         for (j = 0;j < 128;j++)
1045                         {
1046                                 rgba.i = palette_complete[src[i*256 + j + 128]];
1047                                 r += rgba.b[0];
1048                                 g += rgba.b[1];
1049                                 b += rgba.b[2];
1050                         }
1051                 }
1052                 rgba.b[0] = r/(128*128);
1053                 rgba.b[1] = g/(128*128);
1054                 rgba.b[2] = b/(128*128);
1055                 rgba.b[3] = 0;
1056                 for (i = 0;i < 128;i++)
1057                 {
1058                         for (j = 0;j < 128;j++)
1059                         {
1060                                 solidpixels[(i*128) + j] = palette_complete[src[i*256 + j + 128]];
1061                                 alphapixels[(i*128) + j] = (p = src[i*256 + j]) ? palette_complete[p] : rgba.i;
1062                         }
1063                 }
1064         }
1065
1066         loadmodel->brush.solidskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_solidtexture", 128, 128, (qbyte *) solidpixels, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
1067         loadmodel->brush.alphaskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_alphatexture", 128, 128, (qbyte *) alphapixels, TEXTYPE_RGBA, TEXF_ALPHA | TEXF_PRECACHE, NULL);
1068 }
1069
1070 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1071 {
1072         int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1073         miptex_t *dmiptex;
1074         texture_t *tx, *tx2, *anims[10], *altanims[10];
1075         dmiptexlump_t *m;
1076         qbyte *data, *mtdata;
1077         char name[256];
1078
1079         loadmodel->data_textures = NULL;
1080
1081         // add two slots for notexture walls and notexture liquids
1082         if (l->filelen)
1083         {
1084                 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1085                 m->nummiptex = LittleLong (m->nummiptex);
1086                 loadmodel->num_textures = m->nummiptex + 2;
1087         }
1088         else
1089         {
1090                 m = NULL;
1091                 loadmodel->num_textures = 2;
1092         }
1093
1094         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1095
1096         // fill out all slots with notexture
1097         for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1098         {
1099                 strcpy(tx->name, "NO TEXTURE FOUND");
1100                 tx->width = 16;
1101                 tx->height = 16;
1102                 tx->skin.base = r_texture_notexture;
1103                 tx->basematerialflags = 0;
1104                 if (i == loadmodel->num_textures - 1)
1105                 {
1106                         tx->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES;
1107                         tx->supercontents = SUPERCONTENTS_WATER;
1108                 }
1109                 else
1110                 {
1111                         tx->basematerialflags |= MATERIALFLAG_WALL;
1112                         tx->supercontents = SUPERCONTENTS_SOLID;
1113                 }
1114                 tx->currentframe = tx;
1115         }
1116
1117         if (!m)
1118                 return;
1119
1120         // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1121         dofs = m->dataofs;
1122         // LordHavoc: mostly rewritten map texture loader
1123         for (i = 0;i < m->nummiptex;i++)
1124         {
1125                 dofs[i] = LittleLong(dofs[i]);
1126                 if (dofs[i] == -1 || r_nosurftextures.integer)
1127                         continue;
1128                 dmiptex = (miptex_t *)((qbyte *)m + dofs[i]);
1129
1130                 // make sure name is no more than 15 characters
1131                 for (j = 0;dmiptex->name[j] && j < 15;j++)
1132                         name[j] = dmiptex->name[j];
1133                 name[j] = 0;
1134
1135                 mtwidth = LittleLong(dmiptex->width);
1136                 mtheight = LittleLong(dmiptex->height);
1137                 mtdata = NULL;
1138                 j = LittleLong(dmiptex->offsets[0]);
1139                 if (j)
1140                 {
1141                         // texture included
1142                         if (j < 40 || j + mtwidth * mtheight > l->filelen)
1143                         {
1144                                 Con_Printf("Texture \"%s\" in \"%s\"is corrupt or incomplete\n", dmiptex->name, loadmodel->name);
1145                                 continue;
1146                         }
1147                         mtdata = (qbyte *)dmiptex + j;
1148                 }
1149
1150                 if ((mtwidth & 15) || (mtheight & 15))
1151                         Con_Printf("warning: texture \"%s\" in \"%s\" is not 16 aligned\n", dmiptex->name, loadmodel->name);
1152
1153                 // LordHavoc: force all names to lowercase
1154                 for (j = 0;name[j];j++)
1155                         if (name[j] >= 'A' && name[j] <= 'Z')
1156                                 name[j] += 'a' - 'A';
1157
1158                 tx = loadmodel->data_textures + i;
1159                 strcpy(tx->name, name);
1160                 tx->width = mtwidth;
1161                 tx->height = mtheight;
1162
1163                 if (!tx->name[0])
1164                 {
1165                         sprintf(tx->name, "unnamed%i", i);
1166                         Con_Printf("warning: unnamed texture in %s, renaming to %s\n", loadmodel->name, tx->name);
1167                 }
1168
1169                 // LordHavoc: HL sky textures are entirely different than quake
1170                 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == 256 && mtheight == 128)
1171                 {
1172                         if (loadmodel->isworldmodel)
1173                         {
1174                                 data = loadimagepixels(tx->name, false, 0, 0);
1175                                 if (data)
1176                                 {
1177                                         R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1178                                         Mem_Free(data);
1179                                 }
1180                                 else if (mtdata != NULL)
1181                                         R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1182                         }
1183                 }
1184                 else
1185                 {
1186                         if (!Mod_LoadSkinFrame(&tx->skin, tx->name, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, false, true))
1187                         {
1188                                 // did not find external texture, load it from the bsp or wad3
1189                                 if (loadmodel->brush.ishlbsp)
1190                                 {
1191                                         // internal texture overrides wad
1192                                         qbyte *pixels, *freepixels, *fogpixels;
1193                                         pixels = freepixels = NULL;
1194                                         if (mtdata)
1195                                                 pixels = W_ConvertWAD3Texture(dmiptex);
1196                                         if (pixels == NULL)
1197                                                 pixels = freepixels = W_GetTexture(tx->name);
1198                                         if (pixels != NULL)
1199                                         {
1200                                                 tx->width = image_width;
1201                                                 tx->height = image_height;
1202                                                 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);
1203                                                 if (Image_CheckAlpha(pixels, image_width * image_height, true))
1204                                                 {
1205                                                         fogpixels = (qbyte *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1206                                                         for (j = 0;j < image_width * image_height * 4;j += 4)
1207                                                         {
1208                                                                 fogpixels[j + 0] = 255;
1209                                                                 fogpixels[j + 1] = 255;
1210                                                                 fogpixels[j + 2] = 255;
1211                                                                 fogpixels[j + 3] = pixels[j + 3];
1212                                                         }
1213                                                         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);
1214                                                         Mem_Free(fogpixels);
1215                                                 }
1216                                         }
1217                                         if (freepixels)
1218                                                 Mem_Free(freepixels);
1219                                 }
1220                                 else if (mtdata) // texture included
1221                                         Mod_LoadSkinFrame_Internal(&tx->skin, tx->name, TEXF_MIPMAP | TEXF_PRECACHE | TEXF_PICMIP, false, tx->name[0] != '*' && r_fullbrights.integer, mtdata, tx->width, tx->height);
1222                         }
1223                 }
1224                 if (tx->skin.base == NULL)
1225                 {
1226                         // no texture found
1227                         tx->width = 16;
1228                         tx->height = 16;
1229                         tx->skin.base = r_texture_notexture;
1230                 }
1231
1232                 tx->basematerialflags = 0;
1233                 if (tx->name[0] == '*')
1234                 {
1235                         // turb does not block movement
1236                         tx->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES;
1237                         // LordHavoc: some turbulent textures should be fullbright and solid
1238                         if (!strncmp(tx->name,"*lava",5)
1239                          || !strncmp(tx->name,"*teleport",9)
1240                          || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1241                                 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
1242                         else
1243                                 tx->basematerialflags |= MATERIALFLAG_WATERALPHA;
1244                         if (!strncmp(tx->name, "*lava", 5))
1245                                 tx->supercontents = SUPERCONTENTS_LAVA;
1246                         else if (!strncmp(tx->name, "*slime", 6))
1247                                 tx->supercontents = SUPERCONTENTS_SLIME;
1248                         else
1249                                 tx->supercontents = SUPERCONTENTS_WATER;
1250                 }
1251                 else if (tx->name[0] == 's' && tx->name[1] == 'k' && tx->name[2] == 'y')
1252                 {
1253                         tx->supercontents = SUPERCONTENTS_SKY;
1254                         tx->basematerialflags |= MATERIALFLAG_SKY;
1255                 }
1256                 else
1257                 {
1258                         tx->supercontents = SUPERCONTENTS_SOLID;
1259                         tx->basematerialflags |= MATERIALFLAG_WALL;
1260                 }
1261                 if (tx->skin.fog)
1262                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
1263
1264                 // start out with no animation
1265                 tx->currentframe = tx;
1266         }
1267
1268         // sequence the animations
1269         for (i = 0;i < m->nummiptex;i++)
1270         {
1271                 tx = loadmodel->data_textures + i;
1272                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1273                         continue;
1274                 if (tx->anim_total[0] || tx->anim_total[1])
1275                         continue;       // already sequenced
1276
1277                 // find the number of frames in the animation
1278                 memset(anims, 0, sizeof(anims));
1279                 memset(altanims, 0, sizeof(altanims));
1280
1281                 for (j = i;j < m->nummiptex;j++)
1282                 {
1283                         tx2 = loadmodel->data_textures + j;
1284                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1285                                 continue;
1286
1287                         num = tx2->name[1];
1288                         if (num >= '0' && num <= '9')
1289                                 anims[num - '0'] = tx2;
1290                         else if (num >= 'a' && num <= 'j')
1291                                 altanims[num - 'a'] = tx2;
1292                         else
1293                                 Con_Printf("Bad animating texture %s\n", tx->name);
1294                 }
1295
1296                 max = altmax = 0;
1297                 for (j = 0;j < 10;j++)
1298                 {
1299                         if (anims[j])
1300                                 max = j + 1;
1301                         if (altanims[j])
1302                                 altmax = j + 1;
1303                 }
1304                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1305
1306                 incomplete = false;
1307                 for (j = 0;j < max;j++)
1308                 {
1309                         if (!anims[j])
1310                         {
1311                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1312                                 incomplete = true;
1313                         }
1314                 }
1315                 for (j = 0;j < altmax;j++)
1316                 {
1317                         if (!altanims[j])
1318                         {
1319                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1320                                 incomplete = true;
1321                         }
1322                 }
1323                 if (incomplete)
1324                         continue;
1325
1326                 if (altmax < 1)
1327                 {
1328                         // if there is no alternate animation, duplicate the primary
1329                         // animation into the alternate
1330                         altmax = max;
1331                         for (k = 0;k < 10;k++)
1332                                 altanims[k] = anims[k];
1333                 }
1334
1335                 // link together the primary animation
1336                 for (j = 0;j < max;j++)
1337                 {
1338                         tx2 = anims[j];
1339                         tx2->animated = true;
1340                         tx2->anim_total[0] = max;
1341                         tx2->anim_total[1] = altmax;
1342                         for (k = 0;k < 10;k++)
1343                         {
1344                                 tx2->anim_frames[0][k] = anims[k];
1345                                 tx2->anim_frames[1][k] = altanims[k];
1346                         }
1347                 }
1348
1349                 // if there really is an alternate anim...
1350                 if (anims[0] != altanims[0])
1351                 {
1352                         // link together the alternate animation
1353                         for (j = 0;j < altmax;j++)
1354                         {
1355                                 tx2 = altanims[j];
1356                                 tx2->animated = true;
1357                                 // the primary/alternate are reversed here
1358                                 tx2->anim_total[0] = altmax;
1359                                 tx2->anim_total[1] = max;
1360                                 for (k = 0;k < 10;k++)
1361                                 {
1362                                         tx2->anim_frames[0][k] = altanims[k];
1363                                         tx2->anim_frames[1][k] = anims[k];
1364                                 }
1365                         }
1366                 }
1367         }
1368 }
1369
1370 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1371 {
1372         int i;
1373         qbyte *in, *out, *data, d;
1374         char litfilename[1024];
1375         loadmodel->brushq1.lightdata = NULL;
1376         if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1377         {
1378                 loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen);
1379                 for (i=0; i<l->filelen; i++)
1380                         loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1381         }
1382         else if (loadmodel->brush.ismcbsp)
1383         {
1384                 loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen);
1385                 memcpy(loadmodel->brushq1.lightdata, mod_base + l->fileofs, l->filelen);
1386         }
1387         else // LordHavoc: bsp version 29 (normal white lighting)
1388         {
1389                 // LordHavoc: hope is not lost yet, check for a .lit file to load
1390                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1391                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1392                 strlcat (litfilename, ".lit", sizeof (litfilename));
1393                 data = (qbyte*) FS_LoadFile(litfilename, tempmempool, false);
1394                 if (data)
1395                 {
1396                         if (fs_filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1397                         {
1398                                 i = LittleLong(((int *)data)[1]);
1399                                 if (i == 1)
1400                                 {
1401                                         Con_DPrintf("loaded %s\n", litfilename);
1402                                         loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, fs_filesize - 8);
1403                                         memcpy(loadmodel->brushq1.lightdata, data + 8, fs_filesize - 8);
1404                                         Mem_Free(data);
1405                                         return;
1406                                 }
1407                                 else
1408                                 {
1409                                         Con_Printf("Unknown .lit file version (%d)\n", i);
1410                                         Mem_Free(data);
1411                                 }
1412                         }
1413                         else
1414                         {
1415                                 if (fs_filesize == 8)
1416                                         Con_Print("Empty .lit file, ignoring\n");
1417                                 else
1418                                         Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", fs_filesize, 8 + l->filelen * 3);
1419                                 Mem_Free(data);
1420                         }
1421                 }
1422                 // LordHavoc: oh well, expand the white lighting data
1423                 if (!l->filelen)
1424                         return;
1425                 loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1426                 in = loadmodel->brushq1.lightdata + l->filelen*2; // place the file at the end, so it will not be overwritten until the very last write
1427                 out = loadmodel->brushq1.lightdata;
1428                 memcpy(in, mod_base + l->fileofs, l->filelen);
1429                 for (i = 0;i < l->filelen;i++)
1430                 {
1431                         d = *in++;
1432                         *out++ = d;
1433                         *out++ = d;
1434                         *out++ = d;
1435                 }
1436         }
1437 }
1438
1439 static void Mod_Q1BSP_LoadLightList(void)
1440 {
1441         int a, n, numlights;
1442         char tempchar, *s, *t, *lightsstring, lightsfilename[1024];
1443         mlight_t *e;
1444
1445         strlcpy (lightsfilename, loadmodel->name, sizeof (lightsfilename));
1446         FS_StripExtension (lightsfilename, lightsfilename, sizeof(lightsfilename));
1447         strlcat (lightsfilename, ".lights", sizeof (lightsfilename));
1448         s = lightsstring = (char *) FS_LoadFile(lightsfilename, tempmempool, false);
1449         if (s)
1450         {
1451                 numlights = 0;
1452                 while (*s)
1453                 {
1454                         while (*s && *s != '\n' && *s != '\r')
1455                                 s++;
1456                         if (!*s)
1457                         {
1458                                 Mem_Free(lightsstring);
1459                                 Con_Printf("lights file must end with a newline\n");
1460                                 return;
1461                         }
1462                         s++;
1463                         numlights++;
1464                 }
1465                 loadmodel->brushq1.lights = (mlight_t *)Mem_Alloc(loadmodel->mempool, numlights * sizeof(mlight_t));
1466                 s = lightsstring;
1467                 n = 0;
1468                 while (*s && n < numlights)
1469                 {
1470                         t = s;
1471                         while (*s && *s != '\n' && *s != '\r')
1472                                 s++;
1473                         if (!*s)
1474                         {
1475                                 Con_Printf("misparsed lights file!\n");
1476                                 break;
1477                         }
1478                         e = loadmodel->brushq1.lights + n;
1479                         tempchar = *s;
1480                         *s = 0;
1481                         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);
1482                         *s = tempchar;
1483                         if (a != 14)
1484                         {
1485                                 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);
1486                                 break;
1487                         }
1488                         if (*s == '\r')
1489                                 s++;
1490                         if (*s == '\n')
1491                                 s++;
1492                         n++;
1493                 }
1494                 if (*s)
1495                         Con_Printf("misparsed lights file!\n");
1496                 loadmodel->brushq1.numlights = numlights;
1497                 Mem_Free(lightsstring);
1498         }
1499 }
1500
1501 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1502 {
1503         loadmodel->brushq1.num_compressedpvs = 0;
1504         loadmodel->brushq1.data_compressedpvs = NULL;
1505         if (!l->filelen)
1506                 return;
1507         loadmodel->brushq1.num_compressedpvs = l->filelen;
1508         loadmodel->brushq1.data_compressedpvs = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen);
1509         memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1510 }
1511
1512 // used only for HalfLife maps
1513 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1514 {
1515         char key[128], value[4096];
1516         char wadname[128];
1517         int i, j, k;
1518         if (!data)
1519                 return;
1520         if (!COM_ParseToken(&data, false))
1521                 return; // error
1522         if (com_token[0] != '{')
1523                 return; // error
1524         while (1)
1525         {
1526                 if (!COM_ParseToken(&data, false))
1527                         return; // error
1528                 if (com_token[0] == '}')
1529                         break; // end of worldspawn
1530                 if (com_token[0] == '_')
1531                         strcpy(key, com_token + 1);
1532                 else
1533                         strcpy(key, com_token);
1534                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1535                         key[strlen(key)-1] = 0;
1536                 if (!COM_ParseToken(&data, false))
1537                         return; // error
1538                 strcpy(value, com_token);
1539                 if (!strcmp("wad", key)) // for HalfLife maps
1540                 {
1541                         if (loadmodel->brush.ishlbsp)
1542                         {
1543                                 j = 0;
1544                                 for (i = 0;i < 4096;i++)
1545                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1546                                                 break;
1547                                 if (value[i])
1548                                 {
1549                                         for (;i < 4096;i++)
1550                                         {
1551                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1552                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1553                                                         j = i+1;
1554                                                 else if (value[i] == ';' || value[i] == 0)
1555                                                 {
1556                                                         k = value[i];
1557                                                         value[i] = 0;
1558                                                         strcpy(wadname, "textures/");
1559                                                         strcat(wadname, &value[j]);
1560                                                         W_LoadTextureWadFile(wadname, false);
1561                                                         j = i+1;
1562                                                         if (!k)
1563                                                                 break;
1564                                                 }
1565                                         }
1566                                 }
1567                         }
1568                 }
1569         }
1570 }
1571
1572 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1573 {
1574         loadmodel->brush.entities = NULL;
1575         if (!l->filelen)
1576                 return;
1577         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1578         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1579         if (loadmodel->brush.ishlbsp)
1580                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1581 }
1582
1583
1584 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1585 {
1586         dvertex_t       *in;
1587         mvertex_t       *out;
1588         int                     i, count;
1589
1590         in = (dvertex_t *)(mod_base + l->fileofs);
1591         if (l->filelen % sizeof(*in))
1592                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1593         count = l->filelen / sizeof(*in);
1594         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1595
1596         loadmodel->brushq1.vertexes = out;
1597         loadmodel->brushq1.numvertexes = count;
1598
1599         for ( i=0 ; i<count ; i++, in++, out++)
1600         {
1601                 out->position[0] = LittleFloat(in->point[0]);
1602                 out->position[1] = LittleFloat(in->point[1]);
1603                 out->position[2] = LittleFloat(in->point[2]);
1604         }
1605 }
1606
1607 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1608 // can be used for this
1609 // REMOVEME
1610 int SB_ReadInt (qbyte **buffer)
1611 {
1612         int     i;
1613         i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1614         (*buffer) += 4;
1615         return i;
1616 }
1617
1618 // REMOVEME
1619 float SB_ReadFloat (qbyte **buffer)
1620 {
1621         union
1622         {
1623                 int             i;
1624                 float   f;
1625         } u;
1626
1627         u.i = SB_ReadInt (buffer);
1628         return u.f;
1629 }
1630
1631 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1632 {
1633         qbyte           *index;
1634         dmodel_t        *out;
1635         int                     i, j, count;
1636
1637         index = (qbyte *)(mod_base + l->fileofs);
1638         if (l->filelen % (48+4*hullinfo->filehulls))
1639                 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1640
1641         count = l->filelen / (48+4*hullinfo->filehulls);
1642         out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1643
1644         loadmodel->brushq1.submodels = out;
1645         loadmodel->brush.numsubmodels = count;
1646
1647         for (i = 0; i < count; i++, out++)
1648         {
1649         // spread out the mins / maxs by a pixel
1650                 out->mins[0] = SB_ReadFloat (&index) - 1;
1651                 out->mins[1] = SB_ReadFloat (&index) - 1;
1652                 out->mins[2] = SB_ReadFloat (&index) - 1;
1653                 out->maxs[0] = SB_ReadFloat (&index) + 1;
1654                 out->maxs[1] = SB_ReadFloat (&index) + 1;
1655                 out->maxs[2] = SB_ReadFloat (&index) + 1;
1656                 out->origin[0] = SB_ReadFloat (&index);
1657                 out->origin[1] = SB_ReadFloat (&index);
1658                 out->origin[2] = SB_ReadFloat (&index);
1659                 for (j = 0; j < hullinfo->filehulls; j++)
1660                         out->headnode[j] = SB_ReadInt (&index);
1661                 out->visleafs = SB_ReadInt (&index);
1662                 out->firstface = SB_ReadInt (&index);
1663                 out->numfaces = SB_ReadInt (&index);
1664         }
1665 }
1666
1667 static void Mod_Q1BSP_LoadEdges(lump_t *l)
1668 {
1669         dedge_t *in;
1670         medge_t *out;
1671         int     i, count;
1672
1673         in = (dedge_t *)(mod_base + l->fileofs);
1674         if (l->filelen % sizeof(*in))
1675                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
1676         count = l->filelen / sizeof(*in);
1677         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
1678
1679         loadmodel->brushq1.edges = out;
1680         loadmodel->brushq1.numedges = count;
1681
1682         for ( i=0 ; i<count ; i++, in++, out++)
1683         {
1684                 out->v[0] = (unsigned short)LittleShort(in->v[0]);
1685                 out->v[1] = (unsigned short)LittleShort(in->v[1]);
1686         }
1687 }
1688
1689 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
1690 {
1691         texinfo_t *in;
1692         mtexinfo_t *out;
1693         int i, j, k, count, miptex;
1694
1695         in = (texinfo_t *)(mod_base + l->fileofs);
1696         if (l->filelen % sizeof(*in))
1697                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
1698         count = l->filelen / sizeof(*in);
1699         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
1700
1701         loadmodel->brushq1.texinfo = out;
1702         loadmodel->brushq1.numtexinfo = count;
1703
1704         for (i = 0;i < count;i++, in++, out++)
1705         {
1706                 for (k = 0;k < 2;k++)
1707                         for (j = 0;j < 4;j++)
1708                                 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
1709
1710                 miptex = LittleLong(in->miptex);
1711                 out->flags = LittleLong(in->flags);
1712
1713                 out->texture = NULL;
1714                 if (loadmodel->data_textures)
1715                 {
1716                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
1717                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
1718                         else
1719                                 out->texture = loadmodel->data_textures + miptex;
1720                 }
1721                 if (out->flags & TEX_SPECIAL)
1722                 {
1723                         // if texture chosen is NULL or the shader needs a lightmap,
1724                         // force to notexture water shader
1725                         if (out->texture == NULL || out->texture->basematerialflags & MATERIALFLAG_WALL)
1726                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
1727                 }
1728                 else
1729                 {
1730                         // if texture chosen is NULL, force to notexture
1731                         if (out->texture == NULL)
1732                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
1733                 }
1734         }
1735 }
1736
1737 #if 0
1738 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
1739 {
1740         int             i, j;
1741         float   *v;
1742
1743         mins[0] = mins[1] = mins[2] = 9999;
1744         maxs[0] = maxs[1] = maxs[2] = -9999;
1745         v = verts;
1746         for (i = 0;i < numverts;i++)
1747         {
1748                 for (j = 0;j < 3;j++, v++)
1749                 {
1750                         if (*v < mins[j])
1751                                 mins[j] = *v;
1752                         if (*v > maxs[j])
1753                                 maxs[j] = *v;
1754                 }
1755         }
1756 }
1757
1758 #define MAX_SUBDIVPOLYTRIANGLES 4096
1759 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
1760
1761 static int subdivpolyverts, subdivpolytriangles;
1762 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
1763 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
1764
1765 static int subdivpolylookupvert(vec3_t v)
1766 {
1767         int i;
1768         for (i = 0;i < subdivpolyverts;i++)
1769                 if (subdivpolyvert[i][0] == v[0]
1770                  && subdivpolyvert[i][1] == v[1]
1771                  && subdivpolyvert[i][2] == v[2])
1772                         return i;
1773         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
1774                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
1775         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
1776         return subdivpolyverts++;
1777 }
1778
1779 static void SubdividePolygon(int numverts, float *verts)
1780 {
1781         int             i, i1, i2, i3, f, b, c, p;
1782         vec3_t  mins, maxs, front[256], back[256];
1783         float   m, *pv, *cv, dist[256], frac;
1784
1785         if (numverts > 250)
1786                 Host_Error("SubdividePolygon: ran out of verts in buffer");
1787
1788         BoundPoly(numverts, verts, mins, maxs);
1789
1790         for (i = 0;i < 3;i++)
1791         {
1792                 m = (mins[i] + maxs[i]) * 0.5;
1793                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
1794                 if (maxs[i] - m < 8)
1795                         continue;
1796                 if (m - mins[i] < 8)
1797                         continue;
1798
1799                 // cut it
1800                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
1801                         dist[c] = cv[i] - m;
1802
1803                 f = b = 0;
1804                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
1805                 {
1806                         if (dist[p] >= 0)
1807                         {
1808                                 VectorCopy(pv, front[f]);
1809                                 f++;
1810                         }
1811                         if (dist[p] <= 0)
1812                         {
1813                                 VectorCopy(pv, back[b]);
1814                                 b++;
1815                         }
1816                         if (dist[p] == 0 || dist[c] == 0)
1817                                 continue;
1818                         if ((dist[p] > 0) != (dist[c] > 0) )
1819                         {
1820                                 // clip point
1821                                 frac = dist[p] / (dist[p] - dist[c]);
1822                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
1823                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
1824                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
1825                                 f++;
1826                                 b++;
1827                         }
1828                 }
1829
1830                 SubdividePolygon(f, front[0]);
1831                 SubdividePolygon(b, back[0]);
1832                 return;
1833         }
1834
1835         i1 = subdivpolylookupvert(verts);
1836         i2 = subdivpolylookupvert(verts + 3);
1837         for (i = 2;i < numverts;i++)
1838         {
1839                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
1840                 {
1841                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
1842                         return;
1843                 }
1844
1845                 i3 = subdivpolylookupvert(verts + i * 3);
1846                 subdivpolyindex[subdivpolytriangles][0] = i1;
1847                 subdivpolyindex[subdivpolytriangles][1] = i2;
1848                 subdivpolyindex[subdivpolytriangles][2] = i3;
1849                 i2 = i3;
1850                 subdivpolytriangles++;
1851         }
1852 }
1853
1854 //Breaks a polygon up along axial 64 unit
1855 //boundaries so that turbulent and sky warps
1856 //can be done reasonably.
1857 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
1858 {
1859         int i, j;
1860         surfvertex_t *v;
1861         surfmesh_t *mesh;
1862
1863         subdivpolytriangles = 0;
1864         subdivpolyverts = 0;
1865         SubdividePolygon(surface->num_vertices, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex));
1866         if (subdivpolytriangles < 1)
1867                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?\n");
1868
1869         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
1870         mesh->num_vertices = subdivpolyverts;
1871         mesh->num_triangles = subdivpolytriangles;
1872         mesh->vertex = (surfvertex_t *)(mesh + 1);
1873         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
1874         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
1875
1876         for (i = 0;i < mesh->num_triangles;i++)
1877                 for (j = 0;j < 3;j++)
1878                         mesh->index[i*3+j] = subdivpolyindex[i][j];
1879
1880         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
1881         {
1882                 VectorCopy(subdivpolyvert[i], v->v);
1883                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
1884                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
1885         }
1886 }
1887 #endif
1888
1889 static void Mod_Q1BSP_LoadFaces(lump_t *l)
1890 {
1891         dface_t *in;
1892         msurface_t *surface;
1893         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris;
1894         float texmins[2], texmaxs[2], val;
1895
1896         in = (dface_t *)(mod_base + l->fileofs);
1897         if (l->filelen % sizeof(*in))
1898                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
1899         count = l->filelen / sizeof(*in);
1900         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
1901         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
1902
1903         loadmodel->num_surfaces = count;
1904
1905         totalverts = 0;
1906         totaltris = 0;
1907         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
1908         {
1909                 numedges = LittleShort(in->numedges);
1910                 totalverts += numedges;
1911                 totaltris += numedges - 2;
1912         }
1913
1914         // TODO: split up into multiple meshes as needed to avoid exceeding 65536
1915         // vertex limit
1916         loadmodel->nummeshes = 1;
1917         loadmodel->meshlist = (surfmesh_t **)Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *));
1918         loadmodel->meshlist[0] = Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
1919
1920         totalverts = 0;
1921         totaltris = 0;
1922         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
1923         {
1924                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
1925
1926                 // FIXME: validate edges, texinfo, etc?
1927                 firstedge = LittleLong(in->firstedge);
1928                 numedges = LittleShort(in->numedges);
1929                 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)
1930                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)\n", firstedge, numedges, loadmodel->brushq1.numsurfedges);
1931                 i = LittleShort(in->texinfo);
1932                 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
1933                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)\n", i, loadmodel->brushq1.numtexinfo);
1934                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
1935                 surface->texture = surface->lightmapinfo->texinfo->texture;
1936
1937                 planenum = LittleShort(in->planenum);
1938                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
1939                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)\n", planenum, loadmodel->brush.num_planes);
1940
1941                 //surface->flags = surface->texture->flags;
1942                 //if (LittleShort(in->side))
1943                 //      surface->flags |= SURF_PLANEBACK;
1944                 //surface->plane = loadmodel->brush.data_planes + planenum;
1945
1946                 surface->groupmesh = loadmodel->meshlist[0];
1947                 surface->num_firstvertex = totalverts;
1948                 surface->num_vertices = numedges;
1949                 surface->num_firsttriangle = totaltris;
1950                 surface->num_triangles = numedges - 2;
1951                 totalverts += numedges;
1952                 totaltris += numedges - 2;
1953
1954                 // convert edges back to a normal polygon
1955                 for (i = 0;i < surface->num_vertices;i++)
1956                 {
1957                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
1958                         float s, t;
1959                         if (lindex > 0)
1960                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
1961                         else
1962                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
1963                         s = DotProduct(((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
1964                         t = DotProduct(((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
1965                         (surface->groupmesh->data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
1966                         (surface->groupmesh->data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
1967                         (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
1968                         (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
1969                         (surface->groupmesh->data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
1970                 }
1971
1972                 for (i = 0;i < surface->num_triangles;i++)
1973                 {
1974                         (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
1975                         (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
1976                         (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
1977                 }
1978
1979                 // compile additional data about the surface geometry
1980                 Mod_BuildTextureVectorsAndNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, surface->groupmesh->data_vertex3f, surface->groupmesh->data_texcoordtexture2f, (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle), surface->groupmesh->data_svector3f, surface->groupmesh->data_tvector3f, surface->groupmesh->data_normal3f, true);
1981                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex));
1982
1983                 // generate surface extents information
1984                 texmins[0] = texmaxs[0] = DotProduct((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
1985                 texmins[1] = texmaxs[1] = DotProduct((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
1986                 for (i = 1;i < surface->num_vertices;i++)
1987                 {
1988                         for (j = 0;j < 2;j++)
1989                         {
1990                                 val = DotProduct((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
1991                                 texmins[j] = min(texmins[j], val);
1992                                 texmaxs[j] = max(texmaxs[j], val);
1993                         }
1994                 }
1995                 for (i = 0;i < 2;i++)
1996                 {
1997                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
1998                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
1999                 }
2000
2001                 smax = surface->lightmapinfo->extents[0] >> 4;
2002                 tmax = surface->lightmapinfo->extents[1] >> 4;
2003                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2004                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2005
2006                 // lighting info
2007                 for (i = 0;i < MAXLIGHTMAPS;i++)
2008                         surface->lightmapinfo->styles[i] = in->styles[i];
2009                 // force lightmap upload on first time seeing the surface
2010                 surface->cached_dlight = true;
2011                 surface->lightmapinfo->lightmaptexturestride = 0;
2012                 surface->lightmaptexture = NULL;
2013                 i = LittleLong(in->lightofs);
2014                 if (i == -1)
2015                 {
2016                         surface->lightmapinfo->samples = NULL;
2017                         // give non-lightmapped water a 1x white lightmap
2018                         if ((surface->texture->basematerialflags & MATERIALFLAG_WATER) && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2019                         {
2020                                 surface->lightmapinfo->samples = (qbyte *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2021                                 surface->lightmapinfo->styles[0] = 0;
2022                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2023                         }
2024                 }
2025                 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2026                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2027                 else // LordHavoc: white lighting (bsp version 29)
2028                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2029
2030                 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2031                 {
2032                         int i, iu, iv;
2033                         float u, v, ubase, vbase, uscale, vscale;
2034
2035                         if (ssize > 256 || tsize > 256)
2036                                 Host_Error("Bad surface extents");
2037                         // stainmap for permanent marks on walls
2038                         surface->lightmapinfo->stainsamples = (qbyte *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2039                         // clear to white
2040                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
2041
2042                         if (r_miplightmaps.integer)
2043                         {
2044                                 surface->lightmapinfo->lightmaptexturestride = ssize;
2045                                 surface->lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, NULL, surface->lightmapinfo->lightmaptexturestride, tsize, NULL, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, TEXF_MIPMAP | TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
2046                         }
2047                         else
2048                         {
2049                                 surface->lightmapinfo->lightmaptexturestride = R_CompatibleFragmentWidth(ssize, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, 0);
2050                                 surface->lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, NULL, surface->lightmapinfo->lightmaptexturestride, tsize, NULL, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, TEXF_FRAGMENT | TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
2051                         }
2052                         R_FragmentLocation(surface->lightmaptexture, NULL, NULL, &ubase, &vbase, &uscale, &vscale);
2053                         uscale = (uscale - ubase) / ssize;
2054                         vscale = (vscale - vbase) / tsize;
2055
2056                         for (i = 0;i < surface->num_vertices;i++)
2057                         {
2058                                 u = ((DotProduct(((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3]) + 8 - surface->lightmapinfo->texturemins[0]) * (1.0 / 16.0);
2059                                 v = ((DotProduct(((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3]) + 8 - surface->lightmapinfo->texturemins[1]) * (1.0 / 16.0);
2060                                 (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2061                                 (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2062                                 // LordHavoc: calc lightmap data offset for vertex lighting to use
2063                                 iu = (int) u;
2064                                 iv = (int) v;
2065                                 (surface->groupmesh->data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2066                         }
2067                 }
2068         }
2069 }
2070
2071 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2072 {
2073         //if (node->parent)
2074         //      Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion\n");
2075         node->parent = parent;
2076         if (node->plane)
2077         {
2078                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2079                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2080         }
2081 }
2082
2083 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2084 {
2085         int                     i, j, count, p;
2086         dnode_t         *in;
2087         mnode_t         *out;
2088
2089         in = (dnode_t *)(mod_base + l->fileofs);
2090         if (l->filelen % sizeof(*in))
2091                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2092         count = l->filelen / sizeof(*in);
2093         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2094
2095         loadmodel->brush.data_nodes = out;
2096         loadmodel->brush.num_nodes = count;
2097
2098         for ( i=0 ; i<count ; i++, in++, out++)
2099         {
2100                 for (j=0 ; j<3 ; j++)
2101                 {
2102                         out->mins[j] = LittleShort(in->mins[j]);
2103                         out->maxs[j] = LittleShort(in->maxs[j]);
2104                 }
2105
2106                 p = LittleLong(in->planenum);
2107                 out->plane = loadmodel->brush.data_planes + p;
2108
2109                 out->firstsurface = LittleShort(in->firstface);
2110                 out->numsurfaces = LittleShort(in->numfaces);
2111
2112                 for (j=0 ; j<2 ; j++)
2113                 {
2114                         p = LittleShort(in->children[j]);
2115                         if (p >= 0)
2116                                 out->children[j] = loadmodel->brush.data_nodes + p;
2117                         else
2118                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + (-1 - p));
2119                 }
2120         }
2121
2122         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);      // sets nodes and leafs
2123 }
2124
2125 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2126 {
2127         dleaf_t *in;
2128         mleaf_t *out;
2129         int i, j, count, p;
2130
2131         in = (dleaf_t *)(mod_base + l->fileofs);
2132         if (l->filelen % sizeof(*in))
2133                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2134         count = l->filelen / sizeof(*in);
2135         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2136
2137         loadmodel->brush.data_leafs = out;
2138         loadmodel->brush.num_leafs = count;
2139         // get visleafs from the submodel data
2140         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2141         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2142         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2143         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2144
2145         for ( i=0 ; i<count ; i++, in++, out++)
2146         {
2147                 for (j=0 ; j<3 ; j++)
2148                 {
2149                         out->mins[j] = LittleShort(in->mins[j]);
2150                         out->maxs[j] = LittleShort(in->maxs[j]);
2151                 }
2152
2153                 // FIXME: this function could really benefit from some error checking
2154
2155                 out->contents = LittleLong(in->contents);
2156
2157                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + LittleShort(in->firstmarksurface);
2158                 out->numleafsurfaces = LittleShort(in->nummarksurfaces);
2159                 if (out->firstleafsurface < 0 || LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2160                 {
2161                         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);
2162                         out->firstleafsurface = NULL;
2163                         out->numleafsurfaces = 0;
2164                 }
2165
2166                 out->clusterindex = i - 1;
2167                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2168                         out->clusterindex = -1;
2169
2170                 p = LittleLong(in->visofs);
2171                 // ignore visofs errors on leaf 0 (solid)
2172                 if (p >= 0 && out->clusterindex >= 0)
2173                 {
2174                         if (p >= loadmodel->brushq1.num_compressedpvs)
2175                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2176                         else
2177                                 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);
2178                 }
2179
2180                 for (j = 0;j < 4;j++)
2181                         out->ambient_sound_level[j] = in->ambient_level[j];
2182
2183                 // FIXME: Insert caustics here
2184         }
2185 }
2186
2187 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2188 {
2189         dclipnode_t *in, *out;
2190         int                     i, count;
2191         hull_t          *hull;
2192
2193         in = (dclipnode_t *)(mod_base + l->fileofs);
2194         if (l->filelen % sizeof(*in))
2195                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2196         count = l->filelen / sizeof(*in);
2197         out = (dclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2198
2199         loadmodel->brushq1.clipnodes = out;
2200         loadmodel->brushq1.numclipnodes = count;
2201
2202         for (i = 1; i < hullinfo->numhulls; i++)
2203         {
2204                 hull = &loadmodel->brushq1.hulls[i];
2205                 hull->clipnodes = out;
2206                 hull->firstclipnode = 0;
2207                 hull->lastclipnode = count-1;
2208                 hull->planes = loadmodel->brush.data_planes;
2209                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2210                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2211                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2212                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2213                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2214                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2215                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2216         }
2217
2218         for (i=0 ; i<count ; i++, out++, in++)
2219         {
2220                 out->planenum = LittleLong(in->planenum);
2221                 out->children[0] = LittleShort(in->children[0]);
2222                 out->children[1] = LittleShort(in->children[1]);
2223                 if (out->children[0] >= count || out->children[1] >= count)
2224                         Host_Error("Corrupt clipping hull(out of range child)\n");
2225         }
2226 }
2227
2228 //Duplicate the drawing hull structure as a clipping hull
2229 static void Mod_Q1BSP_MakeHull0(void)
2230 {
2231         mnode_t         *in;
2232         dclipnode_t *out;
2233         int                     i;
2234         hull_t          *hull;
2235
2236         hull = &loadmodel->brushq1.hulls[0];
2237
2238         in = loadmodel->brush.data_nodes;
2239         out = (dclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(dclipnode_t));
2240
2241         hull->clipnodes = out;
2242         hull->firstclipnode = 0;
2243         hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2244         hull->planes = loadmodel->brush.data_planes;
2245
2246         for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2247         {
2248                 out->planenum = in->plane - loadmodel->brush.data_planes;
2249                 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2250                 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2251         }
2252 }
2253
2254 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2255 {
2256         int i, j;
2257         short *in;
2258
2259         in = (short *)(mod_base + l->fileofs);
2260         if (l->filelen % sizeof(*in))
2261                 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2262         loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2263         loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2264
2265         for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2266         {
2267                 j = (unsigned) LittleShort(in[i]);
2268                 if (j >= loadmodel->num_surfaces)
2269                         Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2270                 loadmodel->brush.data_leafsurfaces[i] = j;
2271         }
2272 }
2273
2274 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2275 {
2276         int             i;
2277         int             *in;
2278
2279         in = (int *)(mod_base + l->fileofs);
2280         if (l->filelen % sizeof(*in))
2281                 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2282         loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2283         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2284
2285         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2286                 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2287 }
2288
2289
2290 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2291 {
2292         int                     i;
2293         mplane_t        *out;
2294         dplane_t        *in;
2295
2296         in = (dplane_t *)(mod_base + l->fileofs);
2297         if (l->filelen % sizeof(*in))
2298                 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2299
2300         loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2301         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2302
2303         for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2304         {
2305                 out->normal[0] = LittleFloat(in->normal[0]);
2306                 out->normal[1] = LittleFloat(in->normal[1]);
2307                 out->normal[2] = LittleFloat(in->normal[2]);
2308                 out->dist = LittleFloat(in->dist);
2309
2310                 PlaneClassify(out);
2311         }
2312 }
2313
2314 static void Mod_Q1BSP_LoadMapBrushes(void)
2315 {
2316 #if 0
2317 // unfinished
2318         int submodel, numbrushes;
2319         qboolean firstbrush;
2320         char *text, *maptext;
2321         char mapfilename[MAX_QPATH];
2322         FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2323         strlcat (mapfilename, ".map", sizeof (mapfilename));
2324         maptext = (qbyte*) FS_LoadFile(mapfilename, tempmempool, false);
2325         if (!maptext)
2326                 return;
2327         text = maptext;
2328         if (!COM_ParseToken(&data, false))
2329                 return; // error
2330         submodel = 0;
2331         for (;;)
2332         {
2333                 if (!COM_ParseToken(&data, false))
2334                         break;
2335                 if (com_token[0] != '{')
2336                         return; // error
2337                 // entity
2338                 firstbrush = true;
2339                 numbrushes = 0;
2340                 maxbrushes = 256;
2341                 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2342                 for (;;)
2343                 {
2344                         if (!COM_ParseToken(&data, false))
2345                                 return; // error
2346                         if (com_token[0] == '}')
2347                                 break; // end of entity
2348                         if (com_token[0] == '{')
2349                         {
2350                                 // brush
2351                                 if (firstbrush)
2352                                 {
2353                                         if (submodel)
2354                                         {
2355                                                 if (submodel > loadmodel->brush.numsubmodels)
2356                                                 {
2357                                                         Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2358                                                         model = NULL;
2359                                                 }
2360                                                 else
2361                                                         model = loadmodel->brush.submodels[submodel];
2362                                         }
2363                                         else
2364                                                 model = loadmodel;
2365                                 }
2366                                 for (;;)
2367                                 {
2368                                         if (!COM_ParseToken(&data, false))
2369                                                 return; // error
2370                                         if (com_token[0] == '}')
2371                                                 break; // end of brush
2372                                         // each brush face should be this format:
2373                                         // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2374                                         // FIXME: support hl .map format
2375                                         for (pointnum = 0;pointnum < 3;pointnum++)
2376                                         {
2377                                                 COM_ParseToken(&data, false);
2378                                                 for (componentnum = 0;componentnum < 3;componentnum++)
2379                                                 {
2380                                                         COM_ParseToken(&data, false);
2381                                                         point[pointnum][componentnum] = atof(com_token);
2382                                                 }
2383                                                 COM_ParseToken(&data, false);
2384                                         }
2385                                         COM_ParseToken(&data, false);
2386                                         strlcpy(facetexture, com_token, sizeof(facetexture));
2387                                         COM_ParseToken(&data, false);
2388                                         //scroll_s = atof(com_token);
2389                                         COM_ParseToken(&data, false);
2390                                         //scroll_t = atof(com_token);
2391                                         COM_ParseToken(&data, false);
2392                                         //rotate = atof(com_token);
2393                                         COM_ParseToken(&data, false);
2394                                         //scale_s = atof(com_token);
2395                                         COM_ParseToken(&data, false);
2396                                         //scale_t = atof(com_token);
2397                                         TriangleNormal(point[0], point[1], point[2], planenormal);
2398                                         VectorNormalizeDouble(planenormal);
2399                                         planedist = DotProduct(point[0], planenormal);
2400                                         //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2401                                 }
2402                                 continue;
2403                         }
2404                 }
2405         }
2406 #endif
2407 }
2408
2409
2410 #define MAX_PORTALPOINTS 64
2411
2412 typedef struct portal_s
2413 {
2414         mplane_t plane;
2415         mnode_t *nodes[2];              // [0] = front side of plane
2416         struct portal_s *next[2];
2417         int numpoints;
2418         double points[3*MAX_PORTALPOINTS];
2419         struct portal_s *chain; // all portals are linked into a list
2420 }
2421 portal_t;
2422
2423 static portal_t *portalchain;
2424
2425 /*
2426 ===========
2427 AllocPortal
2428 ===========
2429 */
2430 static portal_t *AllocPortal(void)
2431 {
2432         portal_t *p;
2433         p = (portal_t *)Mem_Alloc(loadmodel->mempool, sizeof(portal_t));
2434         p->chain = portalchain;
2435         portalchain = p;
2436         return p;
2437 }
2438
2439 static void FreePortal(portal_t *p)
2440 {
2441         Mem_Free(p);
2442 }
2443
2444 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2445 {
2446         // process only nodes (leafs already had their box calculated)
2447         if (!node->plane)
2448                 return;
2449
2450         // calculate children first
2451         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2452         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2453
2454         // make combined bounding box from children
2455         node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2456         node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2457         node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2458         node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2459         node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2460         node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2461 }
2462
2463 static void Mod_Q1BSP_FinalizePortals(void)
2464 {
2465         int i, j, numportals, numpoints;
2466         portal_t *p, *pnext;
2467         mportal_t *portal;
2468         mvertex_t *point;
2469         mleaf_t *leaf, *endleaf;
2470
2471         // recalculate bounding boxes for all leafs(because qbsp is very sloppy)
2472         leaf = loadmodel->brush.data_leafs;
2473         endleaf = leaf + loadmodel->brush.num_leafs;
2474         for (;leaf < endleaf;leaf++)
2475         {
2476                 VectorSet(leaf->mins,  2000000000,  2000000000,  2000000000);
2477                 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2478         }
2479         p = portalchain;
2480         while (p)
2481         {
2482                 if (p->numpoints >= 3)
2483                 {
2484                         for (i = 0;i < 2;i++)
2485                         {
2486                                 leaf = (mleaf_t *)p->nodes[i];
2487                                 for (j = 0;j < p->numpoints;j++)
2488                                 {
2489                                         if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
2490                                         if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
2491                                         if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
2492                                         if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
2493                                         if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
2494                                         if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
2495                                 }
2496                         }
2497                 }
2498                 p = p->chain;
2499         }
2500
2501         Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes);
2502
2503         // tally up portal and point counts
2504         p = portalchain;
2505         numportals = 0;
2506         numpoints = 0;
2507         while (p)
2508         {
2509                 // note: this check must match the one below or it will usually corrupt memory
2510                 // 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
2511                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2512                 {
2513                         numportals += 2;
2514                         numpoints += p->numpoints * 2;
2515                 }
2516                 p = p->chain;
2517         }
2518         loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
2519         loadmodel->brush.num_portals = numportals;
2520         loadmodel->brush.data_portalpoints = (mvertex_t *)((qbyte *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
2521         loadmodel->brush.num_portalpoints = numpoints;
2522         // clear all leaf portal chains
2523         for (i = 0;i < loadmodel->brush.num_leafs;i++)
2524                 loadmodel->brush.data_leafs[i].portals = NULL;
2525         // process all portals in the global portal chain, while freeing them
2526         portal = loadmodel->brush.data_portals;
2527         point = loadmodel->brush.data_portalpoints;
2528         p = portalchain;
2529         portalchain = NULL;
2530         while (p)
2531         {
2532                 pnext = p->chain;
2533
2534                 // note: this check must match the one above or it will usually corrupt memory
2535                 // 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
2536                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2537                 {
2538                         // first make the back to front portal(forward portal)
2539                         portal->points = point;
2540                         portal->numpoints = p->numpoints;
2541                         portal->plane.dist = p->plane.dist;
2542                         VectorCopy(p->plane.normal, portal->plane.normal);
2543                         portal->here = (mleaf_t *)p->nodes[1];
2544                         portal->past = (mleaf_t *)p->nodes[0];
2545                         // copy points
2546                         for (j = 0;j < portal->numpoints;j++)
2547                         {
2548                                 VectorCopy(p->points + j*3, point->position);
2549                                 point++;
2550                         }
2551                         BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
2552                         PlaneClassify(&portal->plane);
2553
2554                         // link into leaf's portal chain
2555                         portal->next = portal->here->portals;
2556                         portal->here->portals = portal;
2557
2558                         // advance to next portal
2559                         portal++;
2560
2561                         // then make the front to back portal(backward portal)
2562                         portal->points = point;
2563                         portal->numpoints = p->numpoints;
2564                         portal->plane.dist = -p->plane.dist;
2565                         VectorNegate(p->plane.normal, portal->plane.normal);
2566                         portal->here = (mleaf_t *)p->nodes[0];
2567                         portal->past = (mleaf_t *)p->nodes[1];
2568                         // copy points
2569                         for (j = portal->numpoints - 1;j >= 0;j--)
2570                         {
2571                                 VectorCopy(p->points + j*3, point->position);
2572                                 point++;
2573                         }
2574                         BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
2575                         PlaneClassify(&portal->plane);
2576
2577                         // link into leaf's portal chain
2578                         portal->next = portal->here->portals;
2579                         portal->here->portals = portal;
2580
2581                         // advance to next portal
2582                         portal++;
2583                 }
2584                 FreePortal(p);
2585                 p = pnext;
2586         }
2587 }
2588
2589 /*
2590 =============
2591 AddPortalToNodes
2592 =============
2593 */
2594 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
2595 {
2596         if (!front)
2597                 Host_Error("AddPortalToNodes: NULL front node");
2598         if (!back)
2599                 Host_Error("AddPortalToNodes: NULL back node");
2600         if (p->nodes[0] || p->nodes[1])
2601                 Host_Error("AddPortalToNodes: already included");
2602         // 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
2603
2604         p->nodes[0] = front;
2605         p->next[0] = (portal_t *)front->portals;
2606         front->portals = (mportal_t *)p;
2607
2608         p->nodes[1] = back;
2609         p->next[1] = (portal_t *)back->portals;
2610         back->portals = (mportal_t *)p;
2611 }
2612
2613 /*
2614 =============
2615 RemovePortalFromNode
2616 =============
2617 */
2618 static void RemovePortalFromNodes(portal_t *portal)
2619 {
2620         int i;
2621         mnode_t *node;
2622         void **portalpointer;
2623         portal_t *t;
2624         for (i = 0;i < 2;i++)
2625         {
2626                 node = portal->nodes[i];
2627
2628                 portalpointer = (void **) &node->portals;
2629                 while (1)
2630                 {
2631                         t = (portal_t *)*portalpointer;
2632                         if (!t)
2633                                 Host_Error("RemovePortalFromNodes: portal not in leaf");
2634
2635                         if (t == portal)
2636                         {
2637                                 if (portal->nodes[0] == node)
2638                                 {
2639                                         *portalpointer = portal->next[0];
2640                                         portal->nodes[0] = NULL;
2641                                 }
2642                                 else if (portal->nodes[1] == node)
2643                                 {
2644                                         *portalpointer = portal->next[1];
2645                                         portal->nodes[1] = NULL;
2646                                 }
2647                                 else
2648                                         Host_Error("RemovePortalFromNodes: portal not bounding leaf");
2649                                 break;
2650                         }
2651
2652                         if (t->nodes[0] == node)
2653                                 portalpointer = (void **) &t->next[0];
2654                         else if (t->nodes[1] == node)
2655                                 portalpointer = (void **) &t->next[1];
2656                         else
2657                                 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
2658                 }
2659         }
2660 }
2661
2662 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
2663 {
2664         int i, side;
2665         mnode_t *front, *back, *other_node;
2666         mplane_t clipplane, *plane;
2667         portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
2668         int numfrontpoints, numbackpoints;
2669         double frontpoints[3*MAX_PORTALPOINTS], backpoints[3*MAX_PORTALPOINTS];
2670
2671         // if a leaf, we're done
2672         if (!node->plane)
2673                 return;
2674
2675         plane = node->plane;
2676
2677         front = node->children[0];
2678         back = node->children[1];
2679         if (front == back)
2680                 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
2681
2682         // create the new portal by generating a polygon for the node plane,
2683         // and clipping it by all of the other portals(which came from nodes above this one)
2684         nodeportal = AllocPortal();
2685         nodeportal->plane = *plane;
2686
2687         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);
2688         nodeportal->numpoints = 4;
2689         side = 0;       // shut up compiler warning
2690         for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
2691         {
2692                 clipplane = portal->plane;
2693                 if (portal->nodes[0] == portal->nodes[1])
2694                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
2695                 if (portal->nodes[0] == node)
2696                         side = 0;
2697                 else if (portal->nodes[1] == node)
2698                 {
2699                         clipplane.dist = -clipplane.dist;
2700                         VectorNegate(clipplane.normal, clipplane.normal);
2701                         side = 1;
2702                 }
2703                 else
2704                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
2705
2706                 for (i = 0;i < nodeportal->numpoints*3;i++)
2707                         frontpoints[i] = nodeportal->points[i];
2708                 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);
2709                 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
2710                         break;
2711         }
2712
2713         if (nodeportal->numpoints < 3)
2714         {
2715                 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
2716                 nodeportal->numpoints = 0;
2717         }
2718         else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
2719         {
2720                 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
2721                 nodeportal->numpoints = 0;
2722         }
2723
2724         AddPortalToNodes(nodeportal, front, back);
2725
2726         // split the portals of this node along this node's plane and assign them to the children of this node
2727         // (migrating the portals downward through the tree)
2728         for (portal = (portal_t *)node->portals;portal;portal = nextportal)
2729         {
2730                 if (portal->nodes[0] == portal->nodes[1])
2731                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
2732                 if (portal->nodes[0] == node)
2733                         side = 0;
2734                 else if (portal->nodes[1] == node)
2735                         side = 1;
2736                 else
2737                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
2738                 nextportal = portal->next[side];
2739                 if (!portal->numpoints)
2740                         continue;
2741
2742                 other_node = portal->nodes[!side];
2743                 RemovePortalFromNodes(portal);
2744
2745                 // cut the portal into two portals, one on each side of the node plane
2746                 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);
2747
2748                 if (!numfrontpoints)
2749                 {
2750                         if (side == 0)
2751                                 AddPortalToNodes(portal, back, other_node);
2752                         else
2753                                 AddPortalToNodes(portal, other_node, back);
2754                         continue;
2755                 }
2756                 if (!numbackpoints)
2757                 {
2758                         if (side == 0)
2759                                 AddPortalToNodes(portal, front, other_node);
2760                         else
2761                                 AddPortalToNodes(portal, other_node, front);
2762                         continue;
2763                 }
2764
2765                 // the portal is split
2766                 splitportal = AllocPortal();
2767                 temp = splitportal->chain;
2768                 *splitportal = *portal;
2769                 splitportal->chain = temp;
2770                 for (i = 0;i < numbackpoints*3;i++)
2771                         splitportal->points[i] = backpoints[i];
2772                 splitportal->numpoints = numbackpoints;
2773                 for (i = 0;i < numfrontpoints*3;i++)
2774                         portal->points[i] = frontpoints[i];
2775                 portal->numpoints = numfrontpoints;
2776
2777                 if (side == 0)
2778                 {
2779                         AddPortalToNodes(portal, front, other_node);
2780                         AddPortalToNodes(splitportal, back, other_node);
2781                 }
2782                 else
2783                 {
2784                         AddPortalToNodes(portal, other_node, front);
2785                         AddPortalToNodes(splitportal, other_node, back);
2786                 }
2787         }
2788
2789         Mod_Q1BSP_RecursiveNodePortals(front);
2790         Mod_Q1BSP_RecursiveNodePortals(back);
2791 }
2792
2793 static void Mod_Q1BSP_MakePortals(void)
2794 {
2795         portalchain = NULL;
2796         Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes);
2797         Mod_Q1BSP_FinalizePortals();
2798 }
2799
2800 static void Mod_Q1BSP_BuildLightmapUpdateChains(mempool_t *mempool, model_t *model)
2801 {
2802         int i, j, stylecounts[256], totalcount, remapstyles[256];
2803         msurface_t *surface;
2804         memset(stylecounts, 0, sizeof(stylecounts));
2805         for (i = 0;i < model->nummodelsurfaces;i++)
2806         {
2807                 surface = model->data_surfaces + model->firstmodelsurface + i;
2808                 for (j = 0;j < MAXLIGHTMAPS;j++)
2809                         stylecounts[surface->lightmapinfo->styles[j]]++;
2810         }
2811         totalcount = 0;
2812         model->brushq1.light_styles = 0;
2813         for (i = 0;i < 255;i++)
2814         {
2815                 if (stylecounts[i])
2816                 {
2817                         remapstyles[i] = model->brushq1.light_styles++;
2818                         totalcount += stylecounts[i] + 1;
2819                 }
2820         }
2821         if (!totalcount)
2822                 return;
2823         model->brushq1.light_style = (qbyte *)Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(qbyte));
2824         model->brushq1.light_stylevalue = (int *)Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(int));
2825         model->brushq1.light_styleupdatechains = (msurface_t ***)Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(msurface_t **));
2826         model->brushq1.light_styleupdatechainsbuffer = (msurface_t **)Mem_Alloc(mempool, totalcount * sizeof(msurface_t *));
2827         model->brushq1.light_styles = 0;
2828         for (i = 0;i < 255;i++)
2829                 if (stylecounts[i])
2830                         model->brushq1.light_style[model->brushq1.light_styles++] = i;
2831         j = 0;
2832         for (i = 0;i < model->brushq1.light_styles;i++)
2833         {
2834                 model->brushq1.light_styleupdatechains[i] = model->brushq1.light_styleupdatechainsbuffer + j;
2835                 j += stylecounts[model->brushq1.light_style[i]] + 1;
2836         }
2837         for (i = 0;i < model->nummodelsurfaces;i++)
2838         {
2839                 surface = model->data_surfaces + model->firstmodelsurface + i;
2840                 for (j = 0;j < MAXLIGHTMAPS;j++)
2841                         if (surface->lightmapinfo->styles[j] != 255)
2842                                 *model->brushq1.light_styleupdatechains[remapstyles[surface->lightmapinfo->styles[j]]]++ = surface;
2843         }
2844         j = 0;
2845         for (i = 0;i < model->brushq1.light_styles;i++)
2846         {
2847                 *model->brushq1.light_styleupdatechains[i] = NULL;
2848                 model->brushq1.light_styleupdatechains[i] = model->brushq1.light_styleupdatechainsbuffer + j;
2849                 j += stylecounts[model->brushq1.light_style[i]] + 1;
2850         }
2851 }
2852
2853 //Returns PVS data for a given point
2854 //(note: can return NULL)
2855 static qbyte *Mod_Q1BSP_GetPVS(model_t *model, const vec3_t p)
2856 {
2857         mnode_t *node;
2858         Mod_CheckLoaded(model);
2859         node = model->brush.data_nodes;
2860         while (node->plane)
2861                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
2862         if (((mleaf_t *)node)->clusterindex >= 0)
2863                 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
2864         else
2865                 return NULL;
2866 }
2867
2868 static void Mod_Q1BSP_FatPVS_RecursiveBSPNode(model_t *model, const vec3_t org, vec_t radius, qbyte *pvsbuffer, int pvsbytes, mnode_t *node)
2869 {
2870         while (node->plane)
2871         {
2872                 float d = PlaneDiff(org, node->plane);
2873                 if (d > radius)
2874                         node = node->children[0];
2875                 else if (d < -radius)
2876                         node = node->children[1];
2877                 else
2878                 {
2879                         // go down both sides
2880                         Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
2881                         node = node->children[1];
2882                 }
2883         }
2884         // if this leaf is in a cluster, accumulate the pvs bits
2885         if (((mleaf_t *)node)->clusterindex >= 0)
2886         {
2887                 int i;
2888                 qbyte *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
2889                 for (i = 0;i < pvsbytes;i++)
2890                         pvsbuffer[i] |= pvs[i];
2891         }
2892 }
2893
2894 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
2895 //of the given point.
2896 static int Mod_Q1BSP_FatPVS(model_t *model, const vec3_t org, vec_t radius, qbyte *pvsbuffer, int pvsbufferlength)
2897 {
2898         int bytes = model->brush.num_pvsclusterbytes;
2899         bytes = min(bytes, pvsbufferlength);
2900         if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
2901         {
2902                 memset(pvsbuffer, 0xFF, bytes);
2903                 return bytes;
2904         }
2905         memset(pvsbuffer, 0, bytes);
2906         Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes);
2907         return bytes;
2908 }
2909
2910 static void Mod_Q1BSP_RoundUpToHullSize(model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
2911 {
2912         vec3_t size;
2913         const hull_t *hull;
2914
2915         VectorSubtract(inmaxs, inmins, size);
2916         if (cmodel->brush.ismcbsp)
2917         {
2918                 if (size[0] < 3)
2919                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2920                 else if (size[2] < 48) // pick the nearest of 40 or 56
2921                         hull = &cmodel->brushq1.hulls[2]; // 16x16x40
2922                 else
2923                         hull = &cmodel->brushq1.hulls[1]; // 16x16x56
2924         }
2925         else if (cmodel->brush.ishlbsp)
2926         {
2927                 if (size[0] < 3)
2928                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2929                 else if (size[0] <= 32)
2930                 {
2931                         if (size[2] < 54) // pick the nearest of 36 or 72
2932                                 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
2933                         else
2934                                 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
2935                 }
2936                 else
2937                         hull = &cmodel->brushq1.hulls[2]; // 64x64x64
2938         }
2939         else
2940         {
2941                 if (size[0] < 3)
2942                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2943                 else if (size[0] <= 32)
2944                         hull = &cmodel->brushq1.hulls[1]; // 32x32x56
2945                 else
2946                         hull = &cmodel->brushq1.hulls[2]; // 64x64x88
2947         }
2948         VectorCopy(inmins, outmins);
2949         VectorAdd(inmins, hull->clip_size, outmaxs);
2950 }
2951
2952 void Mod_Q1BSP_Load(model_t *mod, void *buffer, void *bufferend)
2953 {
2954         int i, j, k;
2955         dheader_t *header;
2956         dmodel_t *bm;
2957         mempool_t *mainmempool;
2958         float dist, modelyawradius, modelradius, *vec;
2959         msurface_t *surface;
2960         int numshadowmeshtriangles;
2961         dheader_t _header;
2962         hullinfo_t hullinfo;
2963
2964         mod->type = mod_brushq1;
2965
2966         if (!memcmp (buffer, "MCBSPpad", 8))
2967         {
2968                 qbyte   *index;
2969
2970                 mod->brush.ismcbsp = true;
2971                 mod->brush.ishlbsp = false;
2972
2973                 mod_base = (qbyte*)buffer;
2974
2975                 index = mod_base;
2976                 index += 8;
2977                 i = SB_ReadInt (&index);
2978                 if (i != MCBSPVERSION)
2979                         Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i)", mod->name, i, MCBSPVERSION);
2980
2981         // read hull info
2982                 hullinfo.numhulls = LittleLong(*(int*)index); index += 4;
2983                 hullinfo.filehulls = hullinfo.numhulls;
2984                 VectorClear (hullinfo.hullsizes[0][0]);
2985                 VectorClear (hullinfo.hullsizes[0][1]);
2986                 for (i = 1; i < hullinfo.numhulls; i++)
2987                 {
2988                         hullinfo.hullsizes[i][0][0] = SB_ReadFloat (&index);
2989                         hullinfo.hullsizes[i][0][1] = SB_ReadFloat (&index);
2990                         hullinfo.hullsizes[i][0][2] = SB_ReadFloat (&index);
2991                         hullinfo.hullsizes[i][1][0] = SB_ReadFloat (&index);
2992                         hullinfo.hullsizes[i][1][1] = SB_ReadFloat (&index);
2993                         hullinfo.hullsizes[i][1][2] = SB_ReadFloat (&index);
2994                 }
2995
2996         // read lumps
2997                 _header.version = 0;
2998                 for (i = 0; i < HEADER_LUMPS; i++)
2999                 {
3000                         _header.lumps[i].fileofs = SB_ReadInt (&index);
3001                         _header.lumps[i].filelen = SB_ReadInt (&index);
3002                 }
3003
3004                 header = &_header;
3005         }
3006         else
3007         {
3008                 header = (dheader_t *)buffer;
3009
3010                 i = LittleLong(header->version);
3011                 if (i != BSPVERSION && i != 30)
3012                         Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3013                 mod->brush.ishlbsp = i == 30;
3014                 mod->brush.ismcbsp = false;
3015
3016         // fill in hull info
3017                 VectorClear (hullinfo.hullsizes[0][0]);
3018                 VectorClear (hullinfo.hullsizes[0][1]);
3019                 if (mod->brush.ishlbsp)
3020                 {
3021                         hullinfo.numhulls = 4;
3022                         hullinfo.filehulls = 4;
3023                         VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3024                         VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3025                         VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3026                         VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3027                         VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3028                         VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3029                 }
3030                 else
3031                 {
3032                         hullinfo.numhulls = 3;
3033                         hullinfo.filehulls = 4;
3034                         VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3035                         VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3036                         VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3037                         VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3038                 }
3039
3040         // read lumps
3041                 mod_base = (qbyte*)buffer;
3042                 for (i = 0; i < HEADER_LUMPS; i++)
3043                 {
3044                         header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3045                         header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3046                 }
3047         }
3048
3049         mod->soundfromcenter = true;
3050         mod->TraceBox = Mod_Q1BSP_TraceBox;
3051         mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3052         mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3053         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3054         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3055         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3056         mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3057         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3058         mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3059         mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3060         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3061         mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3062         mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3063         mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3064
3065         if (loadmodel->isworldmodel)
3066         {
3067                 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
3068                 Cvar_SetValue("mcbsp", mod->brush.ismcbsp);
3069         }
3070
3071 // load into heap
3072
3073         // store which lightmap format to use
3074         mod->brushq1.lightmaprgba = r_lightmaprgba.integer;
3075
3076         Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3077         Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3078         Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3079         Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3080         Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3081         Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3082         Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3083         Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3084         Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3085         Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3086         Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3087         // load submodels before leafs because they contain the number of vis leafs
3088         Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3089         Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3090         Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3091         Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3092
3093         if (!mod->brushq1.lightdata)
3094                 mod->brush.LightPoint = NULL;
3095
3096         if (mod->brushq1.data_compressedpvs)
3097                 Mem_Free(mod->brushq1.data_compressedpvs);
3098         mod->brushq1.data_compressedpvs = NULL;
3099         mod->brushq1.num_compressedpvs = 0;
3100
3101         Mod_Q1BSP_MakeHull0();
3102         Mod_Q1BSP_MakePortals();
3103
3104         mod->numframes = 2;             // regular and alternate animation
3105         mod->numskins = 1;
3106
3107         mainmempool = mod->mempool;
3108
3109         Mod_Q1BSP_LoadLightList();
3110
3111         // make a single combined shadow mesh to allow optimized shadow volume creation
3112         numshadowmeshtriangles = 0;
3113         for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3114         {
3115                 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3116                 numshadowmeshtriangles += surface->num_triangles;
3117         }
3118         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3119         for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3120                 Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, surface->groupmesh->data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle));
3121         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true);
3122         Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
3123
3124         if (loadmodel->brush.numsubmodels)
3125                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
3126
3127         if (loadmodel->isworldmodel)
3128         {
3129                 // clear out any stale submodels or worldmodels lying around
3130                 // if we did this clear before now, an error might abort loading and
3131                 // leave things in a bad state
3132                 Mod_RemoveStaleWorldModels(loadmodel);
3133         }
3134
3135         // LordHavoc: to clear the fog around the original quake submodel code, I
3136         // will explain:
3137         // first of all, some background info on the submodels:
3138         // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3139         // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3140         // now the weird for loop itself:
3141         // the loop functions in an odd way, on each iteration it sets up the
3142         // current 'mod' model (which despite the confusing code IS the model of
3143         // the number i), at the end of the loop it duplicates the model to become
3144         // the next submodel, and loops back to set up the new submodel.
3145
3146         // LordHavoc: now the explanation of my sane way (which works identically):
3147         // set up the world model, then on each submodel copy from the world model
3148         // and set up the submodel with the respective model info.
3149         for (i = 0;i < mod->brush.numsubmodels;i++)
3150         {
3151                 // LordHavoc: this code was originally at the end of this loop, but
3152                 // has been transformed to something more readable at the start here.
3153
3154                 if (i > 0)
3155                 {
3156                         char name[10];
3157                         // LordHavoc: only register submodels if it is the world
3158                         // (prevents external bsp models from replacing world submodels with
3159                         //  their own)
3160                         if (!loadmodel->isworldmodel)
3161                                 continue;
3162                         // duplicate the basic information
3163                         sprintf(name, "*%i", i);
3164                         mod = Mod_FindName(name);
3165                         // copy the base model to this one
3166                         *mod = *loadmodel;
3167                         // rename the clone back to its proper name
3168                         strcpy(mod->name, name);
3169                         // textures and memory belong to the main model
3170                         mod->texturepool = NULL;
3171                         mod->mempool = NULL;
3172                 }
3173
3174                 mod->brush.submodel = i;
3175
3176                 if (loadmodel->brush.submodels)
3177                         loadmodel->brush.submodels[i] = mod;
3178
3179                 bm = &mod->brushq1.submodels[i];
3180
3181                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3182                 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3183                 {
3184                         mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3185                         mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3186                 }
3187
3188                 mod->firstmodelsurface = bm->firstface;
3189                 mod->nummodelsurfaces = bm->numfaces;
3190
3191                 // make the model surface list (used by shadowing/lighting)
3192                 mod->surfacelist = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->surfacelist));
3193                 for (j = 0;j < mod->nummodelsurfaces;j++)
3194                         mod->surfacelist[j] = mod->firstmodelsurface + j;
3195
3196                 // this gets altered below if sky is used
3197                 mod->DrawSky = NULL;
3198                 mod->Draw = R_Q1BSP_Draw;
3199                 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3200                 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3201                 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3202                 mod->DrawLight = R_Q1BSP_DrawLight;
3203                 if (i != 0)
3204                 {
3205                         mod->brush.GetPVS = NULL;
3206                         mod->brush.FatPVS = NULL;
3207                         mod->brush.BoxTouchingPVS = NULL;
3208                         mod->brush.BoxTouchingLeafPVS = NULL;
3209                         mod->brush.BoxTouchingVisibleLeafs = NULL;
3210                         mod->brush.FindBoxClusters = NULL;
3211                         mod->brush.LightPoint = NULL;
3212                         mod->brush.AmbientSoundLevelsForPoint = NULL;
3213                 }
3214                 Mod_Q1BSP_BuildLightmapUpdateChains(loadmodel->mempool, mod);
3215                 if (mod->nummodelsurfaces)
3216                 {
3217                         // LordHavoc: calculate bmodel bounding box rather than trusting what it says
3218                         mod->normalmins[0] = mod->normalmins[1] = mod->normalmins[2] = 1000000000.0f;
3219                         mod->normalmaxs[0] = mod->normalmaxs[1] = mod->normalmaxs[2] = -1000000000.0f;
3220                         modelyawradius = 0;
3221                         modelradius = 0;
3222                         for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3223                         {
3224                                 // we only need to have a drawsky function if it is used(usually only on world model)
3225                                 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3226                                         mod->DrawSky = R_Q1BSP_DrawSky;
3227                                 // calculate bounding shapes
3228                                 for (k = 0, vec = (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex);k < surface->num_vertices;k++, vec += 3)
3229                                 {
3230                                         if (mod->normalmins[0] > vec[0]) mod->normalmins[0] = vec[0];
3231                                         if (mod->normalmins[1] > vec[1]) mod->normalmins[1] = vec[1];
3232                                         if (mod->normalmins[2] > vec[2]) mod->normalmins[2] = vec[2];
3233                                         if (mod->normalmaxs[0] < vec[0]) mod->normalmaxs[0] = vec[0];
3234                                         if (mod->normalmaxs[1] < vec[1]) mod->normalmaxs[1] = vec[1];
3235                                         if (mod->normalmaxs[2] < vec[2]) mod->normalmaxs[2] = vec[2];
3236                                         dist = vec[0]*vec[0]+vec[1]*vec[1];
3237                                         if (modelyawradius < dist)
3238                                                 modelyawradius = dist;
3239                                         dist += vec[2]*vec[2];
3240                                         if (modelradius < dist)
3241                                                 modelradius = dist;
3242                                 }
3243                         }
3244                         modelyawradius = sqrt(modelyawradius);
3245                         modelradius = sqrt(modelradius);
3246                         mod->yawmins[0] = mod->yawmins[1] = - (mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius);
3247                         mod->yawmins[2] = mod->normalmins[2];
3248                         mod->yawmaxs[2] = mod->normalmaxs[2];
3249                         mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3250                         mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3251                         mod->radius = modelradius;
3252                         mod->radius2 = modelradius * modelradius;
3253                 }
3254                 else
3255                 {
3256                         // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3257                         Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3258                 }
3259                 //mod->brushq1.num_visleafs = bm->visleafs;
3260         }
3261
3262         Mod_Q1BSP_LoadMapBrushes();
3263
3264         //Mod_Q1BSP_ProcessLightList();
3265
3266         if (developer.integer)
3267                 Con_Printf("Some stats for q1bsp model \"%s\": %i faces, %i nodes, %i leafs, %i visleafs, %i visleafportals\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals);
3268 }
3269
3270 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3271 {
3272 }
3273
3274 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3275 {
3276 /*
3277         d_t *in;
3278         m_t *out;
3279         int i, count;
3280
3281         in = (void *)(mod_base + l->fileofs);
3282         if (l->filelen % sizeof(*in))
3283                 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3284         count = l->filelen / sizeof(*in);
3285         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3286
3287         loadmodel-> = out;
3288         loadmodel->num = count;
3289
3290         for (i = 0;i < count;i++, in++, out++)
3291         {
3292         }
3293 */
3294 }
3295
3296 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3297 {
3298 /*
3299         d_t *in;
3300         m_t *out;
3301         int i, count;
3302
3303         in = (void *)(mod_base + l->fileofs);
3304         if (l->filelen % sizeof(*in))
3305                 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3306         count = l->filelen / sizeof(*in);
3307         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3308
3309         loadmodel-> = out;
3310         loadmodel->num = count;
3311
3312         for (i = 0;i < count;i++, in++, out++)
3313         {
3314         }
3315 */
3316 }
3317
3318 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3319 {
3320 /*
3321         d_t *in;
3322         m_t *out;
3323         int i, count;
3324
3325         in = (void *)(mod_base + l->fileofs);
3326         if (l->filelen % sizeof(*in))
3327                 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3328         count = l->filelen / sizeof(*in);
3329         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3330
3331         loadmodel-> = out;
3332         loadmodel->num = count;
3333
3334         for (i = 0;i < count;i++, in++, out++)
3335         {
3336         }
3337 */
3338 }
3339
3340 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3341 {
3342 /*
3343         d_t *in;
3344         m_t *out;
3345         int i, count;
3346
3347         in = (void *)(mod_base + l->fileofs);
3348         if (l->filelen % sizeof(*in))
3349                 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3350         count = l->filelen / sizeof(*in);
3351         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3352
3353         loadmodel-> = out;
3354         loadmodel->num = count;
3355
3356         for (i = 0;i < count;i++, in++, out++)
3357         {
3358         }
3359 */
3360 }
3361
3362 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3363 {
3364 /*
3365         d_t *in;
3366         m_t *out;
3367         int i, count;
3368
3369         in = (void *)(mod_base + l->fileofs);
3370         if (l->filelen % sizeof(*in))
3371                 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3372         count = l->filelen / sizeof(*in);
3373         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3374
3375         loadmodel-> = out;
3376         loadmodel->num = count;
3377
3378         for (i = 0;i < count;i++, in++, out++)
3379         {
3380         }
3381 */
3382 }
3383
3384 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3385 {
3386 /*
3387         d_t *in;
3388         m_t *out;
3389         int i, count;
3390
3391         in = (void *)(mod_base + l->fileofs);
3392         if (l->filelen % sizeof(*in))
3393                 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3394         count = l->filelen / sizeof(*in);
3395         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3396
3397         loadmodel-> = out;
3398         loadmodel->num = count;
3399
3400         for (i = 0;i < count;i++, in++, out++)
3401         {
3402         }
3403 */
3404 }
3405
3406 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3407 {
3408 /*
3409         d_t *in;
3410         m_t *out;
3411         int i, count;