]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - model_brush.c
f7bb4243b244d82bb75e4f4afa18522ccb8f1cdb
[xonotic/darkplaces.git] / model_brush.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24 #include "polygon.h"
25 #include "curves.h"
26 #include "wad.h"
27
28
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128"};
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;
3412
3413         in = (void *)(mod_base + l->fileofs);
3414         if (l->filelen % sizeof(*in))
3415                 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3416         count = l->filelen / sizeof(*in);
3417         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3418
3419         loadmodel-> = out;
3420         loadmodel->num = count;
3421
3422         for (i = 0;i < count;i++, in++, out++)
3423         {
3424         }
3425 */
3426 }
3427
3428 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3429 {
3430 /*
3431         d_t *in;
3432         m_t *out;
3433         int i, count;
3434
3435         in = (void *)(mod_base + l->fileofs);
3436         if (l->filelen % sizeof(*in))
3437                 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3438         count = l->filelen / sizeof(*in);
3439         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3440
3441         loadmodel-> = out;
3442         loadmodel->num = count;
3443
3444         for (i = 0;i < count;i++, in++, out++)
3445         {
3446         }
3447 */
3448 }
3449
3450 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3451 {
3452 /*
3453         d_t *in;
3454         m_t *out;
3455         int i, count;
3456
3457         in = (void *)(mod_base + l->fileofs);
3458         if (l->filelen % sizeof(*in))
3459                 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3460         count = l->filelen / sizeof(*in);
3461         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3462
3463         loadmodel-> = out;
3464         loadmodel->num = count;
3465
3466         for (i = 0;i < count;i++, in++, out++)
3467         {
3468         }
3469 */
3470 }
3471
3472 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3473 {
3474 /*
3475         d_t *in;
3476         m_t *out;
3477         int i, count;
3478
3479         in = (void *)(mod_base + l->fileofs);
3480         if (l->filelen % sizeof(*in))
3481                 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3482         count = l->filelen / sizeof(*in);
3483         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3484
3485         loadmodel-> = out;
3486         loadmodel->num = count;
3487
3488         for (i = 0;i < count;i++, in++, out++)
3489         {
3490         }
3491 */
3492 }
3493
3494 static void Mod_Q2BSP_LoadEdges(lump_t *l)
3495 {
3496 /*
3497         d_t *in;
3498         m_t *out;
3499         int i, count;
3500
3501         in = (void *)(mod_base + l->fileofs);
3502         if (l->filelen % sizeof(*in))
3503                 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
3504         count = l->filelen / sizeof(*in);
3505         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3506
3507         loadmodel-> = out;
3508         loadmodel->num = count;
3509
3510         for (i = 0;i < count;i++, in++, out++)
3511         {
3512         }
3513 */
3514 }
3515
3516 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
3517 {
3518 /*
3519         d_t *in;
3520         m_t *out;
3521         int i, count;
3522
3523         in = (void *)(mod_base + l->fileofs);
3524         if (l->filelen % sizeof(*in))
3525                 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
3526         count = l->filelen / sizeof(*in);
3527         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3528
3529         loadmodel-> = out;
3530         loadmodel->num = count;
3531
3532         for (i = 0;i < count;i++, in++, out++)
3533         {
3534         }
3535 */
3536 }
3537
3538 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
3539 {
3540 /*
3541         d_t *in;
3542         m_t *out;
3543         int i, count;
3544
3545         in = (void *)(mod_base + l->fileofs);
3546         if (l->filelen % sizeof(*in))
3547                 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
3548         count = l->filelen / sizeof(*in);
3549         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3550
3551         loadmodel-> = out;
3552         loadmodel->num = count;
3553
3554         for (i = 0;i < count;i++, in++, out++)
3555         {
3556         }
3557 */
3558 }
3559
3560 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
3561 {
3562 /*
3563         d_t *in;
3564         m_t *out;
3565         int i, count;
3566
3567         in = (void *)(mod_base + l->fileofs);
3568         if (l->filelen % sizeof(*in))
3569                 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
3570         count = l->filelen / sizeof(*in);
3571         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3572
3573         loadmodel-> = out;
3574         loadmodel->num = count;
3575
3576         for (i = 0;i < count;i++, in++, out++)
3577         {
3578         }
3579 */
3580 }
3581
3582 static void Mod_Q2BSP_LoadAreas(lump_t *l)
3583 {
3584 /*
3585         d_t *in;
3586         m_t *out;
3587         int i, count;
3588
3589         in = (void *)(mod_base + l->fileofs);
3590         if (l->filelen % sizeof(*in))
3591                 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
3592         count = l->filelen / sizeof(*in);
3593         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3594
3595         loadmodel-> = out;
3596         loadmodel->num = count;
3597
3598         for (i = 0;i < count;i++, in++, out++)
3599         {
3600         }
3601 */
3602 }
3603
3604 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
3605 {
3606 /*
3607         d_t *in;
3608         m_t *out;
3609         int i, count;
3610
3611         in = (void *)(mod_base + l->fileofs);
3612         if (l->filelen % sizeof(*in))
3613                 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
3614         count = l->filelen / sizeof(*in);
3615         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3616
3617         loadmodel-> = out;
3618         loadmodel->num = count;
3619
3620         for (i = 0;i < count;i++, in++, out++)
3621         {
3622         }
3623 */
3624 }
3625
3626 static void Mod_Q2BSP_LoadModels(lump_t *l)
3627 {
3628 /*
3629         d_t *in;
3630         m_t *out;
3631         int i, count;
3632
3633         in = (void *)(mod_base + l->fileofs);
3634         if (l->filelen % sizeof(*in))
3635                 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
3636         count = l->filelen / sizeof(*in);
3637         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3638
3639         loadmodel-> = out;
3640         loadmodel->num = count;
3641
3642         for (i = 0;i < count;i++, in++, out++)
3643         {
3644         }
3645 */
3646 }
3647
3648 void static Mod_Q2BSP_Load(model_t *mod, void *buffer, void *bufferend)
3649 {
3650         int i;
3651         q2dheader_t *header;
3652
3653         Host_Error("Mod_Q2BSP_Load: not yet implemented\n");
3654
3655         mod->type = mod_brushq2;
3656
3657         header = (q2dheader_t *)buffer;
3658
3659         i = LittleLong(header->version);
3660         if (i != Q2BSPVERSION)
3661                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
3662         mod->brush.ishlbsp = false;
3663         mod->brush.ismcbsp = false;
3664         if (loadmodel->isworldmodel)
3665         {
3666                 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
3667                 Cvar_SetValue("mcbsp", mod->brush.ismcbsp);
3668         }
3669
3670         mod_base = (qbyte *)header;
3671
3672         // swap all the lumps
3673         for (i = 0;i < (int) sizeof(*header) / 4;i++)
3674                 ((int *)header)[i] = LittleLong(((int *)header)[i]);
3675
3676         // store which lightmap format to use
3677         mod->brushq1.lightmaprgba = r_lightmaprgba.integer;
3678
3679         Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
3680         Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
3681         Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
3682         Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
3683         Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
3684         Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
3685         Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
3686         Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
3687         Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
3688         Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
3689         Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
3690         Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
3691         Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
3692         Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
3693         Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
3694         Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
3695         Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
3696         // LordHavoc: must go last because this makes the submodels
3697         Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
3698 }
3699
3700 static int Mod_Q3BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents);
3701 static int Mod_Q3BSP_NativeContentsFromSuperContents(model_t *model, int supercontents);
3702
3703 static void Mod_Q3BSP_LoadEntities(lump_t *l)
3704 {
3705         const char *data;
3706         char key[128], value[4096];
3707         float v[3];
3708         loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
3709         loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
3710         loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
3711         if (!l->filelen)
3712                 return;
3713         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen);
3714         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
3715         data = loadmodel->brush.entities;
3716         // some Q3 maps override the lightgrid_cellsize with a worldspawn key
3717         if (data && COM_ParseToken(&data, false) && com_token[0] == '{')
3718         {
3719                 while (1)
3720                 {
3721                         if (!COM_ParseToken(&data, false))
3722                                 break; // error
3723                         if (com_token[0] == '}')
3724                                 break; // end of worldspawn
3725                         if (com_token[0] == '_')
3726                                 strcpy(key, com_token + 1);
3727                         else
3728                                 strcpy(key, com_token);
3729                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
3730                                 key[strlen(key)-1] = 0;
3731                         if (!COM_ParseToken(&data, false))
3732                                 break; // error
3733                         strcpy(value, com_token);
3734                         if (!strcmp("gridsize", key))
3735                         {
3736                                 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
3737                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
3738                         }
3739                 }
3740         }
3741 }
3742
3743 static void Mod_Q3BSP_LoadTextures(lump_t *l)
3744 {
3745         q3dtexture_t *in;
3746         texture_t *out;
3747         int i, count;
3748         int j, c;
3749         fssearch_t *search;
3750         char *f;
3751         const char *text;
3752         int flags, flags2, numparameters, passnumber;
3753         char shadername[Q3PATHLENGTH];
3754         char sky[Q3PATHLENGTH];
3755         char firstpasstexturename[Q3PATHLENGTH];
3756         char parameter[4][Q3PATHLENGTH];
3757
3758         in = (q3dtexture_t *)(mod_base + l->fileofs);
3759         if (l->filelen % sizeof(*in))
3760                 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
3761         count = l->filelen / sizeof(*in);
3762         out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3763
3764         loadmodel->data_textures = out;
3765         loadmodel->num_textures = count;
3766
3767         for (i = 0;i < count;i++, in++, out++)
3768         {
3769                 strlcpy (out->name, in->name, sizeof (out->name));
3770                 out->surfaceflags = LittleLong(in->surfaceflags);
3771                 out->supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in->contents));
3772                 out->surfaceparms = -1;
3773         }
3774
3775         // do a quick parse of shader files to get surfaceparms
3776         if ((search = FS_Search("scripts/*.shader", true, false)))
3777         {
3778                 for (i = 0;i < search->numfilenames;i++)
3779                 {
3780                         if ((f = (char *)FS_LoadFile(search->filenames[i], tempmempool, false)))
3781                         {
3782                                 text = f;
3783                                 while (COM_ParseToken(&text, false))
3784                                 {
3785                                         strlcpy (shadername, com_token, sizeof (shadername));
3786                                         flags = 0;
3787                                         flags2 = 0;
3788                                         sky[0] = 0;
3789                                         passnumber = 0;
3790                                         firstpasstexturename[0] = 0;
3791                                         if (COM_ParseToken(&text, false) && !strcasecmp(com_token, "{"))
3792                                         {
3793                                                 while (COM_ParseToken(&text, false))
3794                                                 {
3795                                                         if (!strcasecmp(com_token, "}"))
3796                                                                 break;
3797                                                         else if (!strcasecmp(com_token, "{"))
3798                                                         {
3799                                                                 while (COM_ParseToken(&text, false))
3800                                                                 {
3801                                                                         if (!strcasecmp(com_token, "}"))
3802                                                                                 break;
3803                                                                         if (!strcasecmp(com_token, "\n"))
3804                                                                                 continue;
3805                                                                         numparameters = 0;
3806                                                                         for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
3807                                                                         {
3808                                                                                 if (j < 4)
3809                                                                                 {
3810                                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
3811                                                                                         numparameters = j + 1;
3812                                                                                 }
3813                                                                                 if (!COM_ParseToken(&text, true))
3814                                                                                         break;
3815                                                                         }
3816                                                                         if (developer.integer >= 2)
3817                                                                         {
3818                                                                                 Con_Printf("%s %i: ", shadername, passnumber);
3819                                                                                 for (j = 0;j < numparameters;j++)
3820                                                                                         Con_Printf(" %s", parameter[j]);
3821                                                                                 Con_Print("\n");
3822                                                                         }
3823                                                                         if (passnumber == 0 && numparameters >= 1)
3824                                                                         {
3825                                                                                 if (!strcasecmp(parameter[0], "blendfunc") && (flags & Q3SURFACEPARM_TRANS))
3826                                                                                 {
3827                                                                                         if (numparameters == 2 && !strcasecmp(parameter[1], "add"))
3828                                                                                                 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3829                                                                                         else if (numparameters == 3 && !strcasecmp(parameter[1], "gl_one") && !strcasecmp(parameter[2], "gl_one"))
3830                                                                                                 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3831                                                                                         else if (numparameters == 3 && !strcasecmp(parameter[1], "gl_src_alpha") && !strcasecmp(parameter[2], "gl_one"))
3832                                                                                                 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3833                                                                                 }
3834                                                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
3835                                                                                         strlcpy(firstpasstexturename, parameter[1], sizeof(firstpasstexturename));
3836                                                                                 else if (numparameters >= 3 && !strcasecmp(parameter[0], "animmap"))
3837                                                                                         strlcpy(firstpasstexturename, parameter[2], sizeof(firstpasstexturename));
3838                                                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
3839                                                                                         flags2 |= Q3TEXTUREFLAG_ALPHATEST;
3840                                                                         }
3841                                                                         // break out a level if it was }
3842                                                                         if (!strcasecmp(com_token, "}"))
3843                                                                                 break;
3844                                                                 }
3845                                                                 passnumber++;
3846                                                                 continue;
3847                                                         }
3848                                                         numparameters = 0;
3849                                                         for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
3850                                                         {
3851                                                                 if (j < 4)
3852                                                                 {
3853                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
3854                                                                         numparameters = j + 1;
3855                                                                 }
3856                                                                 if (!COM_ParseToken(&text, true))
3857                                                                         break;
3858                                                         }
3859                                                         if (i == 0 && !strcasecmp(com_token, "}"))
3860                                                                 break;
3861                                                         if (developer.integer >= 2)
3862                                                         {
3863                                                                 Con_Printf("%s: ", shadername);
3864                                                                 for (j = 0;j < numparameters;j++)
3865                                                                         Con_Printf(" %s", parameter[j]);
3866                                                                 Con_Print("\n");
3867                                                         }
3868                                                         if (numparameters < 1)
3869                                                                 continue;
3870                                                         if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
3871                                                         {
3872                                                                 if (!strcasecmp(parameter[1], "alphashadow"))
3873                                                                         flags |= Q3SURFACEPARM_ALPHASHADOW;
3874                                                                 else if (!strcasecmp(parameter[1], "areaportal"))
3875                                                                         flags |= Q3SURFACEPARM_AREAPORTAL;
3876                                                                 else if (!strcasecmp(parameter[1], "clusterportal"))
3877                                                                         flags |= Q3SURFACEPARM_CLUSTERPORTAL;
3878                                                                 else if (!strcasecmp(parameter[1], "detail"))
3879                                                                         flags |= Q3SURFACEPARM_DETAIL;
3880                                                                 else if (!strcasecmp(parameter[1], "donotenter"))
3881                                                                         flags |= Q3SURFACEPARM_DONOTENTER;
3882                                                                 else if (!strcasecmp(parameter[1], "fog"))
3883                                                                         flags |= Q3SURFACEPARM_FOG;
3884                                                                 else if (!strcasecmp(parameter[1], "lava"))
3885                                                                         flags |= Q3SURFACEPARM_LAVA;
3886                                                                 else if (!strcasecmp(parameter[1], "lightfilter"))
3887                                                                         flags |= Q3SURFACEPARM_LIGHTFILTER;
3888                                                                 else if (!strcasecmp(parameter[1], "metalsteps"))
3889                                                                         flags |= Q3SURFACEPARM_METALSTEPS;
3890                                                                 else if (!strcasecmp(parameter[1], "nodamage"))
3891                                                                         flags |= Q3SURFACEPARM_NODAMAGE;
3892                                                                 else if (!strcasecmp(parameter[1], "nodlight"))
3893                                                                         flags |= Q3SURFACEPARM_NODLIGHT;
3894                                                                 else if (!strcasecmp(parameter[1], "nodraw"))
3895                                                                         flags |= Q3SURFACEPARM_NODRAW;
3896                                                                 else if (!strcasecmp(parameter[1], "nodrop"))
3897                                                                         flags |= Q3SURFACEPARM_NODROP;
3898                                                                 else if (!strcasecmp(parameter[1], "noimpact"))
3899                                                                         flags |= Q3SURFACEPARM_NOIMPACT;
3900                                                                 else if (!strcasecmp(parameter[1], "nolightmap"))
3901                                                                         flags |= Q3SURFACEPARM_NOLIGHTMAP;
3902                                                                 else if (!strcasecmp(parameter[1], "nomarks"))
3903                                                                         flags |= Q3SURFACEPARM_NOMARKS;
3904                                                                 else if (!strcasecmp(parameter[1], "nomipmaps"))
3905                                                                         flags |= Q3SURFACEPARM_NOMIPMAPS;
3906                                                                 else if (!strcasecmp(parameter[1], "nonsolid"))
3907                                                                         flags |= Q3SURFACEPARM_NONSOLID;
3908                                                                 else if (!strcasecmp(parameter[1], "origin"))
3909                                                                         flags |= Q3SURFACEPARM_ORIGIN;
3910                                                                 else if (!strcasecmp(parameter[1], "playerclip"))
3911                                                                         flags |= Q3SURFACEPARM_PLAYERCLIP;
3912                                                                 else if (!strcasecmp(parameter[1], "sky"))
3913                                                                         flags |= Q3SURFACEPARM_SKY;
3914                                                                 else if (!strcasecmp(parameter[1], "slick"))
3915                                                                         flags |= Q3SURFACEPARM_SLICK;
3916                                                                 else if (!strcasecmp(parameter[1], "slime"))
3917                                                                         flags |= Q3SURFACEPARM_SLIME;
3918                                                                 else if (!strcasecmp(parameter[1], "structural"))
3919                                                                         flags |= Q3SURFACEPARM_STRUCTURAL;
3920                                                                 else if (!strcasecmp(parameter[1], "trans"))
3921                                                                         flags |= Q3SURFACEPARM_TRANS;
3922                                                                 else if (!strcasecmp(parameter[1], "water"))
3923                                                                         flags |= Q3SURFACEPARM_WATER;
3924                                                                 else if (!strcasecmp(parameter[1], "pointlight"))
3925                                                                         flags |= Q3SURFACEPARM_POINTLIGHT;
3926                                                                 else
3927                                                                         Con_Printf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[i], parameter[1]);
3928                                                         }
3929                                                         else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
3930                                                                 strlcpy(sky, parameter[1], sizeof(sky));
3931                                                         else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
3932                                                         {
3933                                                                 if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
3934                                                                         strlcpy(sky, parameter[1], sizeof(sky));
3935                                                         }
3936                                                         else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
3937                                                         {
3938                                                                 if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
3939                                                                         flags2 |= Q3TEXTUREFLAG_TWOSIDED;
3940                                                         }
3941                                                         else if (!strcasecmp(parameter[0], "nomipmaps"))
3942                                                                 flags2 |= Q3TEXTUREFLAG_NOMIPMAPS;
3943                                                         else if (!strcasecmp(parameter[0], "nopicmip"))
3944                                                                 flags2 |= Q3TEXTUREFLAG_NOPICMIP;
3945                                                         else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
3946                                                         {
3947                                                                 if (!strcasecmp(parameter[1], "autosprite") && numparameters == 2)
3948                                                                         flags2 |= Q3TEXTUREFLAG_AUTOSPRITE;
3949                                                                 if (!strcasecmp(parameter[1], "autosprite2") && numparameters == 2)
3950                                                                         flags2 |= Q3TEXTUREFLAG_AUTOSPRITE2;
3951                                                         }
3952                                                 }
3953                                                 // add shader to list (shadername and flags)
3954                                                 // actually here we just poke into the texture settings
3955                                                 for (j = 0, out = loadmodel->data_textures;j < loadmodel->num_textures;j++, out++)
3956                                                 {
3957                                                         if (!strcasecmp(out->name, shadername))
3958                                                         {
3959                                                                 out->surfaceparms = flags;
3960                                                                 out->textureflags = flags2;
3961                                                                 out->basematerialflags = 0;
3962                                                                 if (out->surfaceparms & Q3SURFACEPARM_NODRAW)
3963                                                                         out->basematerialflags |= MATERIALFLAG_NODRAW;
3964                                                                 else if (out->surfaceparms & Q3SURFACEPARM_SKY)
3965                                                                         out->basematerialflags |= MATERIALFLAG_SKY;
3966                                                                 else if (out->surfaceparms & Q3SURFACEPARM_LAVA)
3967                                                                         out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_FULLBRIGHT;
3968                                                                 else if (out->surfaceparms & Q3SURFACEPARM_SLIME)
3969                                                                         out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_WATERALPHA;
3970                                                                 else if (out->surfaceparms & Q3SURFACEPARM_WATER)
3971                                                                         out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_WATERALPHA;
3972                                                                 else
3973                                                                         out->basematerialflags |= MATERIALFLAG_WALL;
3974                                                                 if (out->textureflags & Q3TEXTUREFLAG_ALPHATEST)
3975                                                                 {
3976                                                                         // FIXME: support alpha test?
3977                                                                         out->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
3978                                                                 }
3979                                                                 else if (out->surfaceparms & Q3SURFACEPARM_TRANS)
3980                                                                 {
3981                                                                         if (out->textureflags & Q3TEXTUREFLAG_ADDITIVE)
3982                                                                                 out->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_TRANSPARENT;
3983                                                                         else
3984                                                                                 out->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
3985                                                                 }
3986                                                                 strlcpy(out->firstpasstexturename, firstpasstexturename, sizeof(out->firstpasstexturename));
3987                                                                 if ((flags & Q3SURFACEPARM_SKY) && sky[0])
3988                                                                 {
3989                                                                         // quake3 seems to append a _ to the skybox name, so this must do so as well
3990                                                                         dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", sky);
3991                                                                 }
3992                                                         }
3993                                                 }
3994                                         }
3995                                         else
3996                                         {
3997                                                 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[i], com_token);
3998                                                 goto parseerror;
3999                                         }
4000                                 }
4001 parseerror:
4002                                 Mem_Free(f);
4003                         }
4004                 }
4005         }
4006
4007         c = 0;
4008         for (j = 0, out = loadmodel->data_textures;j < loadmodel->num_textures;j++, out++)
4009         {
4010                 if (out->surfaceparms == -1)
4011                 {
4012                         c++;
4013                         Con_DPrintf("%s: No shader found for texture \"%s\"\n", loadmodel->name, out->name);
4014                         out->surfaceparms = 0;
4015                         if (out->surfaceflags & Q3SURFACEFLAG_NODRAW)
4016                                 out->basematerialflags |= MATERIALFLAG_NODRAW;
4017                         else if (out->surfaceflags & Q3SURFACEFLAG_SKY)
4018                                 out->basematerialflags |= MATERIALFLAG_SKY;
4019                         else
4020                                 out->basematerialflags |= MATERIALFLAG_WALL;
4021                         // these are defaults
4022                         //if (!strncmp(out->name, "textures/skies/", 15))
4023                         //      out->surfaceparms |= Q3SURFACEPARM_SKY;
4024                         //if (!strcmp(out->name, "caulk") || !strcmp(out->name, "common/caulk") || !strcmp(out->name, "textures/common/caulk")
4025                         // || !strcmp(out->name, "nodraw") || !strcmp(out->name, "common/nodraw") || !strcmp(out->name, "textures/common/nodraw"))
4026                         //      out->surfaceparms |= Q3SURFACEPARM_NODRAW;
4027                         //if (R_TextureHasAlpha(out->skin.base))
4028                         //      out->surfaceparms |= Q3SURFACEPARM_TRANS;
4029                 }
4030                 if (!Mod_LoadSkinFrame(&out->skin, out->name, (((out->textureflags & Q3TEXTUREFLAG_NOMIPMAPS) || (out->surfaceparms & Q3SURFACEPARM_NOMIPMAPS)) ? 0 : TEXF_MIPMAP) | TEXF_ALPHA | TEXF_PRECACHE | (out->textureflags & Q3TEXTUREFLAG_NOPICMIP ? 0 : TEXF_PICMIP), false, true))
4031                         if (!Mod_LoadSkinFrame(&out->skin, out->firstpasstexturename, (((out->textureflags & Q3TEXTUREFLAG_NOMIPMAPS) || (out->surfaceparms & Q3SURFACEPARM_NOMIPMAPS)) ? 0 : TEXF_MIPMAP) | TEXF_ALPHA | TEXF_PRECACHE | (out->textureflags & Q3TEXTUREFLAG_NOPICMIP ? 0 : TEXF_PICMIP), false, true))
4032                                 if (cls.state != ca_dedicated)
4033                                         Con_Printf("%s: texture loading for shader \"%s\" failed (first layer \"%s\" not found either)\n", loadmodel->name, out->name, out->firstpasstexturename);
4034                 // no animation
4035                 out->currentframe = out;
4036         }
4037         if (c)
4038                 Con_DPrintf("%s: %i textures missing shaders\n", loadmodel->name, c);
4039 }
4040
4041 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4042 {
4043         q3dplane_t *in;
4044         mplane_t *out;
4045         int i, count;
4046
4047         in = (q3dplane_t *)(mod_base + l->fileofs);
4048         if (l->filelen % sizeof(*in))
4049                 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4050         count = l->filelen / sizeof(*in);
4051         out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4052
4053         loadmodel->brush.data_planes = out;
4054         loadmodel->brush.num_planes = count;
4055
4056         for (i = 0;i < count;i++, in++, out++)
4057         {
4058                 out->normal[0] = LittleFloat(in->normal[0]);
4059                 out->normal[1] = LittleFloat(in->normal[1]);
4060                 out->normal[2] = LittleFloat(in->normal[2]);
4061                 out->dist = LittleFloat(in->dist);
4062                 PlaneClassify(out);
4063         }
4064 }
4065
4066 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4067 {
4068         q3dbrushside_t *in;
4069         q3mbrushside_t *out;
4070         int i, n, count;
4071
4072         in = (q3dbrushside_t *)(mod_base + l->fileofs);
4073         if (l->filelen % sizeof(*in))
4074                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4075         count = l->filelen / sizeof(*in);
4076         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4077
4078         loadmodel->brush.data_brushsides = out;
4079         loadmodel->brush.num_brushsides = count;
4080
4081         for (i = 0;i < count;i++, in++, out++)
4082         {
4083                 n = LittleLong(in->planeindex);
4084                 if (n < 0 || n >= loadmodel->brush.num_planes)
4085                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)\n", n, loadmodel->brush.num_planes);
4086                 out->plane = loadmodel->brush.data_planes + n;
4087                 n = LittleLong(in->textureindex);
4088                 if (n < 0 || n >= loadmodel->num_textures)
4089                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)\n", n, loadmodel->num_textures);
4090                 out->texture = loadmodel->data_textures + n;
4091         }
4092 }
4093
4094 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4095 {
4096         q3dbrush_t *in;
4097         q3mbrush_t *out;
4098         int i, j, n, c, count, maxplanes;
4099         mplane_t *planes;
4100
4101         in = (q3dbrush_t *)(mod_base + l->fileofs);
4102         if (l->filelen % sizeof(*in))
4103                 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4104         count = l->filelen / sizeof(*in);
4105         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4106
4107         loadmodel->brush.data_brushes = out;
4108         loadmodel->brush.num_brushes = count;
4109
4110         maxplanes = 0;
4111         planes = NULL;
4112
4113         for (i = 0;i < count;i++, in++, out++)
4114         {
4115                 n = LittleLong(in->firstbrushside);
4116                 c = LittleLong(in->numbrushsides);
4117                 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4118                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)\n", n, n + c, loadmodel->brush.num_brushsides);
4119                 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4120                 out->numbrushsides = c;
4121                 n = LittleLong(in->textureindex);
4122                 if (n < 0 || n >= loadmodel->num_textures)
4123                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)\n", n, loadmodel->num_textures);
4124                 out->texture = loadmodel->data_textures + n;
4125
4126                 // make a list of mplane_t structs to construct a colbrush from
4127                 if (maxplanes < out->numbrushsides)
4128                 {
4129                         maxplanes = out->numbrushsides;
4130                         if (planes)
4131                                 Mem_Free(planes);
4132                         planes = (mplane_t *)Mem_Alloc(tempmempool, sizeof(mplane_t) * maxplanes);
4133                 }
4134                 for (j = 0;j < out->numbrushsides;j++)
4135                 {
4136                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4137                         planes[j].dist = out->firstbrushside[j].plane->dist;
4138                 }
4139                 // make the colbrush from the planes
4140                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents);
4141         }
4142         if (planes)
4143                 Mem_Free(planes);
4144 }
4145
4146 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4147 {
4148         q3deffect_t *in;
4149         q3deffect_t *out;
4150         int i, n, count;
4151
4152         in = (q3deffect_t *)(mod_base + l->fileofs);
4153         if (l->filelen % sizeof(*in))
4154                 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4155         count = l->filelen / sizeof(*in);
4156         out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4157
4158         loadmodel->brushq3.data_effects = out;
4159         loadmodel->brushq3.num_effects = count;
4160
4161         for (i = 0;i < count;i++, in++, out++)
4162         {
4163                 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4164                 n = LittleLong(in->brushindex);
4165                 if (n >= loadmodel->brush.num_brushes)
4166                 {
4167                         Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4168                         n = -1;
4169                 }
4170                 out->brushindex = n;
4171                 out->unknown = LittleLong(in->unknown);
4172         }
4173 }
4174
4175 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4176 {
4177         q3dvertex_t *in;
4178         int i, count;
4179
4180         in = (q3dvertex_t *)(mod_base + l->fileofs);
4181         if (l->filelen % sizeof(*in))
4182                 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4183         loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4184         loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 2 + 2 + 4)));
4185         loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_vertex3f + count * 3;
4186         loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4187         loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4188
4189         for (i = 0;i < count;i++, in++)
4190         {
4191                 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4192                 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4193                 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4194                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4195                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4196                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4197                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4198                 // svector/tvector are calculated later in face loading
4199                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4200                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4201                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4202                 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4203         }
4204 }
4205
4206 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4207 {
4208         int *in;
4209         int *out;
4210         int i, count;
4211
4212         in = (int *)(mod_base + l->fileofs);
4213         if (l->filelen % sizeof(int[3]))
4214                 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4215         count = l->filelen / sizeof(*in);
4216         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4217
4218         loadmodel->brushq3.num_triangles = count / 3;
4219         loadmodel->brushq3.data_element3i = out;
4220
4221         for (i = 0;i < count;i++, in++, out++)
4222         {
4223                 *out = LittleLong(*in);
4224                 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4225                 {
4226                         Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4227                         *out = 0;
4228                 }
4229         }
4230 }
4231
4232 static void Mod_Q3BSP_LoadLightmaps(lump_t *l)
4233 {
4234         q3dlightmap_t *in;
4235         rtexture_t **out;
4236         int i, count;
4237
4238         if (!l->filelen)
4239                 return;
4240         in = (q3dlightmap_t *)(mod_base + l->fileofs);
4241         if (l->filelen % sizeof(*in))
4242                 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4243         count = l->filelen / sizeof(*in);
4244         out = (rtexture_t **)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4245
4246         loadmodel->brushq3.data_lightmaps = out;
4247         loadmodel->brushq3.num_lightmaps = count;
4248
4249         for (i = 0;i < count;i++, in++, out++)
4250                 *out = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", i), 128, 128, in->rgb, TEXTYPE_RGB, TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
4251 }
4252
4253 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4254 {
4255         q3dface_t *in, *oldin;
4256         msurface_t *out, *oldout;
4257         int i, oldi, j, n, count, invalidelements, patchsize[2], finalwidth, finalheight, xtess, ytess, finalvertices, finaltriangles, firstvertex, firstelement, type, oldnumtriangles, oldnumtriangles2, meshnum, meshvertices, meshtriangles, numvertices, numtriangles;
4258         //int *originalelement3i;
4259         //int *originalneighbor3i;
4260         float *originalvertex3f;
4261         //float *originalsvector3f;
4262         //float *originaltvector3f;
4263         //float *originalnormal3f;
4264         float *originalcolor4f;
4265         float *originaltexcoordtexture2f;
4266         float *originaltexcoordlightmap2f;
4267         float *v;
4268         surfmesh_t *mesh, *tempmeshlist[1024];
4269
4270         in = (q3dface_t *)(mod_base + l->fileofs);
4271         if (l->filelen % sizeof(*in))
4272                 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4273         count = l->filelen / sizeof(*in);
4274         out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4275
4276         loadmodel->data_surfaces = out;
4277         loadmodel->num_surfaces = count;
4278
4279         i = 0;
4280         for (meshnum = 0;i < count;meshnum++)
4281         {
4282                 oldi = i;
4283                 oldin = in;
4284                 oldout = out;
4285                 meshvertices = 0;
4286                 meshtriangles = 0;
4287                 for (;i < count;i++, in++, out++)
4288                 {
4289                         // check face type first
4290                         type = LittleLong(in->type);
4291                         if (type != Q3FACETYPE_POLYGON
4292                          && type != Q3FACETYPE_PATCH
4293                          && type != Q3FACETYPE_MESH
4294                          && type != Q3FACETYPE_FLARE)
4295                         {
4296                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4297                                 continue;
4298                         }
4299
4300                         n = LittleLong(in->textureindex);
4301                         if (n < 0 || n >= loadmodel->num_textures)
4302                         {
4303                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4304                                 continue;
4305                         }
4306                         out->texture = loadmodel->data_textures + n;
4307                         n = LittleLong(in->effectindex);
4308                         if (n < -1 || n >= loadmodel->brushq3.num_effects)
4309                         {
4310                                 if (developer.integer >= 2)
4311                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4312                                 n = -1;
4313                         }
4314                         if (n == -1)
4315                                 out->effect = NULL;
4316                         else
4317                                 out->effect = loadmodel->brushq3.data_effects + n;
4318                         n = LittleLong(in->lightmapindex);
4319                         if (n >= loadmodel->brushq3.num_lightmaps)
4320                         {
4321                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_lightmaps);
4322                                 n = -1;
4323                         }
4324                         else if (n < 0)
4325                                 n = -1;
4326                         if (n == -1)
4327                                 out->lightmaptexture = NULL;
4328                         else
4329                                 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n];
4330
4331                         firstvertex = LittleLong(in->firstvertex);
4332                         numvertices = LittleLong(in->numvertices);
4333                         firstelement = LittleLong(in->firstelement);
4334                         numtriangles = LittleLong(in->numelements) / 3;
4335                         if (numtriangles * 3 != LittleLong(in->numelements))
4336                         {
4337                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): numelements %i is not a multiple of 3\n", i, out->texture->name, LittleLong(in->numelements));
4338                                 continue;
4339                         }
4340                         if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4341                         {
4342                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid vertex range %i : %i (%i vertices)\n", i, out->texture->name, firstvertex, firstvertex + numvertices, loadmodel->brushq3.num_vertices);
4343                                 continue;
4344                         }
4345                         if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4346                         {
4347                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid element range %i : %i (%i elements)\n", i, out->texture->name, firstelement, firstelement + numtriangles * 3, loadmodel->brushq3.num_triangles * 3);
4348                                 continue;
4349                         }
4350                         switch(type)
4351                         {
4352                         case Q3FACETYPE_POLYGON:
4353                         case Q3FACETYPE_MESH:
4354                                 // no processing necessary
4355                                 break;
4356                         case Q3FACETYPE_PATCH:
4357                                 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4358                                 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4359                                 if (numvertices != (patchsize[0] * patchsize[1]) || patchsize[0] < 3 || patchsize[1] < 3 || !(patchsize[0] & 1) || !(patchsize[1] & 1) || patchsize[0] * patchsize[1] >= min(r_subdivisions_maxvertices.integer, r_subdivisions_collision_maxvertices.integer))
4360                                 {
4361                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
4362                                         continue;
4363                                 }
4364                                 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4365                                 // convert patch to Q3FACETYPE_MESH
4366                                 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4367                                 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4368                                 // bound to user settings
4369                                 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4370                                 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4371                                 // bound to sanity settings
4372                                 xtess = bound(1, xtess, 1024);
4373                                 ytess = bound(1, ytess, 1024);
4374                                 // bound to user limit on vertices
4375                                 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_maxvertices.integer, 262144))
4376                                 {
4377                                         if (xtess > ytess)
4378                                                 xtess--;
4379                                         else
4380                                                 ytess--;
4381                                 }
4382                                 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4383                                 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4384                                 numvertices = finalwidth * finalheight;
4385                                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4386                                 break;
4387                         case Q3FACETYPE_FLARE:
4388                                 if (developer.integer >= 2)
4389                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
4390                                 // don't render it
4391                                 continue;
4392                         }
4393                         out->num_vertices = numvertices;
4394                         out->num_triangles = numtriangles;
4395                         if (meshvertices + out->num_vertices > 65536)
4396                                 break;
4397                         meshvertices += out->num_vertices;
4398                         meshtriangles += out->num_triangles;
4399                 }
4400
4401                 i = oldi;
4402                 in = oldin;
4403                 out = oldout;
4404                 mesh = tempmeshlist[meshnum] = Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
4405                 meshvertices = 0;
4406                 meshtriangles = 0;
4407                 for (;i < count && meshvertices + out->num_vertices <= mesh->num_vertices;i++, in++, out++)
4408                 {
4409                         if (out->num_vertices < 3 || out->num_triangles < 1)
4410                                 continue;
4411
4412                         type = LittleLong(in->type);
4413                         firstvertex = LittleLong(in->firstvertex);
4414                         firstelement = LittleLong(in->firstelement);
4415                         out->groupmesh = mesh;
4416                         out->num_firstvertex = meshvertices;
4417                         out->num_firsttriangle = meshtriangles;
4418                         switch(type)
4419                         {
4420                         case Q3FACETYPE_POLYGON:
4421                         case Q3FACETYPE_MESH:
4422                                 // no processing necessary
4423                                 for (j = 0;j < out->num_vertices;j++)
4424                                 {
4425                                         (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
4426                                         (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
4427                                         (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
4428                                         (out->groupmesh->data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
4429                                         (out->groupmesh->data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
4430                                         (out->groupmesh->data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
4431                                         (out->groupmesh->data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
4432                                         (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
4433                                         (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
4434                                         (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
4435                                         (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
4436                                 }
4437                                 for (j = 0;j < out->num_triangles*3;j++)
4438                                         (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
4439                                 break;
4440                         case Q3FACETYPE_PATCH:
4441                                 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4442                                 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4443                                 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4444                                 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
4445                                 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
4446                                 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
4447                                 // convert patch to Q3FACETYPE_MESH
4448                                 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4449                                 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4450                                 // bound to user settings
4451                                 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4452                                 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4453                                 // bound to sanity settings
4454                                 xtess = bound(1, xtess, 1024);
4455                                 ytess = bound(1, ytess, 1024);
4456                                 // bound to user limit on vertices
4457                                 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_maxvertices.integer, 262144))
4458                                 {
4459                                         if (xtess > ytess)
4460                                                 xtess--;
4461                                         else
4462                                                 ytess--;
4463                                 }
4464                                 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4465                                 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4466                                 finalvertices = finalwidth * finalheight;
4467                                 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4468                                 type = Q3FACETYPE_MESH;
4469                                 // generate geometry
4470                                 // (note: normals are skipped because they get recalculated)
4471                                 Q3PatchTesselateFloat(3, sizeof(float[3]), (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
4472                                 Q3PatchTesselateFloat(2, sizeof(float[2]), (out->groupmesh->data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
4473                                 Q3PatchTesselateFloat(2, sizeof(float[2]), (out->groupmesh->data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
4474                                 Q3PatchTesselateFloat(4, sizeof(float[4]), (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
4475                                 Q3PatchTriangleElements((out->groupmesh->data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
4476                                 out->num_triangles = Mod_RemoveDegenerateTriangles(out->num_triangles, (out->groupmesh->data_element3i + 3 * out->num_firsttriangle), (out->groupmesh->data_element3i + 3 * out->num_firsttriangle), out->groupmesh->data_vertex3f);
4477                                 if (developer.integer >= 2)
4478                                 {
4479                                         if (out->num_triangles < finaltriangles)
4480                                                 Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles, %i degenerate triangles removed (leaving %i)\n", patchsize[0], patchsize[1], out->num_vertices, finaltriangles, finaltriangles - out->num_triangles, out->num_triangles);
4481                                         else
4482                                                 Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles\n", patchsize[0], patchsize[1], out->num_vertices, out->num_triangles);
4483                                 }
4484                                 // q3map does not put in collision brushes for curves... ugh
4485                                 // build the lower quality collision geometry
4486                                 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4487                                 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4488                                 // bound to user settings
4489                                 xtess = bound(r_subdivisions_collision_mintess.integer, xtess, r_subdivisions_collision_maxtess.integer);
4490                                 ytess = bound(r_subdivisions_collision_mintess.integer, ytess, r_subdivisions_collision_maxtess.integer);
4491                                 // bound to sanity settings
4492                                 xtess = bound(1, xtess, 1024);
4493                                 ytess = bound(1, ytess, 1024);
4494                                 // bound to user limit on vertices
4495                                 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_collision_maxvertices.integer, 262144))
4496                                 {
4497                                         if (xtess > ytess)
4498                                                 xtess--;
4499                                         else
4500                                                 ytess--;
4501                                 }
4502                                 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4503                                 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4504                                 finalvertices = finalwidth * finalheight;
4505                                 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4506
4507                                 out->data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
4508                                 out->data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
4509                                 out->num_collisionvertices = finalvertices;
4510                                 out->num_collisiontriangles = finaltriangles;
4511                                 Q3PatchTesselateFloat(3, sizeof(float[3]), out->data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
4512                                 Q3PatchTriangleElements(out->data_collisionelement3i, finalwidth, finalheight, 0);
4513
4514                                 //Mod_SnapVertices(3, out->num_vertices, (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), 0.25);
4515                                 Mod_SnapVertices(3, out->num_collisionvertices, out->data_collisionvertex3f, 1);
4516
4517                                 oldnumtriangles = out->num_triangles;
4518                                 oldnumtriangles2 = out->num_collisiontriangles;
4519                                 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->num_collisiontriangles, out->data_collisionelement3i, out->data_collisionelement3i, out->data_collisionvertex3f);
4520                                 if (developer.integer)
4521                                         Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve became %i:%i vertices / %i:%i triangles (%i:%i degenerate)\n", patchsize[0], patchsize[1], out->num_vertices, out->num_collisionvertices, oldnumtriangles, oldnumtriangles2, oldnumtriangles - out->num_triangles, oldnumtriangles2 - out->num_collisiontriangles);
4522                                 break;
4523                         default:
4524                                 break;
4525                         }
4526                         meshvertices += out->num_vertices;
4527                         meshtriangles += out->num_triangles;
4528                         for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
4529                                 if ((out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
4530                                         invalidelements++;
4531                         if (invalidelements)
4532                         {
4533                                 Con_Printf("Mod_Q3BSP_LoadFaces: Warning: face #%i has %i invalid elements, type = %i, texture->name = \"%s\", texture->surfaceflags = %i, firstvertex = %i, numvertices = %i, firstelement = %i, numelements = %i, elements list:\n", i, invalidelements, type, out->texture->name, out->texture->surfaceflags, firstvertex, out->num_vertices, firstelement, out->num_triangles * 3);
4534                                 for (j = 0;j < out->num_triangles * 3;j++)
4535                                 {
4536                                         Con_Printf(" %i", (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
4537                                         if ((out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
4538                                                 (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
4539                                 }
4540                                 Con_Print("\n");
4541                         }
4542                         // for per pixel lighting
4543                         Mod_BuildTextureVectorsAndNormals(out->num_firstvertex, out->num_vertices, out->num_triangles, out->groupmesh->data_vertex3f, out->groupmesh->data_texcoordtexture2f, (out->groupmesh->data_element3i + 3 * out->num_firsttriangle), out->groupmesh->data_svector3f, out->groupmesh->data_tvector3f, out->groupmesh->data_normal3f, true);
4544                         // calculate a bounding box
4545                         VectorClear(out->mins);
4546                         VectorClear(out->maxs);
4547                         if (out->num_vertices)
4548                         {
4549                                 VectorCopy((out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), out->mins);
4550                                 VectorCopy((out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), out->maxs);
4551                                 for (j = 1, v = (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
4552                                 {
4553                                         out->mins[0] = min(out->mins[0], v[0]);
4554                                         out->maxs[0] = max(out->maxs[0], v[0]);
4555                                         out->mins[1] = min(out->mins[1], v[1]);
4556                                         out->maxs[1] = max(out->maxs[1], v[1]);
4557                                         out->mins[2] = min(out->mins[2], v[2]);
4558                                         out->maxs[2] = max(out->maxs[2], v[2]);
4559                                 }
4560                                 out->mins[0] -= 1.0f;
4561                                 out->mins[1] -= 1.0f;
4562                                 out->mins[2] -= 1.0f;
4563                                 out->maxs[0] += 1.0f;
4564                                 out->maxs[1] += 1.0f;
4565                                 out->maxs[2] += 1.0f;
4566                         }
4567                         // set lightmap styles for consistency with q1bsp
4568                         //out->lightmapinfo->styles[0] = 0;
4569                         //out->lightmapinfo->styles[1] = 255;
4570                         //out->lightmapinfo->styles[2] = 255;
4571                         //out->lightmapinfo->styles[3] = 255;
4572                 }
4573         }
4574
4575         // now store the completed list of meshes
4576         loadmodel->nummeshes = meshnum;
4577         if (loadmodel->nummeshes)
4578         {
4579                 loadmodel->meshlist = (surfmesh_t **)Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *) * loadmodel->nummeshes);
4580                 memcpy(loadmodel->meshlist, tempmeshlist, sizeof(surfmesh_t *) * loadmodel->nummeshes);
4581         }
4582
4583         // free the no longer needed vertex data
4584         loadmodel->brushq3.num_vertices = 0;
4585         Mem_Free(loadmodel->brushq3.data_vertex3f);
4586         loadmodel->brushq3.data_vertex3f = NULL;
4587         loadmodel->brushq3.data_texcoordtexture2f = NULL;
4588         loadmodel->brushq3.data_texcoordlightmap2f = NULL;
4589         loadmodel->brushq3.data_color4f = NULL;
4590         // free the no longer needed triangle data
4591         loadmodel->brushq3.num_triangles = 0;
4592         Mem_Free(loadmodel->brushq3.data_element3i);
4593         loadmodel->brushq3.data_element3i = NULL;
4594 }
4595
4596 static void Mod_Q3BSP_LoadModels(lump_t *l)
4597 {
4598         q3dmodel_t *in;
4599         q3dmodel_t *out;
4600         int i, j, n, c, count;
4601
4602         in = (q3dmodel_t *)(mod_base + l->fileofs);
4603         if (l->filelen % sizeof(*in))
4604                 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
4605         count = l->filelen / sizeof(*in);
4606         out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4607
4608         loadmodel->brushq3.data_models = out;
4609         loadmodel->brushq3.num_models = count;
4610
4611         for (i = 0;i < count;i++, in++, out++)
4612         {
4613                 for (j = 0;j < 3;j++)
4614                 {
4615                         out->mins[j] = LittleFloat(in->mins[j]);
4616                         out->maxs[j] = LittleFloat(in->maxs[j]);
4617                 }
4618                 n = LittleLong(in->firstface);
4619                 c = LittleLong(in->numfaces);
4620                 if (n < 0 || n + c > loadmodel->num_surfaces)
4621                         Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)\n", n, n + c, loadmodel->num_surfaces);
4622                 out->firstface = n;
4623                 out->numfaces = c;
4624                 n = LittleLong(in->firstbrush);
4625                 c = LittleLong(in->numbrushes);
4626                 if (n < 0 || n + c > loadmodel->brush.num_brushes)
4627                         Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)\n", n, n + c, loadmodel->brush.num_brushes);
4628                 out->firstbrush = n;
4629                 out->numbrushes = c;
4630         }
4631 }
4632
4633 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
4634 {
4635         int *in;
4636         int *out;
4637         int i, n, count;
4638
4639         in = (int *)(mod_base + l->fileofs);
4640         if (l->filelen % sizeof(*in))
4641                 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4642         count = l->filelen / sizeof(*in);
4643         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4644
4645         loadmodel->brush.data_leafbrushes = out;
4646         loadmodel->brush.num_leafbrushes = count;
4647
4648         for (i = 0;i < count;i++, in++, out++)
4649         {
4650                 n = LittleLong(*in);
4651                 if (n < 0 || n >= loadmodel->brush.num_brushes)
4652                         Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)\n", n, loadmodel->brush.num_brushes);
4653                 *out = n;
4654         }
4655 }
4656
4657 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
4658 {
4659         int *in;
4660         int *out;
4661         int i, n, count;
4662
4663         in = (int *)(mod_base + l->fileofs);
4664         if (l->filelen % sizeof(*in))
4665                 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4666         count = l->filelen / sizeof(*in);
4667         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4668
4669         loadmodel->brush.data_leafsurfaces = out;
4670         loadmodel->brush.num_leafsurfaces = count;
4671
4672         for (i = 0;i < count;i++, in++, out++)
4673         {
4674                 n = LittleLong(*in);
4675                 if (n < 0 || n >= loadmodel->num_surfaces)
4676                         Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)\n", n, loadmodel->num_surfaces);
4677                 *out = n;
4678         }
4679 }
4680
4681 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
4682 {
4683         q3dleaf_t *in;
4684         mleaf_t *out;
4685         int i, j, n, c, count;
4686
4687         in = (q3dleaf_t *)(mod_base + l->fileofs);
4688         if (l->filelen % sizeof(*in))
4689                 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4690         count = l->filelen / sizeof(*in);
4691         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4692
4693         loadmodel->brush.data_leafs = out;
4694         loadmodel->brush.num_leafs = count;
4695
4696         for (i = 0;i < count;i++, in++, out++)
4697         {
4698                 out->parent = NULL;
4699                 out->plane = NULL;
4700                 out->clusterindex = LittleLong(in->clusterindex);
4701                 out->areaindex = LittleLong(in->areaindex);
4702                 for (j = 0;j < 3;j++)
4703                 {
4704                         // yes the mins/maxs are ints
4705                         out->mins[j] = LittleLong(in->mins[j]) - 1;
4706                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
4707                 }
4708                 n = LittleLong(in->firstleafface);
4709                 c = LittleLong(in->numleaffaces);
4710                 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
4711                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)\n", n, n + c, loadmodel->brush.num_leafsurfaces);
4712                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
4713                 out->numleafsurfaces = c;
4714                 n = LittleLong(in->firstleafbrush);
4715                 c = LittleLong(in->numleafbrushes);
4716                 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
4717                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)\n", n, n + c, loadmodel->brush.num_leafbrushes);
4718                 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
4719                 out->numleafbrushes = c;
4720         }
4721 }
4722
4723 static void Mod_Q3BSP_LoadNodes(lump_t *l)
4724 {
4725         q3dnode_t *in;
4726         mnode_t *out;
4727         int i, j, n, count;
4728
4729         in = (q3dnode_t *)(mod_base + l->fileofs);
4730         if (l->filelen % sizeof(*in))
4731                 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4732         count = l->filelen / sizeof(*in);
4733         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4734
4735         loadmodel->brush.data_nodes = out;
4736         loadmodel->brush.num_nodes = count;
4737
4738         for (i = 0;i < count;i++, in++, out++)
4739         {
4740                 out->parent = NULL;
4741                 n = LittleLong(in->planeindex);
4742                 if (n < 0 || n >= loadmodel->brush.num_planes)
4743                         Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)\n", n, loadmodel->brush.num_planes);
4744                 out->plane = loadmodel->brush.data_planes + n;
4745                 for (j = 0;j < 2;j++)
4746                 {
4747                         n = LittleLong(in->childrenindex[j]);
4748                         if (n >= 0)
4749                         {
4750                                 if (n >= loadmodel->brush.num_nodes)
4751                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)\n", n, loadmodel->brush.num_nodes);
4752                                 out->children[j] = loadmodel->brush.data_nodes + n;
4753                         }
4754                         else
4755                         {
4756                                 n = -1 - n;
4757                                 if (n >= loadmodel->brush.num_leafs)
4758                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)\n", n, loadmodel->brush.num_leafs);
4759                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
4760                         }
4761                 }
4762                 for (j = 0;j < 3;j++)
4763                 {
4764                         // yes the mins/maxs are ints
4765                         out->mins[j] = LittleLong(in->mins[j]) - 1;
4766                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
4767                 }
4768         }
4769
4770         // set the parent pointers
4771         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
4772 }
4773
4774 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
4775 {
4776         q3dlightgrid_t *in;
4777         q3dlightgrid_t *out;
4778         int count;
4779
4780         in = (q3dlightgrid_t *)(mod_base + l->fileofs);
4781         if (l->filelen % sizeof(*in))
4782                 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
4783         loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
4784         loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
4785         loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
4786         loadmodel->brushq3.num_lightgrid_imins[0] = ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
4787         loadmodel->brushq3.num_lightgrid_imins[1] = ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
4788         loadmodel->brushq3.num_lightgrid_imins[2] = ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
4789         loadmodel->brushq3.num_lightgrid_imaxs[0] = floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
4790         loadmodel->brushq3.num_lightgrid_imaxs[1] = floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
4791         loadmodel->brushq3.num_lightgrid_imaxs[2] = floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
4792         loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
4793         loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
4794         loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
4795         count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
4796         Matrix4x4_CreateScale3(&loadmodel->brushq3.num_lightgrid_indexfromworld, loadmodel->brushq3.num_lightgrid_scale[0], loadmodel->brushq3.num_lightgrid_scale[1], loadmodel->brushq3.num_lightgrid_scale[2]);
4797         Matrix4x4_ConcatTranslate(&loadmodel->brushq3.num_lightgrid_indexfromworld, -loadmodel->brushq3.num_lightgrid_imins[0] * loadmodel->brushq3.num_lightgrid_cellsize[0], -loadmodel->brushq3.num_lightgrid_imins[1] * loadmodel->brushq3.num_lightgrid_cellsize[1], -loadmodel->brushq3.num_lightgrid_imins[2] * loadmodel->brushq3.num_lightgrid_cellsize[2]);
4798
4799         // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
4800         if (l->filelen)
4801         {
4802                 if (l->filelen < count * (int)sizeof(*in))
4803                         Host_Error("Mod_Q3BSP_LoadLightGrid: invalid lightgrid lump size %i bytes, should be %i bytes (%ix%ix%i)\n", l->filelen, count * sizeof(*in), loadmodel->brushq3.num_lightgrid_dimensions[0], loadmodel->brushq3.num_lightgrid_dimensions[1], loadmodel->brushq3.num_lightgrid_dimensions[2]);
4804                 if (l->filelen != count * (int)sizeof(*in))
4805                         Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", count * sizeof(*in), l->filelen);
4806                 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4807                 loadmodel->brushq3.data_lightgrid = out;
4808                 loadmodel->brushq3.num_lightgrid = count;
4809                 // no swapping or validation necessary
4810                 memcpy(out, in, count * (int)sizeof(*out));
4811         }
4812 }
4813
4814 static void Mod_Q3BSP_LoadPVS(lump_t *l)
4815 {
4816         q3dpvs_t *in;
4817         int totalchains;
4818
4819         if (l->filelen == 0)
4820         {
4821                 int i;
4822                 // unvised maps often have cluster indices even without pvs, so check
4823                 // leafs to find real number of clusters
4824                 loadmodel->brush.num_pvsclusters = 1;
4825                 for (i = 0;i < loadmodel->brush.num_leafs;i++)
4826                         loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
4827
4828                 // create clusters
4829                 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
4830                 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
4831                 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
4832                 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
4833                 return;
4834         }
4835
4836         in = (q3dpvs_t *)(mod_base + l->fileofs);
4837         if (l->filelen < 9)
4838                 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
4839
4840         loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
4841         loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
4842         if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
4843                 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8\n", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
4844         totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
4845         if (l->filelen < totalchains + (int)sizeof(*in))
4846                 Host_Error("Mod_Q3BSP_LoadPVS: lump too small ((numclusters = %i) * (chainlength = %i) + sizeof(q3dpvs_t) == %i bytes, lump is %i bytes)\n", loadmodel->brush.num_pvsclusters, loadmodel->brush.num_pvsclusterbytes, totalchains + sizeof(*in), l->filelen);
4847
4848         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
4849         memcpy(loadmodel->brush.data_pvsclusters, (qbyte *)(in + 1), totalchains);
4850 }
4851
4852 static void Mod_Q3BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
4853 {
4854         int i, j, k, index[3];
4855         float transformed[3], blend1, blend2, blend, yaw, pitch, sinpitch;
4856         q3dlightgrid_t *a, *s;
4857         if (!model->brushq3.num_lightgrid)
4858         {
4859                 ambientcolor[0] = 1;
4860                 ambientcolor[1] = 1;
4861                 ambientcolor[2] = 1;
4862                 return;
4863         }
4864         Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
4865         //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
4866         //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
4867         transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
4868         transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
4869         transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
4870         index[0] = (int)floor(transformed[0]);
4871         index[1] = (int)floor(transformed[1]);
4872         index[2] = (int)floor(transformed[2]);
4873         //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
4874         // now lerp the values
4875         VectorClear(diffusenormal);
4876         a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
4877         for (k = 0;k < 2;k++)
4878         {
4879                 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
4880                 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
4881                         continue;
4882                 for (j = 0;j < 2;j++)
4883                 {
4884                         blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
4885                         if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
4886                                 continue;
4887                         for (i = 0;i < 2;i++)
4888                         {
4889                                 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0])));
4890                                 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
4891                                         continue;
4892                                 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
4893                                 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
4894                                 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
4895                                 pitch = s->diffusepitch * M_PI / 128;
4896                                 yaw = s->diffuseyaw * M_PI / 128;
4897                                 sinpitch = sin(pitch);
4898                                 diffusenormal[0] += blend * (cos(yaw) * sinpitch);
4899                                 diffusenormal[1] += blend * (sin(yaw) * sinpitch);
4900                                 diffusenormal[2] += blend * (cos(pitch));
4901                                 //Con_Printf("blend %f: ambient %i %i %i, diffuse %i %i %i, diffusepitch %i diffuseyaw %i (%f %f, normal %f %f %f)\n", blend, s->ambientrgb[0], s->ambientrgb[1], s->ambientrgb[2], s->diffusergb[0], s->diffusergb[1], s->diffusergb[2], s->diffusepitch, s->diffuseyaw, pitch, yaw, (cos(yaw) * cospitch), (sin(yaw) * cospitch), (-sin(pitch)));
4902                         }
4903                 }
4904         }
4905         VectorNormalize(diffusenormal);
4906         //Con_Printf("result: ambient %f %f %f diffuse %f %f %f diffusenormal %f %f %f\n", ambientcolor[0], ambientcolor[1], ambientcolor[2], diffusecolor[0], diffusecolor[1], diffusecolor[2], diffusenormal[0], diffusenormal[1], diffusenormal[2]);
4907 }
4908
4909 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, model_t *model, mnode_t *node, const vec3_t point, int markframe)
4910 {
4911         int i;
4912         mleaf_t *leaf;
4913         colbrushf_t *brush;
4914         // find which leaf the point is in
4915         while (node->plane)
4916                 node = node->children[DotProduct(point, node->plane->normal) < node->plane->dist];
4917         // point trace the brushes
4918         leaf = (mleaf_t *)node;
4919         for (i = 0;i < leaf->numleafbrushes;i++)
4920         {
4921                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
4922                 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
4923                 {
4924                         brush->markframe = markframe;
4925                         Collision_TracePointBrushFloat(trace, point, brush);
4926                 }
4927         }
4928         // can't do point traces on curves (they have no thickness)
4929 }
4930
4931 static void Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace_t *trace, model_t *model, mnode_t *node, const vec3_t start, const vec3_t end, vec_t startfrac, vec_t endfrac, const vec3_t linestart, const vec3_t lineend, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
4932 {
4933         int i, startside, endside;
4934         float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
4935         mleaf_t *leaf;
4936         msurface_t *surface;
4937         colbrushf_t *brush;
4938         if (startfrac > trace->realfraction)
4939                 return;
4940         // note: all line fragments past first impact fraction are ignored
4941         if (VectorCompare(start, end))
4942         {
4943                 // find which leaf the point is in
4944                 while (node->plane)
4945                         node = node->children[DotProduct(start, node->plane->normal) < node->plane->dist];
4946         }
4947         else
4948         {
4949                 // find which nodes the line is in and recurse for them
4950                 while (node->plane)
4951                 {
4952                         // recurse down node sides
4953                         dist1 = PlaneDiff(start, node->plane);
4954                         dist2 = PlaneDiff(end, node->plane);
4955                         startside = dist1 < 0;
4956                         endside = dist2 < 0;
4957                         if (startside == endside)
4958                         {
4959                                 // most of the time the line fragment is on one side of the plane
4960                                 node = node->children[startside];
4961                         }
4962                         else
4963                         {
4964                                 // line crosses node plane, split the line
4965                                 midfrac = dist1 / (dist1 - dist2);
4966                                 VectorLerp(start, midfrac, end, mid);
4967                                 // take the near side first
4968                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
4969                                 if (midfrac <= trace->realfraction)
4970                                         Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
4971                                 return;
4972                         }
4973                 }
4974         }
4975         // hit a leaf
4976         nodesegmentmins[0] = min(start[0], end[0]);
4977         nodesegmentmins[1] = min(start[1], end[1]);
4978         nodesegmentmins[2] = min(start[2], end[2]);
4979         nodesegmentmaxs[0] = max(start[0], end[0]);
4980         nodesegmentmaxs[1] = max(start[1], end[1]);
4981         nodesegmentmaxs[2] = max(start[2], end[2]);
4982         // line trace the brushes
4983         leaf = (mleaf_t *)node;
4984         for (i = 0;i < leaf->numleafbrushes;i++)
4985         {
4986                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
4987                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
4988                 {
4989                         brush->markframe = markframe;
4990                         Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
4991                         if (startfrac > trace->realfraction)
4992                                 return;
4993                 }
4994         }
4995         // can't do point traces on curves (they have no thickness)
4996         if (mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
4997         {
4998                 // line trace the curves
4999                 for (i = 0;i < leaf->numleafsurfaces;i++)
5000                 {
5001                         surface = model->data_surfaces + leaf->firstleafsurface[i];
5002                         if (surface->num_collisiontriangles && surface->collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
5003                         {
5004                                 surface->collisionmarkframe = markframe;
5005                                 Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5006                                 if (startfrac > trace->realfraction)
5007                                         return;
5008                         }
5009                 }
5010         }
5011 }
5012
5013 static void Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace_t *trace, model_t *model, mnode_t *node, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
5014 {
5015         int i;
5016         //int sides;
5017         float nodesegmentmins[3], nodesegmentmaxs[3];
5018         mleaf_t *leaf;
5019         colbrushf_t *brush;
5020         msurface_t *surface;
5021         /*
5022                 // find which nodes the line is in and recurse for them
5023                 while (node->plane)
5024                 {
5025                         // recurse down node sides
5026                         int startside, endside;
5027                         float dist1near, dist1far, dist2near, dist2far;
5028                         BoxPlaneCornerDistances(thisbrush_start->mins, thisbrush_start->maxs, node->plane, &dist1near, &dist1far);
5029                         BoxPlaneCornerDistances(thisbrush_end->mins, thisbrush_end->maxs, node->plane, &dist2near, &dist2far);
5030                         startside = dist1near < 0;
5031                         startside = dist1near < 0 ? (dist1far < 0 ? 1 : 2) : (dist1far < 0 ? 2 : 0);
5032                         endside = dist2near < 0 ? (dist2far < 0 ? 1 : 2) : (dist2far < 0 ? 2 : 0);
5033                         if (startside == 2 || endside == 2)
5034                         {
5035                                 // brushes cross plane
5036                                 // do not clip anything, just take both sides
5037                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5038                                 node = node->children[1];
5039                                 continue;
5040                         }
5041                         if (startside == 0)
5042                         {
5043                                 if (endside == 0)
5044                                 {
5045                                         node = node->children[0];
5046                                         continue;
5047                                 }
5048                                 else
5049                                 {
5050                                         //midf0 = dist1near / (dist1near - dist2near);
5051                                         //midf1 = dist1far / (dist1far - dist2far);
5052                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5053                                         node = node->children[1];
5054                                         continue;
5055                                 }
5056                         }
5057                         else
5058                         {
5059                                 if (endside == 0)
5060                                 {
5061                                         //midf0 = dist1near / (dist1near - dist2near);
5062                                         //midf1 = dist1far / (dist1far - dist2far);
5063                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5064                                         node = node->children[1];
5065                                         continue;
5066                                 }
5067                                 else
5068                                 {
5069                                         node = node->children[1];
5070                                         continue;
5071                                 }
5072                         }
5073
5074                         if (dist1near <  0 && dist2near <  0 && dist1far <  0 && dist2far <  0){node = node->children[1];continue;}
5075                         if (dist1near <  0 && dist2near <  0 && dist1far <  0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5076                         if (dist1near <  0 && dist2near <  0 && dist1far >= 0 && dist2far <  0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5077                         if (dist1near <  0 && dist2near <  0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5078                         if (dist1near <  0 && dist2near >= 0 && dist1far <  0 && dist2far <  0){node = node->children[1];continue;}
5079                         if (dist1near <  0 && dist2near >= 0 && dist1far <  0 && dist2far >= 0){}
5080                         if (dist1near <  0 && dist2near >= 0 && dist1far >= 0 && dist2far <  0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5081                         if (dist1near <  0 && dist2near >= 0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5082                         if (dist1near >= 0 && dist2near <  0 && dist1far <  0 && dist2far <  0){node = node->children[1];continue;}
5083                         if (dist1near >= 0 && dist2near <  0 && dist1far <  0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5084                         if (dist1near >= 0 && dist2near <  0 && dist1far >= 0 && dist2far <  0){}
5085                         if (dist1near >= 0 && dist2near <  0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5086                         if (dist1near >= 0 && dist2near >= 0 && dist1far <  0 && dist2far <  0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5087                         if (dist1near >= 0 && dist2near >= 0 && dist1far <  0 && dist2far >= 0){node = node->children[0];continue;}
5088                         if (dist1near >= 0 && dist2near >= 0 && dist1far >= 0 && dist2far <  0){node = node->children[0];continue;}
5089                         if (dist1near >= 0 && dist2near >= 0 && dist1far >= 0 && dist2far >= 0){node = node->children[0];continue;}
5090                         {
5091                                 if (dist2near < 0) // d1n<0 && d2n<0
5092                                 {
5093                                         if (dist2near < 0) // d1n<0 && d2n<0
5094                                         {
5095                                                 if (dist2near < 0) // d1n<0 && d2n<0
5096                                                 {
5097                                                 }
5098                                                 else // d1n<0 && d2n>0
5099                                                 {
5100                                                 }
5101                                         }
5102                                         else // d1n<0 && d2n>0
5103                                         {
5104                                                 if (dist2near < 0) // d1n<0 && d2n<0
5105                                                 {
5106                                                 }
5107                                                 else // d1n<0 && d2n>0
5108                                                 {
5109                                                 }
5110                                         }
5111                                 }
5112                                 else // d1n<0 && d2n>0
5113                                 {
5114                                 }
5115                         }
5116                         else // d1n>0
5117                         {
5118                                 if (dist2near < 0) // d1n>0 && d2n<0
5119                                 {
5120                                 }
5121                                 else // d1n>0 && d2n>0
5122                                 {
5123                                 }
5124                         }
5125                         if (dist1near < 0 == dist1far < 0 == dist2near < 0 == dist2far < 0)
5126                         {
5127                                 node = node->children[startside];
5128                                 continue;
5129                         }
5130                         if (dist1near < dist2near)
5131                         {
5132                                 // out
5133                                 if (dist1near >= 0)
5134                                 {
5135                                         node = node->children[0];
5136                                         continue;
5137                                 }
5138                                 if (dist2far < 0)
5139                                 {
5140                                         node = node->children[1];
5141                                         continue;
5142                                 }
5143                                 // dist1near < 0 && dist2far >= 0
5144                         }
5145                         else
5146                         {
5147                                 // in
5148                         }
5149                         startside = dist1near < 0 ? (dist1far < 0 ? 1 : 2) : (dist1far < 0 ? 2 : 0);
5150                         endside = dist2near < 0 ? (dist2far < 0 ? 1 : 2) : (dist2far < 0 ? 2 : 0);
5151                         if (startside == 2 || endside == 2)
5152                         {
5153                                 // brushes cross plane
5154                                 // do not clip anything, just take both sides
5155                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5156                                 node = node->children[1];
5157                         }
5158                         else if (startside == endside)
5159                                 node = node->children[startside];
5160                         else if (startside == 0) // endside = 1 (start infront, end behind)
5161                         {
5162                         }
5163                         else // startside == 1 endside = 0 (start behind, end infront)
5164                         {
5165                         }
5166                         == endside)
5167                         {
5168                                 if (startside < 2)
5169                                         node = node->children[startside];
5170                                 else
5171                                 {
5172                                         // start and end brush cross plane
5173                                 }
5174                         }
5175                         else
5176                         {
5177                         }
5178                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5179                                 node = node->children[1];
5180                         else if (dist1near < 0 && dist1far < 0 && dist2near >= 0 && dist2far >= 0)
5181                         else if (dist1near >= 0 && dist1far >= 0 && dist2near < 0 && dist2far < 0)
5182                         else if (dist1near >= 0 && dist1far >= 0 && dist2near >= 0 && dist2far >= 0)
5183                                 node = node->children[0];
5184                         else
5185                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5186                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5187                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5188                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5189                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5190                         {
5191                         }
5192                         else if (dist1near >= 0 && dist1far >= 0)
5193                         {
5194                         }
5195                         else // mixed (lying on plane)
5196                         {
5197                         }
5198                         {
5199                                 if (dist2near < 0 && dist2far < 0)
5200                                 {
5201                                 }
5202                                 else
5203                                         node = node->children[1];
5204                         }
5205                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5206                                 node = node->children[0];
5207                         else if (dist1near >= 0 && dist1far >= 0 && dist2near >= 0 && dist2far >= 0)
5208                                 node = node->children[1];
5209                         else
5210                         {
5211                                 // both sides
5212                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5213                                 node = node->children[1];
5214                         }
5215                         sides = dist1near || dist1near < 0 | dist1far < 0 | dist2near < 0 | dist
5216                         startside = dist1 < 0;
5217                         endside = dist2 < 0;
5218                         if (startside == endside)
5219                         {
5220                                 // most of the time the line fragment is on one side of the plane
5221                                 node = node->children[startside];
5222                         }
5223                         else
5224                         {
5225                                 // line crosses node plane, split the line
5226                                 midfrac = dist1 / (dist1 - dist2);
5227                                 VectorLerp(start, midfrac, end, mid);
5228                                 // take the near side first
5229                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5230                                 if (midfrac <= trace->fraction)
5231                                         Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5232                                 return;
5233                         }
5234                 }
5235         */
5236 #if 1
5237         for (;;)
5238         {
5239                 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5240                 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5241                 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5242                 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5243                 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5244                 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5245                 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5246                         return;
5247                 if (!node->plane)
5248                         break;
5249                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5250                 node = node->children[1];
5251         }
5252 #elif 0
5253         // FIXME: could be made faster by copying TraceLine code and making it use
5254         // box plane distances...  (variant on the BoxOnPlaneSide code)
5255         for (;;)
5256         {
5257                 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5258                 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5259                 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5260                 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5261                 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5262                 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5263                 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5264                         return;
5265                 if (!node->plane)
5266                         break;
5267                 if (mod_q3bsp_debugtracebrush.integer == 2)
5268                 {
5269                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5270                         node = node->children[1];
5271                         continue;
5272                 }
5273                 else if (mod_q3bsp_debugtracebrush.integer == 1)
5274                 {
5275                         // recurse down node sides
5276                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5277                         if (sides == 3)
5278                         {
5279                                 // segment box crosses plane
5280                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5281                                 node = node->children[1];
5282                                 continue;
5283                         }
5284                         // take whichever side the segment box is on
5285                         node = node->children[sides - 1];
5286                         continue;
5287                 }
5288                 else
5289                 {
5290                         // recurse down node sides
5291                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5292                         if (sides == 3)
5293                         {
5294                                 // segment box crosses plane
5295                                 // now check start and end brush boxes to handle a lot of 'diagonal' cases more efficiently...
5296                                 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, node->plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, node->plane);
5297                                 if (sides == 3)
5298                                 {
5299                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5300                                         node = node->children[1];
5301                                         continue;
5302                                 }
5303                         }
5304                         // take whichever side the segment box is on
5305                         node = node->children[sides - 1];
5306                         continue;
5307                 }
5308                 return;
5309         }
5310 #else
5311         // FIXME: could be made faster by copying TraceLine code and making it use
5312         // box plane distances...  (variant on the BoxOnPlaneSide code)
5313         for (;;)
5314         {
5315                 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5316                 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5317                 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5318                 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5319                 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5320                 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5321                 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5322                         return;
5323                 if (!node->plane)
5324                         break;
5325                 if (mod_q3bsp_debugtracebrush.integer == 2)
5326                 {
5327                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5328                         node = node->children[1];
5329                 }
5330                 else if (mod_q3bsp_debugtracebrush.integer == 1)
5331                 {
5332                         // recurse down node sides
5333                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5334                         if (sides == 3)
5335                         {
5336                                 // segment box crosses plane
5337                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5338                                 node = node->children[1];
5339                         }
5340                         else
5341                         {
5342                                 // take whichever side the segment box is on
5343                                 node = node->children[sides - 1];
5344                         }
5345                 }
5346                 else
5347                 {
5348                         // recurse down node sides
5349                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5350                         if (sides == 3)
5351                         {
5352                                 // segment box crosses plane
5353                                 // now check start and end brush boxes to handle a lot of 'diagonal' cases more efficiently...
5354                                 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, node->plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, node->plane);
5355                                 if (sides == 3)
5356                                 {
5357                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5358                                         sides = 2;
5359                                 }
5360                         }
5361                         // take whichever side the segment box is on
5362                         node = node->children[sides - 1];
5363                 }
5364         }
5365 #endif
5366         // hit a leaf
5367         leaf = (mleaf_t *)node;
5368         for (i = 0;i < leaf->numleafbrushes;i++)
5369         {
5370                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
5371                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
5372                 {
5373                         brush->markframe = markframe;
5374                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
5375                 }
5376         }
5377         if (mod_q3bsp_curves_collisions.integer)
5378         {
5379                 for (i = 0;i < leaf->numleafsurfaces;i++)
5380                 {
5381                         surface = model->data_surfaces + leaf->firstleafsurface[i];
5382                         if (surface->num_collisiontriangles && surface->collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
5383                         {
5384                                 surface->collisionmarkframe = markframe;
5385                                 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5386                         }
5387                 }
5388         }
5389 }
5390
5391 static void Mod_Q3BSP_TraceBox(model_t *model, int frame, trace_t *trace, const vec3_t boxstartmins, const vec3_t boxstartmaxs, const vec3_t boxendmins, const vec3_t boxendmaxs, int hitsupercontentsmask)
5392 {
5393         int i;
5394         float segmentmins[3], segmentmaxs[3];
5395         colbrushf_t *thisbrush_start, *thisbrush_end;
5396         matrix4x4_t startmatrix, endmatrix;
5397         static int markframe = 0;
5398         msurface_t *surface;
5399         q3mbrush_t *brush;
5400         memset(trace, 0, sizeof(*trace));
5401         trace->fraction = 1;
5402         trace->realfraction = 1;
5403         trace->hitsupercontentsmask = hitsupercontentsmask;
5404         Matrix4x4_CreateIdentity(&startmatrix);
5405         Matrix4x4_CreateIdentity(&endmatrix);
5406         segmentmins[0] = min(boxstartmins[0], boxendmins[0]);
5407         segmentmins[1] = min(boxstartmins[1], boxendmins[1]);
5408         segmentmins[2] = min(boxstartmins[2], boxendmins[2]);
5409         segmentmaxs[0] = max(boxstartmaxs[0], boxendmaxs[0]);
5410         segmentmaxs[1] = max(boxstartmaxs[1], boxendmaxs[1]);
5411         segmentmaxs[2] = max(boxstartmaxs[2], boxendmaxs[2]);
5412         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxstartmins, boxstartmaxs) && VectorCompare(boxendmins, boxendmaxs))
5413         {
5414                 if (VectorCompare(boxstartmins, boxendmins))
5415                 {
5416                         // point trace
5417                         if (model->brush.submodel)
5418                         {
5419                                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5420                                         if (brush->colbrushf)
5421                                                 Collision_TracePointBrushFloat(trace, boxstartmins, brush->colbrushf);
5422                         }
5423                         else
5424                                 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, boxstartmins, ++markframe);
5425                 }
5426                 else
5427                 {
5428                         // line trace
5429                         if (model->brush.submodel)
5430                         {
5431                                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5432                                         if (brush->colbrushf)
5433                                                 Collision_TraceLineBrushFloat(trace, boxstartmins, boxendmins, brush->colbrushf, brush->colbrushf);
5434                                 if (mod_q3bsp_curves_collisions.integer)
5435                                         for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
5436                                                 if (surface->num_collisiontriangles)
5437                                                         Collision_TraceLineTriangleMeshFloat(trace, boxstartmins, boxendmins, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5438                         }
5439                         else
5440                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, boxstartmins, boxendmins, 0, 1, boxstartmins, boxendmins, ++markframe, segmentmins, segmentmaxs);
5441                 }
5442         }
5443         else
5444         {
5445                 // box trace, performed as brush trace
5446                 thisbrush_start = Collision_BrushForBox(&startmatrix, boxstartmins, boxstartmaxs);
5447                 thisbrush_end = Collision_BrushForBox(&endmatrix, boxendmins, boxendmaxs);
5448                 if (model->brush.submodel)
5449                 {
5450                         for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5451                                 if (brush->colbrushf)
5452                                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush->colbrushf, brush->colbrushf);
5453                         if (mod_q3bsp_curves_collisions.integer)
5454                                 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
5455                                         if (surface->num_collisiontriangles)
5456                                                 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5457                 }
5458                 else
5459                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, thisbrush_start, thisbrush_end, ++markframe, segmentmins, segmentmaxs);
5460         }
5461 }
5462
5463 static int Mod_Q3BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents)
5464 {
5465         int supercontents = 0;
5466         if (nativecontents & CONTENTSQ3_SOLID)
5467                 supercontents |= SUPERCONTENTS_SOLID;
5468         if (nativecontents & CONTENTSQ3_WATER)
5469                 supercontents |= SUPERCONTENTS_WATER;
5470         if (nativecontents & CONTENTSQ3_SLIME)
5471                 supercontents |= SUPERCONTENTS_SLIME;
5472         if (nativecontents & CONTENTSQ3_LAVA)
5473                 supercontents |= SUPERCONTENTS_LAVA;
5474         if (nativecontents & CONTENTSQ3_BODY)
5475                 supercontents |= SUPERCONTENTS_BODY;
5476         if (nativecontents & CONTENTSQ3_CORPSE)
5477                 supercontents |= SUPERCONTENTS_CORPSE;
5478         if (nativecontents & CONTENTSQ3_NODROP)
5479                 supercontents |= SUPERCONTENTS_NODROP;
5480         if (nativecontents & CONTENTSQ3_PLAYERCLIP)
5481                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
5482         if (nativecontents & CONTENTSQ3_MONSTERCLIP)
5483                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
5484         if (nativecontents & CONTENTSQ3_DONOTENTER)
5485                 supercontents |= SUPERCONTENTS_DONOTENTER;
5486         return supercontents;
5487 }
5488
5489 static int Mod_Q3BSP_NativeContentsFromSuperContents(model_t *model, int supercontents)
5490 {
5491         int nativecontents = 0;
5492         if (supercontents & SUPERCONTENTS_SOLID)
5493                 nativecontents |= CONTENTSQ3_SOLID;
5494         if (supercontents & SUPERCONTENTS_WATER)
5495                 nativecontents |= CONTENTSQ3_WATER;
5496         if (supercontents & SUPERCONTENTS_SLIME)
5497                 nativecontents |= CONTENTSQ3_SLIME;
5498         if (supercontents & SUPERCONTENTS_LAVA)
5499                 nativecontents |= CONTENTSQ3_LAVA;
5500         if (supercontents & SUPERCONTENTS_BODY)
5501                 nativecontents |= CONTENTSQ3_BODY;
5502         if (supercontents & SUPERCONTENTS_CORPSE)
5503                 nativecontents |= CONTENTSQ3_CORPSE;
5504         if (supercontents & SUPERCONTENTS_NODROP)
5505                 nativecontents |= CONTENTSQ3_NODROP;
5506         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
5507                 nativecontents |= CONTENTSQ3_PLAYERCLIP;
5508         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
5509                 nativecontents |= CONTENTSQ3_MONSTERCLIP;
5510         if (supercontents & SUPERCONTENTS_DONOTENTER)
5511                 nativecontents |= CONTENTSQ3_DONOTENTER;
5512         return nativecontents;
5513 }
5514
5515 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
5516 {
5517         int numleafs;
5518         while (node->plane)
5519         {
5520                 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
5521                 node = node->children[1];
5522         }
5523         numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
5524         if (loadmodel->brush.num_leafs < numleafs)
5525                 loadmodel->brush.num_leafs = numleafs;
5526 }
5527
5528 void Mod_Q3BSP_Load(model_t *mod, void *buffer, void *bufferend)
5529 {
5530         int i, j, numshadowmeshtriangles;
5531         q3dheader_t *header;
5532         float corner[3], yawradius, modelradius;
5533         msurface_t *surface;
5534
5535         mod->type = mod_brushq3;
5536         mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
5537         mod->numskins = 1;
5538
5539         header = (q3dheader_t *)buffer;
5540
5541         i = LittleLong(header->version);
5542         if (i != Q3BSPVERSION)
5543                 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
5544         mod->brush.ishlbsp = false;
5545         mod->brush.ismcbsp = false;
5546         if (loadmodel->isworldmodel)
5547         {
5548                 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
5549                 Cvar_SetValue("mcbsp", mod->brush.ismcbsp);
5550         }
5551
5552         mod->soundfromcenter = true;
5553         mod->TraceBox = Mod_Q3BSP_TraceBox;
5554         mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
5555         mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
5556         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
5557         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
5558         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
5559         mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
5560         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
5561         mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
5562         mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
5563         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
5564         mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
5565         mod->Draw = R_Q1BSP_Draw;
5566         mod->GetLightInfo = R_Q1BSP_GetLightInfo;
5567         mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
5568         mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
5569         mod->DrawLight = R_Q1BSP_DrawLight;
5570
5571         mod_base = (qbyte *)header;
5572
5573         // swap all the lumps
5574         header->ident = LittleLong(header->ident);
5575         header->version = LittleLong(header->version);
5576         for (i = 0;i < Q3HEADER_LUMPS;i++)
5577         {
5578                 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
5579                 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
5580         }
5581
5582         Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
5583         Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
5584         Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
5585         Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
5586         Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
5587         Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
5588         Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
5589         Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
5590         Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS]);
5591         Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
5592         Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
5593         Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
5594         Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
5595         Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
5596         Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
5597         Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
5598         Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
5599         loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
5600
5601         // the MakePortals code works fine on the q3bsp data as well
5602         Mod_Q1BSP_MakePortals();
5603
5604         // make a single combined shadow mesh to allow optimized shadow volume creation
5605         numshadowmeshtriangles = 0;
5606         for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
5607         {
5608                 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
5609                 numshadowmeshtriangles += surface->num_triangles;
5610         }
5611         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
5612         for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
5613                 if (surface->groupmesh)
5614                         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));
5615         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true);
5616         Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
5617
5618         loadmodel->brush.num_leafs = 0;
5619         Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
5620
5621         if (loadmodel->isworldmodel)
5622         {
5623                 // clear out any stale submodels or worldmodels lying around
5624                 // if we did this clear before now, an error might abort loading and
5625                 // leave things in a bad state
5626                 Mod_RemoveStaleWorldModels(loadmodel);
5627         }
5628
5629         mod = loadmodel;
5630         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
5631         {
5632                 if (i > 0)
5633                 {
5634                         char name[10];
5635                         // LordHavoc: only register submodels if it is the world
5636                         // (prevents external bsp models from replacing world submodels with
5637                         //  their own)
5638                         if (!loadmodel->isworldmodel)
5639                                 continue;
5640                         // duplicate the basic information
5641                         sprintf(name, "*%i", i);
5642                         mod = Mod_FindName(name);
5643                         *mod = *loadmodel;
5644                         strcpy(mod->name, name);
5645                         // textures and memory belong to the main model
5646                         mod->texturepool = NULL;
5647                         mod->mempool = NULL;
5648                         mod->brush.GetPVS = NULL;
5649                         mod->brush.FatPVS = NULL;
5650                         mod->brush.BoxTouchingPVS = NULL;
5651                         mod->brush.BoxTouchingLeafPVS = NULL;
5652                         mod->brush.BoxTouchingVisibleLeafs = NULL;
5653                         mod->brush.FindBoxClusters = NULL;
5654                         mod->brush.LightPoint = NULL;
5655                         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
5656                 }
5657                 mod->brush.submodel = i;
5658
5659                 // make the model surface list (used by shadowing/lighting)
5660                 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
5661                 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
5662                 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
5663                 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
5664                 mod->surfacelist = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->surfacelist));
5665                 for (j = 0;j < mod->nummodelsurfaces;j++)
5666                         mod->surfacelist[j] = mod->firstmodelsurface + j;
5667
5668                 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
5669                 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
5670                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5671                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5672                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5673                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
5674                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
5675                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5676                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5677                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
5678                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
5679                 mod->yawmins[2] = mod->normalmins[2];
5680                 mod->yawmaxs[2] = mod->normalmaxs[2];
5681                 mod->radius = modelradius;
5682                 mod->radius2 = modelradius * modelradius;
5683
5684                 for (j = 0;j < mod->nummodelsurfaces;j++)
5685                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->surfaceflags & Q3SURFACEFLAG_SKY)
5686                                 break;
5687                 if (j < mod->nummodelsurfaces)
5688                         mod->DrawSky = R_Q1BSP_DrawSky;
5689         }
5690 }
5691
5692 void Mod_IBSP_Load(model_t *mod, void *buffer, void *bufferend)
5693 {
5694         int i = LittleLong(((int *)buffer)[1]);
5695         if (i == Q3BSPVERSION)
5696                 Mod_Q3BSP_Load(mod,buffer, bufferend);
5697         else if (i == Q2BSPVERSION)
5698                 Mod_Q2BSP_Load(mod,buffer, bufferend);
5699         else
5700                 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i\n", i);
5701 }
5702
5703 void Mod_MAP_Load(model_t *mod, void *buffer, void *bufferend)
5704 {
5705         Host_Error("Mod_MAP_Load: not yet implemented\n");
5706 }
5707