2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
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"};
48 void Mod_BrushInit(void)
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);
70 static mleaf_t *Mod_Q1BSP_PointInLeaf(model_t *model, const vec3_t p)
77 // LordHavoc: modified to start at first clip node,
78 // in other words: first node of the (sub)model
79 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
81 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
83 return (mleaf_t *)node;
86 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(model_t *model, const vec3_t p, qbyte *out, int outsize)
90 leaf = Mod_Q1BSP_PointInLeaf(model, p);
93 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
96 memcpy(out, leaf->ambient_sound_level, i);
102 memset(out, 0, outsize);
105 static int Mod_Q1BSP_FindBoxClusters(model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
107 int numclusters = 0, side, nodestackindex = 0;
108 mnode_t *node, *nodestack[1024];
109 if (!model->brush.num_pvsclusters)
111 node = model->brush.data_nodes;
116 // node - recurse down the BSP tree
117 side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
120 // box is on one side of plane, take that path
121 node = node->children[side];
125 // box crosses plane, take one path and remember the other
126 if (nodestackindex < 1024)
127 nodestack[nodestackindex++] = node->children[0];
128 node = node->children[1];
133 // leaf - check cluster bit
134 if (numclusters < maxclusters)
135 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
137 // try another path we didn't take earlier
138 if (nodestackindex == 0)
140 node = nodestack[--nodestackindex];
143 // return number of clusters found (even if more than the maxclusters)
147 static int Mod_Q1BSP_BoxTouchingPVS(model_t *model, const qbyte *pvs, const vec3_t mins, const vec3_t maxs)
149 int clusterindex, side, nodestackindex = 0;
150 mnode_t *node, *nodestack[1024];
151 if (!model->brush.num_pvsclusters)
153 node = model->brush.data_nodes;
158 // node - recurse down the BSP tree
159 side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
162 // box is on one side of plane, take that path
163 node = node->children[side];
167 // box crosses plane, take one path and remember the other
168 if (nodestackindex < 1024)
169 nodestack[nodestackindex++] = node->children[0];
170 node = node->children[1];
175 // leaf - check cluster bit
176 clusterindex = ((mleaf_t *)node)->clusterindex;
177 if (CHECKPVSBIT(pvs, clusterindex))
179 // it is visible, return immediately with the news
184 // nothing to see here, try another path we didn't take earlier
185 if (nodestackindex == 0)
187 node = nodestack[--nodestackindex];
195 static int Mod_Q1BSP_BoxTouchingLeafPVS(model_t *model, const qbyte *pvs, const vec3_t mins, const vec3_t maxs)
197 int clusterindex, side, nodestackindex = 0;
198 mnode_t *node, *nodestack[1024];
199 if (!model->brush.num_leafs)
201 node = model->brush.data_nodes;
206 // node - recurse down the BSP tree
207 side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
210 // box is on one side of plane, take that path
211 node = node->children[side];
215 // box crosses plane, take one path and remember the other
216 if (nodestackindex < 1024)
217 nodestack[nodestackindex++] = node->children[0];
218 node = node->children[1];
223 // leaf - check cluster bit
224 clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
225 if (CHECKPVSBIT(pvs, clusterindex))
227 // it is visible, return immediately with the news
232 // nothing to see here, try another path we didn't take earlier
233 if (nodestackindex == 0)
235 node = nodestack[--nodestackindex];
243 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(model_t *model, const qbyte *visibleleafs, const vec3_t mins, const vec3_t maxs)
245 int side, nodestackindex = 0;
246 mnode_t *node, *nodestack[1024];
247 node = model->brush.data_nodes;
252 // node - recurse down the BSP tree
253 side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
256 // box is on one side of plane, take that path
257 node = node->children[side];
261 // box crosses plane, take one path and remember the other
262 if (nodestackindex < 1024)
263 nodestack[nodestackindex++] = node->children[0];
264 node = node->children[1];
269 // leaf - check if it is visible
270 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
272 // it is visible, return immediately with the news
277 // nothing to see here, try another path we didn't take earlier
278 if (nodestackindex == 0)
280 node = nodestack[--nodestackindex];
288 typedef struct findnonsolidlocationinfo_s
296 findnonsolidlocationinfo_t;
298 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
300 int i, surfacenum, k, *tri, *mark;
301 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
303 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
305 surface = info->model->data_surfaces + *mark;
306 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
308 for (k = 0;k < surface->num_triangles;k++)
310 tri = (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle) + k * 3;
311 VectorCopy((surface->groupmesh->data_vertex3f + tri[0] * 3), vert[0]);
312 VectorCopy((surface->groupmesh->data_vertex3f + tri[1] * 3), vert[1]);
313 VectorCopy((surface->groupmesh->data_vertex3f + tri[2] * 3), vert[2]);
314 VectorSubtract(vert[1], vert[0], edge[0]);
315 VectorSubtract(vert[2], vert[1], edge[1]);
316 CrossProduct(edge[1], edge[0], facenormal);
317 if (facenormal[0] || facenormal[1] || facenormal[2])
319 VectorNormalize(facenormal);
320 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
321 if (f <= info->bestdist && f >= -info->bestdist)
323 VectorSubtract(vert[0], vert[2], edge[2]);
324 VectorNormalize(edge[0]);
325 VectorNormalize(edge[1]);
326 VectorNormalize(edge[2]);
327 CrossProduct(facenormal, edge[0], edgenormal[0]);
328 CrossProduct(facenormal, edge[1], edgenormal[1]);
329 CrossProduct(facenormal, edge[2], edgenormal[2]);
331 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
332 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
333 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
335 // we got lucky, the center is within the face
336 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
340 if (info->bestdist > dist)
342 info->bestdist = dist;
343 VectorScale(facenormal, (info->radius - -dist), info->nudge);
348 if (info->bestdist > dist)
350 info->bestdist = dist;
351 VectorScale(facenormal, (info->radius - dist), info->nudge);
357 // check which edge or vertex the center is nearest
358 for (i = 0;i < 3;i++)
360 f = DotProduct(info->center, edge[i]);
361 if (f >= DotProduct(vert[0], edge[i])
362 && f <= DotProduct(vert[1], edge[i]))
365 VectorMA(info->center, -f, edge[i], point);
366 dist = sqrt(DotProduct(point, point));
367 if (info->bestdist > dist)
369 info->bestdist = dist;
370 VectorScale(point, (info->radius / dist), info->nudge);
372 // skip both vertex checks
373 // (both are further away than this edge)
378 // not on edge, check first vertex of edge
379 VectorSubtract(info->center, vert[i], point);
380 dist = sqrt(DotProduct(point, point));
381 if (info->bestdist > dist)
383 info->bestdist = dist;
384 VectorScale(point, (info->radius / dist), info->nudge);
396 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
400 float f = PlaneDiff(info->center, node->plane);
401 if (f >= -info->bestdist)
402 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
403 if (f <= info->bestdist)
404 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
408 if (((mleaf_t *)node)->numleafsurfaces)
409 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
413 static void Mod_Q1BSP_FindNonSolidLocation(model_t *model, const vec3_t in, vec3_t out, float radius)
416 findnonsolidlocationinfo_t info;
422 VectorCopy(in, info.center);
423 info.radius = radius;
428 VectorClear(info.nudge);
429 info.bestdist = radius;
430 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
431 VectorAdd(info.center, info.nudge, info.center);
433 while (info.bestdist < radius && ++i < 10);
434 VectorCopy(info.center, out);
437 int Mod_Q1BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents)
439 switch(nativecontents)
444 return SUPERCONTENTS_SOLID;
446 return SUPERCONTENTS_WATER;
448 return SUPERCONTENTS_SLIME;
450 return SUPERCONTENTS_LAVA;
452 return SUPERCONTENTS_SKY;
457 int Mod_Q1BSP_NativeContentsFromSuperContents(model_t *model, int supercontents)
459 if (supercontents & SUPERCONTENTS_SOLID)
460 return CONTENTS_SOLID;
461 if (supercontents & SUPERCONTENTS_SKY)
463 if (supercontents & SUPERCONTENTS_LAVA)
464 return CONTENTS_LAVA;
465 if (supercontents & SUPERCONTENTS_SLIME)
466 return CONTENTS_SLIME;
467 if (supercontents & SUPERCONTENTS_WATER)
468 return CONTENTS_WATER;
469 return CONTENTS_EMPTY;
472 typedef struct RecursiveHullCheckTraceInfo_s
474 // the hull we're tracing through
477 // the trace structure to fill in
480 // start, end, and end - start (in model space)
485 RecursiveHullCheckTraceInfo_t;
487 // 1/32 epsilon to keep floating point happy
488 #define DIST_EPSILON (0.03125)
490 #define HULLCHECKSTATE_EMPTY 0
491 #define HULLCHECKSTATE_SOLID 1
492 #define HULLCHECKSTATE_DONE 2
494 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
496 // status variables, these don't need to be saved on the stack when
497 // recursing... but are because this should be thread-safe
498 // (note: tracing against a bbox is not thread-safe, yet)
503 // variables that need to be stored on the stack when recursing
508 // LordHavoc: a goto! everyone flee in terror... :)
513 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
514 if (!t->trace->startfound)
516 t->trace->startfound = true;
517 t->trace->startsupercontents |= num;
519 if (num & SUPERCONTENTS_LIQUIDSMASK)
520 t->trace->inwater = true;
522 t->trace->inopen = true;
523 if (num & t->trace->hitsupercontentsmask)
525 // if the first leaf is solid, set startsolid
526 if (t->trace->allsolid)
527 t->trace->startsolid = true;
528 #if COLLISIONPARANOID >= 3
531 return HULLCHECKSTATE_SOLID;
535 t->trace->allsolid = false;
536 #if COLLISIONPARANOID >= 3
539 return HULLCHECKSTATE_EMPTY;
543 // find the point distances
544 node = t->hull->clipnodes + num;
546 plane = t->hull->planes + node->planenum;
549 t1 = p1[plane->type] - plane->dist;
550 t2 = p2[plane->type] - plane->dist;
554 t1 = DotProduct (plane->normal, p1) - plane->dist;
555 t2 = DotProduct (plane->normal, p2) - plane->dist;
562 #if COLLISIONPARANOID >= 3
565 num = node->children[1];
574 #if COLLISIONPARANOID >= 3
577 num = node->children[0];
583 // the line intersects, find intersection point
584 // LordHavoc: this uses the original trace for maximum accuracy
585 #if COLLISIONPARANOID >= 3
590 t1 = t->start[plane->type] - plane->dist;
591 t2 = t->end[plane->type] - plane->dist;
595 t1 = DotProduct (plane->normal, t->start) - plane->dist;
596 t2 = DotProduct (plane->normal, t->end) - plane->dist;
599 midf = t1 / (t1 - t2);
600 midf = bound(p1f, midf, p2f);
601 VectorMA(t->start, midf, t->dist, mid);
603 // recurse both sides, front side first
604 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
605 // if this side is not empty, return what it is (solid or done)
606 if (ret != HULLCHECKSTATE_EMPTY)
609 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
610 // if other side is not solid, return what it is (empty or done)
611 if (ret != HULLCHECKSTATE_SOLID)
614 // front is air and back is solid, this is the impact point...
617 t->trace->plane.dist = -plane->dist;
618 VectorNegate (plane->normal, t->trace->plane.normal);
622 t->trace->plane.dist = plane->dist;
623 VectorCopy (plane->normal, t->trace->plane.normal);
626 // calculate the true fraction
627 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
628 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
629 midf = t1 / (t1 - t2);
630 t->trace->realfraction = bound(0, midf, 1);
632 // calculate the return fraction which is nudged off the surface a bit
633 midf = (t1 - DIST_EPSILON) / (t1 - t2);
634 t->trace->fraction = bound(0, midf, 1);
636 #if COLLISIONPARANOID >= 3
639 return HULLCHECKSTATE_DONE;
642 #if COLLISIONPARANOID < 2
643 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
646 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];
647 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
648 t->trace->startsupercontents |= num;
649 if (num & SUPERCONTENTS_LIQUIDSMASK)
650 t->trace->inwater = true;
652 t->trace->inopen = true;
653 if (num & t->trace->hitsupercontentsmask)
655 t->trace->allsolid = t->trace->startsolid = true;
656 return HULLCHECKSTATE_SOLID;
660 t->trace->allsolid = t->trace->startsolid = false;
661 return HULLCHECKSTATE_EMPTY;
666 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)
668 // this function currently only supports same size start and end
670 RecursiveHullCheckTraceInfo_t rhc;
672 memset(&rhc, 0, sizeof(rhc));
673 memset(trace, 0, sizeof(trace_t));
675 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
676 rhc.trace->fraction = 1;
677 rhc.trace->realfraction = 1;
678 rhc.trace->allsolid = true;
679 VectorSubtract(boxstartmaxs, boxstartmins, boxsize);
681 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
682 else if (model->brush.ismcbsp)
684 if (boxsize[2] < 48) // pick the nearest of 40 or 56
685 rhc.hull = &model->brushq1.hulls[2]; // 16x16x40
687 rhc.hull = &model->brushq1.hulls[1]; // 16x16x56
689 else if (model->brush.ishlbsp)
691 // LordHavoc: this has to have a minor tolerance (the .1) because of
692 // minor float precision errors from the box being transformed around
693 if (boxsize[0] < 32.1)
695 if (boxsize[2] < 54) // pick the nearest of 36 or 72
696 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
698 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
701 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
705 // LordHavoc: this has to have a minor tolerance (the .1) because of
706 // minor float precision errors from the box being transformed around
707 if (boxsize[0] < 32.1)
708 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
710 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
712 VectorSubtract(boxstartmins, rhc.hull->clip_mins, rhc.start);
713 VectorSubtract(boxendmins, rhc.hull->clip_mins, rhc.end);
714 VectorSubtract(rhc.end, rhc.start, rhc.dist);
715 #if COLLISIONPARANOID >= 2
716 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]);
717 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
720 if (DotProduct(rhc.dist, rhc.dist))
721 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
723 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
727 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)
731 colplanef_t cbox_planes[6];
732 cbox.supercontents = boxsupercontents;
735 cbox.numtriangles = 0;
736 cbox.planes = cbox_planes;
738 cbox.elements = NULL;
746 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];
747 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];
748 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];
749 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];
750 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];
751 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];
752 memset(trace, 0, sizeof(trace_t));
753 trace->hitsupercontentsmask = hitsupercontentsmask;
755 trace->realfraction = 1;
756 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
758 RecursiveHullCheckTraceInfo_t rhc;
759 static hull_t box_hull;
760 static dclipnode_t box_clipnodes[6];
761 static mplane_t box_planes[6];
762 // fill in a default trace
763 memset(&rhc, 0, sizeof(rhc));
764 memset(trace, 0, sizeof(trace_t));
765 //To keep everything totally uniform, bounding boxes are turned into small
766 //BSP trees instead of being compared directly.
767 // create a temp hull from bounding box sizes
768 box_planes[0].dist = cmaxs[0] - mins[0];
769 box_planes[1].dist = cmins[0] - maxs[0];
770 box_planes[2].dist = cmaxs[1] - mins[1];
771 box_planes[3].dist = cmins[1] - maxs[1];
772 box_planes[4].dist = cmaxs[2] - mins[2];
773 box_planes[5].dist = cmins[2] - maxs[2];
774 #if COLLISIONPARANOID >= 3
775 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 if (box_hull.clipnodes == NULL)
782 //Set up the planes and clipnodes so that the six floats of a bounding box
783 //can just be stored out and get a proper hull_t structure.
785 box_hull.clipnodes = box_clipnodes;
786 box_hull.planes = box_planes;
787 box_hull.firstclipnode = 0;
788 box_hull.lastclipnode = 5;
790 for (i = 0;i < 6;i++)
792 box_clipnodes[i].planenum = i;
796 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
798 box_clipnodes[i].children[side^1] = i + 1;
800 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
802 box_planes[i].type = i>>1;
803 box_planes[i].normal[i>>1] = 1;
807 // trace a line through the generated clipping hull
808 //rhc.boxsupercontents = boxsupercontents;
809 rhc.hull = &box_hull;
811 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
812 rhc.trace->fraction = 1;
813 rhc.trace->realfraction = 1;
814 rhc.trace->allsolid = true;
815 VectorCopy(start, rhc.start);
816 VectorCopy(end, rhc.end);
817 VectorSubtract(rhc.end, rhc.start, rhc.dist);
818 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
819 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
820 if (rhc.trace->startsupercontents)
821 rhc.trace->startsupercontents = boxsupercontents;
825 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)
827 int side, distz = endz - startz;
833 return false; // didn't hit anything
835 switch (node->plane->type)
838 node = node->children[x < node->plane->dist];
841 node = node->children[y < node->plane->dist];
844 side = startz < node->plane->dist;
845 if ((endz < node->plane->dist) == side)
847 node = node->children[side];
850 // found an intersection
851 mid = node->plane->dist;
854 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
855 front += startz * node->plane->normal[2];
856 back += endz * node->plane->normal[2];
857 side = front < node->plane->dist;
858 if ((back < node->plane->dist) == side)
860 node = node->children[side];
863 // found an intersection
864 mid = startz + distz * (front - node->plane->dist) / (front - back);
868 // go down front side
869 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
870 return true; // hit something
873 // check for impact on this node
874 if (node->numsurfaces)
879 surface = model->data_surfaces + node->firstsurface;
880 for (i = 0;i < node->numsurfaces;i++, surface++)
882 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo->samples)
883 continue; // no lightmaps
885 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];
886 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];
888 if (ds >= 0 && ds < surface->lightmapinfo->extents[0] && dt >= 0 && dt < surface->lightmapinfo->extents[1])
891 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;
892 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
893 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
894 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
895 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
897 lightmap = surface->lightmapinfo->samples + ((dt>>4) * lmwidth + (ds>>4))*3; // LordHavoc: *3 for colored lighting
899 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
901 scale = d_lightstylevalue[surface->lightmapinfo->styles[maps]];
902 r00 += lightmap[ 0] * scale;g00 += lightmap[ 1] * scale;b00 += lightmap[ 2] * scale;
903 r01 += lightmap[ 3] * scale;g01 += lightmap[ 4] * scale;b01 += lightmap[ 5] * scale;
904 r10 += lightmap[line3+0] * scale;g10 += lightmap[line3+1] * scale;b10 += lightmap[line3+2] * scale;
905 r11 += lightmap[line3+3] * scale;g11 += lightmap[line3+4] * scale;b11 += lightmap[line3+5] * scale;
910 LordHavoc: here's the readable version of the interpolation
911 code, not quite as easy for the compiler to optimize...
913 dsfrac is the X position in the lightmap pixel, * 16
914 dtfrac is the Y position in the lightmap pixel, * 16
915 r00 is top left corner, r01 is top right corner
916 r10 is bottom left corner, r11 is bottom right corner
917 g and b are the same layout.
918 r0 and r1 are the top and bottom intermediate results
920 first we interpolate the top two points, to get the top
923 r0 = (((r01-r00) * dsfrac) >> 4) + r00;
924 g0 = (((g01-g00) * dsfrac) >> 4) + g00;
925 b0 = (((b01-b00) * dsfrac) >> 4) + b00;
927 then we interpolate the bottom two points, to get the
930 r1 = (((r11-r10) * dsfrac) >> 4) + r10;
931 g1 = (((g11-g10) * dsfrac) >> 4) + g10;
932 b1 = (((b11-b10) * dsfrac) >> 4) + b10;
934 then we interpolate the top and bottom samples to get the
935 middle sample (the one which was requested)
937 r = (((r1-r0) * dtfrac) >> 4) + r0;
938 g = (((g1-g0) * dtfrac) >> 4) + g0;
939 b = (((b1-b0) * dtfrac) >> 4) + b0;
942 ambientcolor[0] += (float) ((((((((r11-r10) * dsfrac) >> 4) + r10)-((((r01-r00) * dsfrac) >> 4) + r00)) * dtfrac) >> 4) + ((((r01-r00) * dsfrac) >> 4) + r00)) * (1.0f / 32768.0f);
943 ambientcolor[1] += (float) ((((((((g11-g10) * dsfrac) >> 4) + g10)-((((g01-g00) * dsfrac) >> 4) + g00)) * dtfrac) >> 4) + ((((g01-g00) * dsfrac) >> 4) + g00)) * (1.0f / 32768.0f);
944 ambientcolor[2] += (float) ((((((((b11-b10) * dsfrac) >> 4) + b10)-((((b01-b00) * dsfrac) >> 4) + b00)) * dtfrac) >> 4) + ((((b01-b00) * dsfrac) >> 4) + b00)) * (1.0f / 32768.0f);
945 return true; // success
951 node = node->children[side ^ 1];
953 distz = endz - startz;
958 void Mod_Q1BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
960 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 static void Mod_Q1BSP_DecompressVis(const qbyte *in, const qbyte *inend, qbyte *out, qbyte *outend)
966 qbyte *outstart = out;
971 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
981 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 for (c = *in++;c > 0;c--)
988 Con_Printf("Mod_Q1BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
1001 A sky texture is 256*128, with the right side being a masked overlay
1004 void R_Q1BSP_LoadSplitSky (qbyte *src, int width, int height, int bytesperpixel)
1007 unsigned solidpixels[128*128], alphapixels[128*128];
1009 // if sky isn't the right size, just use it as a solid layer
1010 if (width != 256 || height != 128)
1012 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);
1013 loadmodel->brush.alphaskytexture = NULL;;
1017 if (bytesperpixel == 4)
1019 for (i = 0;i < 128;i++)
1021 for (j = 0;j < 128;j++)
1023 solidpixels[(i*128) + j] = ((unsigned *)src)[i*256+j+128];
1024 alphapixels[(i*128) + j] = ((unsigned *)src)[i*256+j];
1030 // make an average value for the back to avoid
1031 // a fringe on the top level
1040 for (i = 0;i < 128;i++)
1042 for (j = 0;j < 128;j++)
1044 rgba.i = palette_complete[src[i*256 + j + 128]];
1050 rgba.b[0] = r/(128*128);
1051 rgba.b[1] = g/(128*128);
1052 rgba.b[2] = b/(128*128);
1054 for (i = 0;i < 128;i++)
1056 for (j = 0;j < 128;j++)
1058 solidpixels[(i*128) + j] = palette_complete[src[i*256 + j + 128]];
1059 alphapixels[(i*128) + j] = (p = src[i*256 + j]) ? palette_complete[p] : rgba.i;
1064 loadmodel->brush.solidskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_solidtexture", 128, 128, (qbyte *) solidpixels, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
1065 loadmodel->brush.alphaskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_alphatexture", 128, 128, (qbyte *) alphapixels, TEXTYPE_RGBA, TEXF_ALPHA | TEXF_PRECACHE, NULL);
1068 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1070 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1072 texture_t *tx, *tx2, *anims[10], *altanims[10];
1074 qbyte *data, *mtdata;
1077 loadmodel->data_textures = NULL;
1079 // add two slots for notexture walls and notexture liquids
1082 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1083 m->nummiptex = LittleLong (m->nummiptex);
1084 loadmodel->num_textures = m->nummiptex + 2;
1089 loadmodel->num_textures = 2;
1092 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1094 // fill out all slots with notexture
1095 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1097 strcpy(tx->name, "NO TEXTURE FOUND");
1100 tx->skin.base = r_texture_notexture;
1101 tx->basematerialflags = 0;
1102 if (i == loadmodel->num_textures - 1)
1104 tx->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES;
1105 tx->supercontents = SUPERCONTENTS_WATER;
1109 tx->basematerialflags |= MATERIALFLAG_WALL;
1110 tx->supercontents = SUPERCONTENTS_SOLID;
1112 tx->currentframe = tx;
1118 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1120 // LordHavoc: mostly rewritten map texture loader
1121 for (i = 0;i < m->nummiptex;i++)
1123 dofs[i] = LittleLong(dofs[i]);
1124 if (dofs[i] == -1 || r_nosurftextures.integer)
1126 dmiptex = (miptex_t *)((qbyte *)m + dofs[i]);
1128 // make sure name is no more than 15 characters
1129 for (j = 0;dmiptex->name[j] && j < 15;j++)
1130 name[j] = dmiptex->name[j];
1133 mtwidth = LittleLong(dmiptex->width);
1134 mtheight = LittleLong(dmiptex->height);
1136 j = LittleLong(dmiptex->offsets[0]);
1140 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1142 Con_Printf("Texture \"%s\" in \"%s\"is corrupt or incomplete\n", dmiptex->name, loadmodel->name);
1145 mtdata = (qbyte *)dmiptex + j;
1148 if ((mtwidth & 15) || (mtheight & 15))
1149 Con_Printf("warning: texture \"%s\" in \"%s\" is not 16 aligned\n", dmiptex->name, loadmodel->name);
1151 // LordHavoc: force all names to lowercase
1152 for (j = 0;name[j];j++)
1153 if (name[j] >= 'A' && name[j] <= 'Z')
1154 name[j] += 'a' - 'A';
1156 tx = loadmodel->data_textures + i;
1157 strcpy(tx->name, name);
1158 tx->width = mtwidth;
1159 tx->height = mtheight;
1163 sprintf(tx->name, "unnamed%i", i);
1164 Con_Printf("warning: unnamed texture in %s, renaming to %s\n", loadmodel->name, tx->name);
1167 // LordHavoc: HL sky textures are entirely different than quake
1168 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == 256 && mtheight == 128)
1170 if (loadmodel->isworldmodel)
1172 data = loadimagepixels(tx->name, false, 0, 0);
1175 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1178 else if (mtdata != NULL)
1179 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1184 if (!Mod_LoadSkinFrame(&tx->skin, tx->name, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, false, true))
1186 // did not find external texture, load it from the bsp or wad3
1187 if (loadmodel->brush.ishlbsp)
1189 // internal texture overrides wad
1190 qbyte *pixels, *freepixels, *fogpixels;
1191 pixels = freepixels = NULL;
1193 pixels = W_ConvertWAD3Texture(dmiptex);
1195 pixels = freepixels = W_GetTexture(tx->name);
1198 tx->width = image_width;
1199 tx->height = image_height;
1200 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);
1201 if (Image_CheckAlpha(pixels, image_width * image_height, true))
1203 fogpixels = (qbyte *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1204 for (j = 0;j < image_width * image_height * 4;j += 4)
1206 fogpixels[j + 0] = 255;
1207 fogpixels[j + 1] = 255;
1208 fogpixels[j + 2] = 255;
1209 fogpixels[j + 3] = pixels[j + 3];
1211 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);
1212 Mem_Free(fogpixels);
1216 Mem_Free(freepixels);
1218 else if (mtdata) // texture included
1219 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 if (tx->skin.base == NULL)
1227 tx->skin.base = r_texture_notexture;
1230 tx->basematerialflags = 0;
1231 if (tx->name[0] == '*')
1233 // turb does not block movement
1234 tx->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES;
1235 // LordHavoc: some turbulent textures should be fullbright and solid
1236 if (!strncmp(tx->name,"*lava",5)
1237 || !strncmp(tx->name,"*teleport",9)
1238 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1239 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
1241 tx->basematerialflags |= MATERIALFLAG_WATERALPHA;
1242 if (!strncmp(tx->name, "*lava", 5))
1243 tx->supercontents = SUPERCONTENTS_LAVA;
1244 else if (!strncmp(tx->name, "*slime", 6))
1245 tx->supercontents = SUPERCONTENTS_SLIME;
1247 tx->supercontents = SUPERCONTENTS_WATER;
1249 else if (tx->name[0] == 's' && tx->name[1] == 'k' && tx->name[2] == 'y')
1251 tx->supercontents = SUPERCONTENTS_SKY;
1252 tx->basematerialflags |= MATERIALFLAG_SKY;
1256 tx->supercontents = SUPERCONTENTS_SOLID;
1257 tx->basematerialflags |= MATERIALFLAG_WALL;
1260 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
1262 // start out with no animation
1263 tx->currentframe = tx;
1266 // sequence the animations
1267 for (i = 0;i < m->nummiptex;i++)
1269 tx = loadmodel->data_textures + i;
1270 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1272 if (tx->anim_total[0] || tx->anim_total[1])
1273 continue; // already sequenced
1275 // find the number of frames in the animation
1276 memset(anims, 0, sizeof(anims));
1277 memset(altanims, 0, sizeof(altanims));
1279 for (j = i;j < m->nummiptex;j++)
1281 tx2 = loadmodel->data_textures + j;
1282 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1286 if (num >= '0' && num <= '9')
1287 anims[num - '0'] = tx2;
1288 else if (num >= 'a' && num <= 'j')
1289 altanims[num - 'a'] = tx2;
1291 Con_Printf("Bad animating texture %s\n", tx->name);
1295 for (j = 0;j < 10;j++)
1302 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1305 for (j = 0;j < max;j++)
1309 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1313 for (j = 0;j < altmax;j++)
1317 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1326 // if there is no alternate animation, duplicate the primary
1327 // animation into the alternate
1329 for (k = 0;k < 10;k++)
1330 altanims[k] = anims[k];
1333 // link together the primary animation
1334 for (j = 0;j < max;j++)
1337 tx2->animated = true;
1338 tx2->anim_total[0] = max;
1339 tx2->anim_total[1] = altmax;
1340 for (k = 0;k < 10;k++)
1342 tx2->anim_frames[0][k] = anims[k];
1343 tx2->anim_frames[1][k] = altanims[k];
1347 // if there really is an alternate anim...
1348 if (anims[0] != altanims[0])
1350 // link together the alternate animation
1351 for (j = 0;j < altmax;j++)
1354 tx2->animated = true;
1355 // the primary/alternate are reversed here
1356 tx2->anim_total[0] = altmax;
1357 tx2->anim_total[1] = max;
1358 for (k = 0;k < 10;k++)
1360 tx2->anim_frames[0][k] = altanims[k];
1361 tx2->anim_frames[1][k] = anims[k];
1368 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1371 qbyte *in, *out, *data, d;
1372 char litfilename[1024];
1373 loadmodel->brushq1.lightdata = NULL;
1374 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1376 loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen);
1377 for (i=0; i<l->filelen; i++)
1378 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1380 else if (loadmodel->brush.ismcbsp)
1382 loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen);
1383 memcpy(loadmodel->brushq1.lightdata, mod_base + l->fileofs, l->filelen);
1385 else // LordHavoc: bsp version 29 (normal white lighting)
1387 // LordHavoc: hope is not lost yet, check for a .lit file to load
1388 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1389 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1390 strlcat (litfilename, ".lit", sizeof (litfilename));
1391 data = (qbyte*) FS_LoadFile(litfilename, tempmempool, false);
1394 if (fs_filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1396 i = LittleLong(((int *)data)[1]);
1399 Con_DPrintf("loaded %s\n", litfilename);
1400 loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, fs_filesize - 8);
1401 memcpy(loadmodel->brushq1.lightdata, data + 8, fs_filesize - 8);
1407 Con_Printf("Unknown .lit file version (%d)\n", i);
1413 if (fs_filesize == 8)
1414 Con_Print("Empty .lit file, ignoring\n");
1416 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", fs_filesize, 8 + l->filelen * 3);
1420 // LordHavoc: oh well, expand the white lighting data
1423 loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1424 in = loadmodel->brushq1.lightdata + l->filelen*2; // place the file at the end, so it will not be overwritten until the very last write
1425 out = loadmodel->brushq1.lightdata;
1426 memcpy(in, mod_base + l->fileofs, l->filelen);
1427 for (i = 0;i < l->filelen;i++)
1437 static void Mod_Q1BSP_LoadLightList(void)
1439 int a, n, numlights;
1440 char tempchar, *s, *t, *lightsstring, lightsfilename[1024];
1443 strlcpy (lightsfilename, loadmodel->name, sizeof (lightsfilename));
1444 FS_StripExtension (lightsfilename, lightsfilename, sizeof(lightsfilename));
1445 strlcat (lightsfilename, ".lights", sizeof (lightsfilename));
1446 s = lightsstring = (char *) FS_LoadFile(lightsfilename, tempmempool, false);
1452 while (*s && *s != '\n' && *s != '\r')
1456 Mem_Free(lightsstring);
1457 Con_Printf("lights file must end with a newline\n");
1463 loadmodel->brushq1.lights = (mlight_t *)Mem_Alloc(loadmodel->mempool, numlights * sizeof(mlight_t));
1466 while (*s && n < numlights)
1469 while (*s && *s != '\n' && *s != '\r')
1473 Con_Printf("misparsed lights file!\n");
1476 e = loadmodel->brushq1.lights + n;
1479 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);
1483 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);
1493 Con_Printf("misparsed lights file!\n");
1494 loadmodel->brushq1.numlights = numlights;
1495 Mem_Free(lightsstring);
1499 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1501 loadmodel->brushq1.num_compressedpvs = 0;
1502 loadmodel->brushq1.data_compressedpvs = NULL;
1505 loadmodel->brushq1.num_compressedpvs = l->filelen;
1506 loadmodel->brushq1.data_compressedpvs = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen);
1507 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1510 // used only for HalfLife maps
1511 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1513 char key[128], value[4096];
1518 if (!COM_ParseToken(&data, false))
1520 if (com_token[0] != '{')
1524 if (!COM_ParseToken(&data, false))
1526 if (com_token[0] == '}')
1527 break; // end of worldspawn
1528 if (com_token[0] == '_')
1529 strcpy(key, com_token + 1);
1531 strcpy(key, com_token);
1532 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1533 key[strlen(key)-1] = 0;
1534 if (!COM_ParseToken(&data, false))
1536 strcpy(value, com_token);
1537 if (!strcmp("wad", key)) // for HalfLife maps
1539 if (loadmodel->brush.ishlbsp)
1542 for (i = 0;i < 4096;i++)
1543 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1549 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1550 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1552 else if (value[i] == ';' || value[i] == 0)
1556 strcpy(wadname, "textures/");
1557 strcat(wadname, &value[j]);
1558 W_LoadTextureWadFile(wadname, false);
1570 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1572 loadmodel->brush.entities = NULL;
1575 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1576 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1577 if (loadmodel->brush.ishlbsp)
1578 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1582 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1588 in = (dvertex_t *)(mod_base + l->fileofs);
1589 if (l->filelen % sizeof(*in))
1590 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1591 count = l->filelen / sizeof(*in);
1592 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1594 loadmodel->brushq1.vertexes = out;
1595 loadmodel->brushq1.numvertexes = count;
1597 for ( i=0 ; i<count ; i++, in++, out++)
1599 out->position[0] = LittleFloat(in->point[0]);
1600 out->position[1] = LittleFloat(in->point[1]);
1601 out->position[2] = LittleFloat(in->point[2]);
1605 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1606 // can be used for this
1608 int SB_ReadInt (qbyte **buffer)
1611 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1617 float SB_ReadFloat (qbyte **buffer)
1625 u.i = SB_ReadInt (buffer);
1629 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1635 index = (qbyte *)(mod_base + l->fileofs);
1636 if (l->filelen % (48+4*hullinfo->filehulls))
1637 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1639 count = l->filelen / (48+4*hullinfo->filehulls);
1640 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1642 loadmodel->brushq1.submodels = out;
1643 loadmodel->brush.numsubmodels = count;
1645 for (i = 0; i < count; i++, out++)
1647 // spread out the mins / maxs by a pixel
1648 out->mins[0] = SB_ReadFloat (&index) - 1;
1649 out->mins[1] = SB_ReadFloat (&index) - 1;
1650 out->mins[2] = SB_ReadFloat (&index) - 1;
1651 out->maxs[0] = SB_ReadFloat (&index) + 1;
1652 out->maxs[1] = SB_ReadFloat (&index) + 1;
1653 out->maxs[2] = SB_ReadFloat (&index) + 1;
1654 out->origin[0] = SB_ReadFloat (&index);
1655 out->origin[1] = SB_ReadFloat (&index);
1656 out->origin[2] = SB_ReadFloat (&index);
1657 for (j = 0; j < hullinfo->filehulls; j++)
1658 out->headnode[j] = SB_ReadInt (&index);
1659 out->visleafs = SB_ReadInt (&index);
1660 out->firstface = SB_ReadInt (&index);
1661 out->numfaces = SB_ReadInt (&index);
1665 static void Mod_Q1BSP_LoadEdges(lump_t *l)
1671 in = (dedge_t *)(mod_base + l->fileofs);
1672 if (l->filelen % sizeof(*in))
1673 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
1674 count = l->filelen / sizeof(*in);
1675 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
1677 loadmodel->brushq1.edges = out;
1678 loadmodel->brushq1.numedges = count;
1680 for ( i=0 ; i<count ; i++, in++, out++)
1682 out->v[0] = (unsigned short)LittleShort(in->v[0]);
1683 out->v[1] = (unsigned short)LittleShort(in->v[1]);
1687 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
1691 int i, j, k, count, miptex;
1693 in = (texinfo_t *)(mod_base + l->fileofs);
1694 if (l->filelen % sizeof(*in))
1695 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
1696 count = l->filelen / sizeof(*in);
1697 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
1699 loadmodel->brushq1.texinfo = out;
1700 loadmodel->brushq1.numtexinfo = count;
1702 for (i = 0;i < count;i++, in++, out++)
1704 for (k = 0;k < 2;k++)
1705 for (j = 0;j < 4;j++)
1706 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
1708 miptex = LittleLong(in->miptex);
1709 out->flags = LittleLong(in->flags);
1711 out->texture = NULL;
1712 if (loadmodel->data_textures)
1714 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
1715 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
1717 out->texture = loadmodel->data_textures + miptex;
1719 if (out->flags & TEX_SPECIAL)
1721 // if texture chosen is NULL or the shader needs a lightmap,
1722 // force to notexture water shader
1723 if (out->texture == NULL || out->texture->basematerialflags & MATERIALFLAG_WALL)
1724 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
1728 // if texture chosen is NULL, force to notexture
1729 if (out->texture == NULL)
1730 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
1736 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
1741 mins[0] = mins[1] = mins[2] = 9999;
1742 maxs[0] = maxs[1] = maxs[2] = -9999;
1744 for (i = 0;i < numverts;i++)
1746 for (j = 0;j < 3;j++, v++)
1756 #define MAX_SUBDIVPOLYTRIANGLES 4096
1757 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
1759 static int subdivpolyverts, subdivpolytriangles;
1760 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
1761 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
1763 static int subdivpolylookupvert(vec3_t v)
1766 for (i = 0;i < subdivpolyverts;i++)
1767 if (subdivpolyvert[i][0] == v[0]
1768 && subdivpolyvert[i][1] == v[1]
1769 && subdivpolyvert[i][2] == v[2])
1771 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
1772 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
1773 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
1774 return subdivpolyverts++;
1777 static void SubdividePolygon(int numverts, float *verts)
1779 int i, i1, i2, i3, f, b, c, p;
1780 vec3_t mins, maxs, front[256], back[256];
1781 float m, *pv, *cv, dist[256], frac;
1784 Host_Error("SubdividePolygon: ran out of verts in buffer");
1786 BoundPoly(numverts, verts, mins, maxs);
1788 for (i = 0;i < 3;i++)
1790 m = (mins[i] + maxs[i]) * 0.5;
1791 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
1792 if (maxs[i] - m < 8)
1794 if (m - mins[i] < 8)
1798 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
1799 dist[c] = cv[i] - m;
1802 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
1806 VectorCopy(pv, front[f]);
1811 VectorCopy(pv, back[b]);
1814 if (dist[p] == 0 || dist[c] == 0)
1816 if ((dist[p] > 0) != (dist[c] > 0) )
1819 frac = dist[p] / (dist[p] - dist[c]);
1820 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
1821 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
1822 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
1828 SubdividePolygon(f, front[0]);
1829 SubdividePolygon(b, back[0]);
1833 i1 = subdivpolylookupvert(verts);
1834 i2 = subdivpolylookupvert(verts + 3);
1835 for (i = 2;i < numverts;i++)
1837 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
1839 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
1843 i3 = subdivpolylookupvert(verts + i * 3);
1844 subdivpolyindex[subdivpolytriangles][0] = i1;
1845 subdivpolyindex[subdivpolytriangles][1] = i2;
1846 subdivpolyindex[subdivpolytriangles][2] = i3;
1848 subdivpolytriangles++;
1852 //Breaks a polygon up along axial 64 unit
1853 //boundaries so that turbulent and sky warps
1854 //can be done reasonably.
1855 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
1861 subdivpolytriangles = 0;
1862 subdivpolyverts = 0;
1863 SubdividePolygon(surface->num_vertices, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex));
1864 if (subdivpolytriangles < 1)
1865 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?\n");
1867 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
1868 mesh->num_vertices = subdivpolyverts;
1869 mesh->num_triangles = subdivpolytriangles;
1870 mesh->vertex = (surfvertex_t *)(mesh + 1);
1871 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
1872 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
1874 for (i = 0;i < mesh->num_triangles;i++)
1875 for (j = 0;j < 3;j++)
1876 mesh->index[i*3+j] = subdivpolyindex[i][j];
1878 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
1880 VectorCopy(subdivpolyvert[i], v->v);
1881 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
1882 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
1887 static void Mod_Q1BSP_LoadFaces(lump_t *l)
1890 msurface_t *surface;
1891 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris;
1892 float texmins[2], texmaxs[2], val;
1894 in = (dface_t *)(mod_base + l->fileofs);
1895 if (l->filelen % sizeof(*in))
1896 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
1897 count = l->filelen / sizeof(*in);
1898 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
1899 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
1901 loadmodel->num_surfaces = count;
1905 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
1907 numedges = LittleShort(in->numedges);
1908 totalverts += numedges;
1909 totaltris += numedges - 2;
1912 // TODO: split up into multiple meshes as needed to avoid exceeding 65536
1914 loadmodel->nummeshes = 1;
1915 loadmodel->meshlist = (surfmesh_t **)Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *));
1916 loadmodel->meshlist[0] = Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
1920 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
1922 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
1924 // FIXME: validate edges, texinfo, etc?
1925 firstedge = LittleLong(in->firstedge);
1926 numedges = LittleShort(in->numedges);
1927 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)
1928 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)\n", firstedge, numedges, loadmodel->brushq1.numsurfedges);
1929 i = LittleShort(in->texinfo);
1930 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
1931 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)\n", i, loadmodel->brushq1.numtexinfo);
1932 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
1933 surface->texture = surface->lightmapinfo->texinfo->texture;
1935 planenum = LittleShort(in->planenum);
1936 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
1937 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)\n", planenum, loadmodel->brush.num_planes);
1939 //surface->flags = surface->texture->flags;
1940 //if (LittleShort(in->side))
1941 // surface->flags |= SURF_PLANEBACK;
1942 //surface->plane = loadmodel->brush.data_planes + planenum;
1944 surface->groupmesh = loadmodel->meshlist[0];
1945 surface->num_firstvertex = totalverts;
1946 surface->num_vertices = numedges;
1947 surface->num_firsttriangle = totaltris;
1948 surface->num_triangles = numedges - 2;
1949 totalverts += numedges;
1950 totaltris += numedges - 2;
1952 // convert edges back to a normal polygon
1953 for (i = 0;i < surface->num_vertices;i++)
1955 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
1958 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
1960 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
1961 s = DotProduct(((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
1962 t = DotProduct(((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
1963 (surface->groupmesh->data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
1964 (surface->groupmesh->data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
1965 (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
1966 (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
1967 (surface->groupmesh->data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
1970 for (i = 0;i < surface->num_triangles;i++)
1972 (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
1973 (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
1974 (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
1977 // compile additional data about the surface geometry
1978 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);
1979 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex));
1981 // generate surface extents information
1982 texmins[0] = texmaxs[0] = DotProduct((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
1983 texmins[1] = texmaxs[1] = DotProduct((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
1984 for (i = 1;i < surface->num_vertices;i++)
1986 for (j = 0;j < 2;j++)
1988 val = DotProduct((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
1989 texmins[j] = min(texmins[j], val);
1990 texmaxs[j] = max(texmaxs[j], val);
1993 for (i = 0;i < 2;i++)
1995 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
1996 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
1999 smax = surface->lightmapinfo->extents[0] >> 4;
2000 tmax = surface->lightmapinfo->extents[1] >> 4;
2001 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2002 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2005 for (i = 0;i < MAXLIGHTMAPS;i++)
2006 surface->lightmapinfo->styles[i] = in->styles[i];
2007 // force lightmap upload on first time seeing the surface
2008 surface->cached_dlight = true;
2009 surface->lightmapinfo->lightmaptexturestride = 0;
2010 surface->lightmaptexture = NULL;
2011 i = LittleLong(in->lightofs);
2014 surface->lightmapinfo->samples = NULL;
2015 // give non-lightmapped water a 1x white lightmap
2016 if ((surface->texture->basematerialflags & MATERIALFLAG_WATER) && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2018 surface->lightmapinfo->samples = (qbyte *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2019 surface->lightmapinfo->styles[0] = 0;
2020 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2023 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2024 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2025 else // LordHavoc: white lighting (bsp version 29)
2026 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2028 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2031 float u, v, ubase, vbase, uscale, vscale;
2033 if (ssize > 256 || tsize > 256)
2034 Host_Error("Bad surface extents");
2035 // stainmap for permanent marks on walls
2036 surface->lightmapinfo->stainsamples = (qbyte *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2038 memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
2040 if (r_miplightmaps.integer)
2042 surface->lightmapinfo->lightmaptexturestride = ssize;
2043 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);
2047 surface->lightmapinfo->lightmaptexturestride = R_CompatibleFragmentWidth(ssize, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, 0);
2048 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);
2050 R_FragmentLocation(surface->lightmaptexture, NULL, NULL, &ubase, &vbase, &uscale, &vscale);
2051 uscale = (uscale - ubase) / ssize;
2052 vscale = (vscale - vbase) / tsize;
2054 for (i = 0;i < surface->num_vertices;i++)
2056 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);
2057 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);
2058 (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2059 (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2060 // LordHavoc: calc lightmap data offset for vertex lighting to use
2063 (surface->groupmesh->data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2069 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2072 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion\n");
2073 node->parent = parent;
2076 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2077 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2081 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2087 in = (dnode_t *)(mod_base + l->fileofs);
2088 if (l->filelen % sizeof(*in))
2089 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2090 count = l->filelen / sizeof(*in);
2091 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2093 loadmodel->brush.data_nodes = out;
2094 loadmodel->brush.num_nodes = count;
2096 for ( i=0 ; i<count ; i++, in++, out++)
2098 for (j=0 ; j<3 ; j++)
2100 out->mins[j] = LittleShort(in->mins[j]);
2101 out->maxs[j] = LittleShort(in->maxs[j]);
2104 p = LittleLong(in->planenum);
2105 out->plane = loadmodel->brush.data_planes + p;
2107 out->firstsurface = LittleShort(in->firstface);
2108 out->numsurfaces = LittleShort(in->numfaces);
2110 for (j=0 ; j<2 ; j++)
2112 p = LittleShort(in->children[j]);
2114 out->children[j] = loadmodel->brush.data_nodes + p;
2116 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + (-1 - p));
2120 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2123 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2129 in = (dleaf_t *)(mod_base + l->fileofs);
2130 if (l->filelen % sizeof(*in))
2131 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2132 count = l->filelen / sizeof(*in);
2133 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2135 loadmodel->brush.data_leafs = out;
2136 loadmodel->brush.num_leafs = count;
2137 // get visleafs from the submodel data
2138 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2139 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2140 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2141 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2143 for ( i=0 ; i<count ; i++, in++, out++)
2145 for (j=0 ; j<3 ; j++)
2147 out->mins[j] = LittleShort(in->mins[j]);
2148 out->maxs[j] = LittleShort(in->maxs[j]);
2151 // FIXME: this function could really benefit from some error checking
2153 out->contents = LittleLong(in->contents);
2155 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + LittleShort(in->firstmarksurface);
2156 out->numleafsurfaces = LittleShort(in->nummarksurfaces);
2157 if (out->firstleafsurface < 0 || LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2159 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);
2160 out->firstleafsurface = NULL;
2161 out->numleafsurfaces = 0;
2164 out->clusterindex = i - 1;
2165 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2166 out->clusterindex = -1;
2168 p = LittleLong(in->visofs);
2169 // ignore visofs errors on leaf 0 (solid)
2170 if (p >= 0 && out->clusterindex >= 0)
2172 if (p >= loadmodel->brushq1.num_compressedpvs)
2173 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2175 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 for (j = 0;j < 4;j++)
2179 out->ambient_sound_level[j] = in->ambient_level[j];
2181 // FIXME: Insert caustics here
2185 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2187 dclipnode_t *in, *out;
2191 in = (dclipnode_t *)(mod_base + l->fileofs);
2192 if (l->filelen % sizeof(*in))
2193 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2194 count = l->filelen / sizeof(*in);
2195 out = (dclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2197 loadmodel->brushq1.clipnodes = out;
2198 loadmodel->brushq1.numclipnodes = count;
2200 for (i = 1; i < hullinfo->numhulls; i++)
2202 hull = &loadmodel->brushq1.hulls[i];
2203 hull->clipnodes = out;
2204 hull->firstclipnode = 0;
2205 hull->lastclipnode = count-1;
2206 hull->planes = loadmodel->brush.data_planes;
2207 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2208 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2209 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2210 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2211 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2212 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2213 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2216 for (i=0 ; i<count ; i++, out++, in++)
2218 out->planenum = LittleLong(in->planenum);
2219 out->children[0] = LittleShort(in->children[0]);
2220 out->children[1] = LittleShort(in->children[1]);
2221 if (out->children[0] >= count || out->children[1] >= count)
2222 Host_Error("Corrupt clipping hull(out of range child)\n");
2226 //Duplicate the drawing hull structure as a clipping hull
2227 static void Mod_Q1BSP_MakeHull0(void)
2234 hull = &loadmodel->brushq1.hulls[0];
2236 in = loadmodel->brush.data_nodes;
2237 out = (dclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(dclipnode_t));
2239 hull->clipnodes = out;
2240 hull->firstclipnode = 0;
2241 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2242 hull->planes = loadmodel->brush.data_planes;
2244 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2246 out->planenum = in->plane - loadmodel->brush.data_planes;
2247 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2248 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2252 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2257 in = (short *)(mod_base + l->fileofs);
2258 if (l->filelen % sizeof(*in))
2259 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2260 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2261 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2263 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2265 j = (unsigned) LittleShort(in[i]);
2266 if (j >= loadmodel->num_surfaces)
2267 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2268 loadmodel->brush.data_leafsurfaces[i] = j;
2272 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2277 in = (int *)(mod_base + l->fileofs);
2278 if (l->filelen % sizeof(*in))
2279 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2280 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2281 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2283 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2284 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2288 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2294 in = (dplane_t *)(mod_base + l->fileofs);
2295 if (l->filelen % sizeof(*in))
2296 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2298 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2299 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2301 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2303 out->normal[0] = LittleFloat(in->normal[0]);
2304 out->normal[1] = LittleFloat(in->normal[1]);
2305 out->normal[2] = LittleFloat(in->normal[2]);
2306 out->dist = LittleFloat(in->dist);
2312 static void Mod_Q1BSP_LoadMapBrushes(void)
2316 int submodel, numbrushes;
2317 qboolean firstbrush;
2318 char *text, *maptext;
2319 char mapfilename[MAX_QPATH];
2320 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2321 strlcat (mapfilename, ".map", sizeof (mapfilename));
2322 maptext = (qbyte*) FS_LoadFile(mapfilename, tempmempool, false);
2326 if (!COM_ParseToken(&data, false))
2331 if (!COM_ParseToken(&data, false))
2333 if (com_token[0] != '{')
2339 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2342 if (!COM_ParseToken(&data, false))
2344 if (com_token[0] == '}')
2345 break; // end of entity
2346 if (com_token[0] == '{')
2353 if (submodel > loadmodel->brush.numsubmodels)
2355 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2359 model = loadmodel->brush.submodels[submodel];
2366 if (!COM_ParseToken(&data, false))
2368 if (com_token[0] == '}')
2369 break; // end of brush
2370 // each brush face should be this format:
2371 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2372 // FIXME: support hl .map format
2373 for (pointnum = 0;pointnum < 3;pointnum++)
2375 COM_ParseToken(&data, false);
2376 for (componentnum = 0;componentnum < 3;componentnum++)
2378 COM_ParseToken(&data, false);
2379 point[pointnum][componentnum] = atof(com_token);
2381 COM_ParseToken(&data, false);
2383 COM_ParseToken(&data, false);
2384 strlcpy(facetexture, com_token, sizeof(facetexture));
2385 COM_ParseToken(&data, false);
2386 //scroll_s = atof(com_token);
2387 COM_ParseToken(&data, false);
2388 //scroll_t = atof(com_token);
2389 COM_ParseToken(&data, false);
2390 //rotate = atof(com_token);
2391 COM_ParseToken(&data, false);
2392 //scale_s = atof(com_token);
2393 COM_ParseToken(&data, false);
2394 //scale_t = atof(com_token);
2395 TriangleNormal(point[0], point[1], point[2], planenormal);
2396 VectorNormalizeDouble(planenormal);
2397 planedist = DotProduct(point[0], planenormal);
2398 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2408 #define MAX_PORTALPOINTS 64
2410 typedef struct portal_s
2413 mnode_t *nodes[2]; // [0] = front side of plane
2414 struct portal_s *next[2];
2416 double points[3*MAX_PORTALPOINTS];
2417 struct portal_s *chain; // all portals are linked into a list
2421 static portal_t *portalchain;
2428 static portal_t *AllocPortal(void)
2431 p = (portal_t *)Mem_Alloc(loadmodel->mempool, sizeof(portal_t));
2432 p->chain = portalchain;
2437 static void FreePortal(portal_t *p)
2442 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2444 // process only nodes (leafs already had their box calculated)
2448 // calculate children first
2449 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2450 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2452 // make combined bounding box from children
2453 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2454 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2455 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2456 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2457 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2458 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2461 static void Mod_Q1BSP_FinalizePortals(void)
2463 int i, j, numportals, numpoints;
2464 portal_t *p, *pnext;
2467 mleaf_t *leaf, *endleaf;
2469 // recalculate bounding boxes for all leafs(because qbsp is very sloppy)
2470 leaf = loadmodel->brush.data_leafs;
2471 endleaf = leaf + loadmodel->brush.num_leafs;
2472 for (;leaf < endleaf;leaf++)
2474 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
2475 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2480 if (p->numpoints >= 3)
2482 for (i = 0;i < 2;i++)
2484 leaf = (mleaf_t *)p->nodes[i];
2485 for (j = 0;j < p->numpoints;j++)
2487 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
2488 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
2489 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
2490 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
2491 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
2492 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
2499 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes);
2501 // tally up portal and point counts
2507 // note: this check must match the one below or it will usually corrupt memory
2508 // 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
2509 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 numpoints += p->numpoints * 2;
2516 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
2517 loadmodel->brush.num_portals = numportals;
2518 loadmodel->brush.data_portalpoints = (mvertex_t *)((qbyte *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
2519 loadmodel->brush.num_portalpoints = numpoints;
2520 // clear all leaf portal chains
2521 for (i = 0;i < loadmodel->brush.num_leafs;i++)
2522 loadmodel->brush.data_leafs[i].portals = NULL;
2523 // process all portals in the global portal chain, while freeing them
2524 portal = loadmodel->brush.data_portals;
2525 point = loadmodel->brush.data_portalpoints;
2532 // note: this check must match the one above or it will usually corrupt memory
2533 // 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
2534 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2536 // first make the back to front portal(forward portal)
2537 portal->points = point;
2538 portal->numpoints = p->numpoints;
2539 portal->plane.dist = p->plane.dist;
2540 VectorCopy(p->plane.normal, portal->plane.normal);
2541 portal->here = (mleaf_t *)p->nodes[1];
2542 portal->past = (mleaf_t *)p->nodes[0];
2544 for (j = 0;j < portal->numpoints;j++)
2546 VectorCopy(p->points + j*3, point->position);
2549 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
2550 PlaneClassify(&portal->plane);
2552 // link into leaf's portal chain
2553 portal->next = portal->here->portals;
2554 portal->here->portals = portal;
2556 // advance to next portal
2559 // then make the front to back portal(backward portal)
2560 portal->points = point;
2561 portal->numpoints = p->numpoints;
2562 portal->plane.dist = -p->plane.dist;
2563 VectorNegate(p->plane.normal, portal->plane.normal);
2564 portal->here = (mleaf_t *)p->nodes[0];
2565 portal->past = (mleaf_t *)p->nodes[1];
2567 for (j = portal->numpoints - 1;j >= 0;j--)
2569 VectorCopy(p->points + j*3, point->position);
2572 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
2573 PlaneClassify(&portal->plane);
2575 // link into leaf's portal chain
2576 portal->next = portal->here->portals;
2577 portal->here->portals = portal;
2579 // advance to next portal
2592 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
2595 Host_Error("AddPortalToNodes: NULL front node");
2597 Host_Error("AddPortalToNodes: NULL back node");
2598 if (p->nodes[0] || p->nodes[1])
2599 Host_Error("AddPortalToNodes: already included");
2600 // 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
2602 p->nodes[0] = front;
2603 p->next[0] = (portal_t *)front->portals;
2604 front->portals = (mportal_t *)p;
2607 p->next[1] = (portal_t *)back->portals;
2608 back->portals = (mportal_t *)p;
2613 RemovePortalFromNode
2616 static void RemovePortalFromNodes(portal_t *portal)
2620 void **portalpointer;
2622 for (i = 0;i < 2;i++)
2624 node = portal->nodes[i];
2626 portalpointer = (void **) &node->portals;
2629 t = (portal_t *)*portalpointer;
2631 Host_Error("RemovePortalFromNodes: portal not in leaf");
2635 if (portal->nodes[0] == node)
2637 *portalpointer = portal->next[0];
2638 portal->nodes[0] = NULL;
2640 else if (portal->nodes[1] == node)
2642 *portalpointer = portal->next[1];
2643 portal->nodes[1] = NULL;
2646 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
2650 if (t->nodes[0] == node)
2651 portalpointer = (void **) &t->next[0];
2652 else if (t->nodes[1] == node)
2653 portalpointer = (void **) &t->next[1];
2655 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
2660 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
2663 mnode_t *front, *back, *other_node;
2664 mplane_t clipplane, *plane;
2665 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
2666 int numfrontpoints, numbackpoints;
2667 double frontpoints[3*MAX_PORTALPOINTS], backpoints[3*MAX_PORTALPOINTS];
2669 // if a leaf, we're done
2673 plane = node->plane;
2675 front = node->children[0];
2676 back = node->children[1];
2678 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
2680 // create the new portal by generating a polygon for the node plane,
2681 // and clipping it by all of the other portals(which came from nodes above this one)
2682 nodeportal = AllocPortal();
2683 nodeportal->plane = *plane;
2685 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);
2686 nodeportal->numpoints = 4;
2687 side = 0; // shut up compiler warning
2688 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
2690 clipplane = portal->plane;
2691 if (portal->nodes[0] == portal->nodes[1])
2692 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
2693 if (portal->nodes[0] == node)
2695 else if (portal->nodes[1] == node)
2697 clipplane.dist = -clipplane.dist;
2698 VectorNegate(clipplane.normal, clipplane.normal);
2702 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
2704 for (i = 0;i < nodeportal->numpoints*3;i++)
2705 frontpoints[i] = nodeportal->points[i];
2706 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);
2707 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
2711 if (nodeportal->numpoints < 3)
2713 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
2714 nodeportal->numpoints = 0;
2716 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
2718 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
2719 nodeportal->numpoints = 0;
2722 AddPortalToNodes(nodeportal, front, back);
2724 // split the portals of this node along this node's plane and assign them to the children of this node
2725 // (migrating the portals downward through the tree)
2726 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
2728 if (portal->nodes[0] == portal->nodes[1])
2729 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
2730 if (portal->nodes[0] == node)
2732 else if (portal->nodes[1] == node)
2735 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
2736 nextportal = portal->next[side];
2737 if (!portal->numpoints)
2740 other_node = portal->nodes[!side];
2741 RemovePortalFromNodes(portal);
2743 // cut the portal into two portals, one on each side of the node plane
2744 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);
2746 if (!numfrontpoints)
2749 AddPortalToNodes(portal, back, other_node);
2751 AddPortalToNodes(portal, other_node, back);
2757 AddPortalToNodes(portal, front, other_node);
2759 AddPortalToNodes(portal, other_node, front);
2763 // the portal is split
2764 splitportal = AllocPortal();
2765 temp = splitportal->chain;
2766 *splitportal = *portal;
2767 splitportal->chain = temp;
2768 for (i = 0;i < numbackpoints*3;i++)
2769 splitportal->points[i] = backpoints[i];
2770 splitportal->numpoints = numbackpoints;
2771 for (i = 0;i < numfrontpoints*3;i++)
2772 portal->points[i] = frontpoints[i];
2773 portal->numpoints = numfrontpoints;
2777 AddPortalToNodes(portal, front, other_node);
2778 AddPortalToNodes(splitportal, back, other_node);
2782 AddPortalToNodes(portal, other_node, front);
2783 AddPortalToNodes(splitportal, other_node, back);
2787 Mod_Q1BSP_RecursiveNodePortals(front);
2788 Mod_Q1BSP_RecursiveNodePortals(back);
2791 static void Mod_Q1BSP_MakePortals(void)
2794 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes);
2795 Mod_Q1BSP_FinalizePortals();
2798 static void Mod_Q1BSP_BuildLightmapUpdateChains(mempool_t *mempool, model_t *model)
2800 int i, j, stylecounts[256], totalcount, remapstyles[256];
2801 msurface_t *surface;
2802 memset(stylecounts, 0, sizeof(stylecounts));
2803 for (i = 0;i < model->nummodelsurfaces;i++)
2805 surface = model->data_surfaces + model->firstmodelsurface + i;
2806 for (j = 0;j < MAXLIGHTMAPS;j++)
2807 stylecounts[surface->lightmapinfo->styles[j]]++;
2810 model->brushq1.light_styles = 0;
2811 for (i = 0;i < 255;i++)
2815 remapstyles[i] = model->brushq1.light_styles++;
2816 totalcount += stylecounts[i] + 1;
2821 model->brushq1.light_style = (qbyte *)Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(qbyte));
2822 model->brushq1.light_stylevalue = (int *)Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(int));
2823 model->brushq1.light_styleupdatechains = (msurface_t ***)Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(msurface_t **));
2824 model->brushq1.light_styleupdatechainsbuffer = (msurface_t **)Mem_Alloc(mempool, totalcount * sizeof(msurface_t *));
2825 model->brushq1.light_styles = 0;
2826 for (i = 0;i < 255;i++)
2828 model->brushq1.light_style[model->brushq1.light_styles++] = i;
2830 for (i = 0;i < model->brushq1.light_styles;i++)
2832 model->brushq1.light_styleupdatechains[i] = model->brushq1.light_styleupdatechainsbuffer + j;
2833 j += stylecounts[model->brushq1.light_style[i]] + 1;
2835 for (i = 0;i < model->nummodelsurfaces;i++)
2837 surface = model->data_surfaces + model->firstmodelsurface + i;
2838 for (j = 0;j < MAXLIGHTMAPS;j++)
2839 if (surface->lightmapinfo->styles[j] != 255)
2840 *model->brushq1.light_styleupdatechains[remapstyles[surface->lightmapinfo->styles[j]]]++ = surface;
2843 for (i = 0;i < model->brushq1.light_styles;i++)
2845 *model->brushq1.light_styleupdatechains[i] = NULL;
2846 model->brushq1.light_styleupdatechains[i] = model->brushq1.light_styleupdatechainsbuffer + j;
2847 j += stylecounts[model->brushq1.light_style[i]] + 1;
2851 //Returns PVS data for a given point
2852 //(note: can return NULL)
2853 static qbyte *Mod_Q1BSP_GetPVS(model_t *model, const vec3_t p)
2856 node = model->brush.data_nodes;
2858 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
2859 if (((mleaf_t *)node)->clusterindex >= 0)
2860 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
2865 static void Mod_Q1BSP_FatPVS_RecursiveBSPNode(model_t *model, const vec3_t org, vec_t radius, qbyte *pvsbuffer, int pvsbytes, mnode_t *node)
2869 float d = PlaneDiff(org, node->plane);
2871 node = node->children[0];
2872 else if (d < -radius)
2873 node = node->children[1];
2876 // go down both sides
2877 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
2878 node = node->children[1];
2881 // if this leaf is in a cluster, accumulate the pvs bits
2882 if (((mleaf_t *)node)->clusterindex >= 0)
2885 qbyte *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
2886 for (i = 0;i < pvsbytes;i++)
2887 pvsbuffer[i] |= pvs[i];
2891 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
2892 //of the given point.
2893 static int Mod_Q1BSP_FatPVS(model_t *model, const vec3_t org, vec_t radius, qbyte *pvsbuffer, int pvsbufferlength)
2895 int bytes = model->brush.num_pvsclusterbytes;
2896 bytes = min(bytes, pvsbufferlength);
2897 if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
2899 memset(pvsbuffer, 0xFF, bytes);
2902 memset(pvsbuffer, 0, bytes);
2903 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes);
2907 static void Mod_Q1BSP_RoundUpToHullSize(model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
2912 VectorSubtract(inmaxs, inmins, size);
2913 if (cmodel->brush.ismcbsp)
2916 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2917 else if (size[2] < 48) // pick the nearest of 40 or 56
2918 hull = &cmodel->brushq1.hulls[2]; // 16x16x40
2920 hull = &cmodel->brushq1.hulls[1]; // 16x16x56
2922 else if (cmodel->brush.ishlbsp)
2925 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2926 else if (size[0] <= 32)
2928 if (size[2] < 54) // pick the nearest of 36 or 72
2929 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
2931 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
2934 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
2939 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2940 else if (size[0] <= 32)
2941 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
2943 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
2945 VectorCopy(inmins, outmins);
2946 VectorAdd(inmins, hull->clip_size, outmaxs);
2949 void Mod_Q1BSP_Load(model_t *mod, void *buffer, void *bufferend)
2954 mempool_t *mainmempool;
2955 float dist, modelyawradius, modelradius, *vec;
2956 msurface_t *surface;
2957 int numshadowmeshtriangles;
2959 hullinfo_t hullinfo;
2961 mod->type = mod_brushq1;
2963 if (!memcmp (buffer, "MCBSPpad", 8))
2967 mod->brush.ismcbsp = true;
2968 mod->brush.ishlbsp = false;
2970 mod_base = (qbyte*)buffer;
2974 i = SB_ReadInt (&index);
2975 if (i != MCBSPVERSION)
2976 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i)", mod->name, i, MCBSPVERSION);
2979 hullinfo.numhulls = LittleLong(*(int*)index); index += 4;
2980 hullinfo.filehulls = hullinfo.numhulls;
2981 VectorClear (hullinfo.hullsizes[0][0]);
2982 VectorClear (hullinfo.hullsizes[0][1]);
2983 for (i = 1; i < hullinfo.numhulls; i++)
2985 hullinfo.hullsizes[i][0][0] = SB_ReadFloat (&index);
2986 hullinfo.hullsizes[i][0][1] = SB_ReadFloat (&index);
2987 hullinfo.hullsizes[i][0][2] = SB_ReadFloat (&index);
2988 hullinfo.hullsizes[i][1][0] = SB_ReadFloat (&index);
2989 hullinfo.hullsizes[i][1][1] = SB_ReadFloat (&index);
2990 hullinfo.hullsizes[i][1][2] = SB_ReadFloat (&index);
2994 _header.version = 0;
2995 for (i = 0; i < HEADER_LUMPS; i++)
2997 _header.lumps[i].fileofs = SB_ReadInt (&index);
2998 _header.lumps[i].filelen = SB_ReadInt (&index);
3005 header = (dheader_t *)buffer;
3007 i = LittleLong(header->version);
3008 if (i != BSPVERSION && i != 30)
3009 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3010 mod->brush.ishlbsp = i == 30;
3011 mod->brush.ismcbsp = false;
3013 // fill in hull info
3014 VectorClear (hullinfo.hullsizes[0][0]);
3015 VectorClear (hullinfo.hullsizes[0][1]);
3016 if (mod->brush.ishlbsp)
3018 hullinfo.numhulls = 4;
3019 hullinfo.filehulls = 4;
3020 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3021 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3022 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3023 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3024 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3025 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3029 hullinfo.numhulls = 3;
3030 hullinfo.filehulls = 4;
3031 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3032 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3033 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3034 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3038 mod_base = (qbyte*)buffer;
3039 for (i = 0; i < HEADER_LUMPS; i++)
3041 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3042 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3046 mod->soundfromcenter = true;
3047 mod->TraceBox = Mod_Q1BSP_TraceBox;
3048 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3049 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3050 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3051 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3052 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3053 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3054 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3055 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3056 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3057 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3058 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3059 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3060 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3062 if (loadmodel->isworldmodel)
3064 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
3065 Cvar_SetValue("mcbsp", mod->brush.ismcbsp);
3070 // store which lightmap format to use
3071 mod->brushq1.lightmaprgba = r_lightmaprgba.integer;
3073 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3074 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3075 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3076 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3077 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3078 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3079 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3080 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3081 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3082 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3083 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3084 // load submodels before leafs because they contain the number of vis leafs
3085 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3086 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3087 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3088 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3090 if (!mod->brushq1.lightdata)
3091 mod->brush.LightPoint = NULL;
3093 if (mod->brushq1.data_compressedpvs)
3094 Mem_Free(mod->brushq1.data_compressedpvs);
3095 mod->brushq1.data_compressedpvs = NULL;
3096 mod->brushq1.num_compressedpvs = 0;
3098 Mod_Q1BSP_MakeHull0();
3099 Mod_Q1BSP_MakePortals();
3101 mod->numframes = 2; // regular and alternate animation
3104 mainmempool = mod->mempool;
3106 Mod_Q1BSP_LoadLightList();
3108 // make a single combined shadow mesh to allow optimized shadow volume creation
3109 numshadowmeshtriangles = 0;
3110 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3112 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3113 numshadowmeshtriangles += surface->num_triangles;
3115 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3116 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3117 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));
3118 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true);
3119 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
3121 if (loadmodel->brush.numsubmodels)
3122 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
3124 if (loadmodel->isworldmodel)
3126 // clear out any stale submodels or worldmodels lying around
3127 // if we did this clear before now, an error might abort loading and
3128 // leave things in a bad state
3129 Mod_RemoveStaleWorldModels(loadmodel);
3132 // LordHavoc: to clear the fog around the original quake submodel code, I
3134 // first of all, some background info on the submodels:
3135 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3136 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3137 // now the weird for loop itself:
3138 // the loop functions in an odd way, on each iteration it sets up the
3139 // current 'mod' model (which despite the confusing code IS the model of
3140 // the number i), at the end of the loop it duplicates the model to become
3141 // the next submodel, and loops back to set up the new submodel.
3143 // LordHavoc: now the explanation of my sane way (which works identically):
3144 // set up the world model, then on each submodel copy from the world model
3145 // and set up the submodel with the respective model info.
3146 for (i = 0;i < mod->brush.numsubmodels;i++)
3148 // LordHavoc: this code was originally at the end of this loop, but
3149 // has been transformed to something more readable at the start here.
3154 // LordHavoc: only register submodels if it is the world
3155 // (prevents external bsp models from replacing world submodels with
3157 if (!loadmodel->isworldmodel)
3159 // duplicate the basic information
3160 sprintf(name, "*%i", i);
3161 mod = Mod_FindName(name);
3162 // copy the base model to this one
3164 // rename the clone back to its proper name
3165 strcpy(mod->name, name);
3166 // textures and memory belong to the main model
3167 mod->texturepool = NULL;
3168 mod->mempool = NULL;
3171 mod->brush.submodel = i;
3173 if (loadmodel->brush.submodels)
3174 loadmodel->brush.submodels[i] = mod;
3176 bm = &mod->brushq1.submodels[i];
3178 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3179 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3181 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3182 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3185 mod->firstmodelsurface = bm->firstface;
3186 mod->nummodelsurfaces = bm->numfaces;
3188 // make the model surface list (used by shadowing/lighting)
3189 mod->surfacelist = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->surfacelist));
3190 for (j = 0;j < mod->nummodelsurfaces;j++)
3191 mod->surfacelist[j] = mod->firstmodelsurface + j;
3193 // this gets altered below if sky is used
3194 mod->DrawSky = NULL;
3195 mod->Draw = R_Q1BSP_Draw;
3196 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3197 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3198 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3199 mod->DrawLight = R_Q1BSP_DrawLight;
3202 mod->brush.GetPVS = NULL;
3203 mod->brush.FatPVS = NULL;
3204 mod->brush.BoxTouchingPVS = NULL;
3205 mod->brush.BoxTouchingLeafPVS = NULL;
3206 mod->brush.BoxTouchingVisibleLeafs = NULL;
3207 mod->brush.FindBoxClusters = NULL;
3208 mod->brush.LightPoint = NULL;
3209 mod->brush.AmbientSoundLevelsForPoint = NULL;
3211 Mod_Q1BSP_BuildLightmapUpdateChains(loadmodel->mempool, mod);
3212 if (mod->nummodelsurfaces)
3214 // LordHavoc: calculate bmodel bounding box rather than trusting what it says
3215 mod->normalmins[0] = mod->normalmins[1] = mod->normalmins[2] = 1000000000.0f;
3216 mod->normalmaxs[0] = mod->normalmaxs[1] = mod->normalmaxs[2] = -1000000000.0f;
3219 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3221 // we only need to have a drawsky function if it is used(usually only on world model)
3222 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3223 mod->DrawSky = R_Q1BSP_DrawSky;
3224 // calculate bounding shapes
3225 for (k = 0, vec = (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex);k < surface->num_vertices;k++, vec += 3)
3227 if (mod->normalmins[0] > vec[0]) mod->normalmins[0] = vec[0];
3228 if (mod->normalmins[1] > vec[1]) mod->normalmins[1] = vec[1];
3229 if (mod->normalmins[2] > vec[2]) mod->normalmins[2] = vec[2];
3230 if (mod->normalmaxs[0] < vec[0]) mod->normalmaxs[0] = vec[0];
3231 if (mod->normalmaxs[1] < vec[1]) mod->normalmaxs[1] = vec[1];
3232 if (mod->normalmaxs[2] < vec[2]) mod->normalmaxs[2] = vec[2];
3233 dist = vec[0]*vec[0]+vec[1]*vec[1];
3234 if (modelyawradius < dist)
3235 modelyawradius = dist;
3236 dist += vec[2]*vec[2];
3237 if (modelradius < dist)
3241 modelyawradius = sqrt(modelyawradius);
3242 modelradius = sqrt(modelradius);
3243 mod->yawmins[0] = mod->yawmins[1] = - (mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius);
3244 mod->yawmins[2] = mod->normalmins[2];
3245 mod->yawmaxs[2] = mod->normalmaxs[2];
3246 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3247 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3248 mod->radius = modelradius;
3249 mod->radius2 = modelradius * modelradius;
3253 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3254 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3256 //mod->brushq1.num_visleafs = bm->visleafs;
3259 Mod_Q1BSP_LoadMapBrushes();
3261 //Mod_Q1BSP_ProcessLightList();
3263 if (developer.integer)
3264 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);
3267 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3271 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3278 in = (void *)(mod_base + l->fileofs);
3279 if (l->filelen % sizeof(*in))
3280 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3281 count = l->filelen / sizeof(*in);
3282 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3285 loadmodel->num = count;
3287 for (i = 0;i < count;i++, in++, out++)
3293 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3300 in = (void *)(mod_base + l->fileofs);
3301 if (l->filelen % sizeof(*in))
3302 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3303 count = l->filelen / sizeof(*in);
3304 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3307 loadmodel->num = count;
3309 for (i = 0;i < count;i++, in++, out++)
3315 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3322 in = (void *)(mod_base + l->fileofs);
3323 if (l->filelen % sizeof(*in))
3324 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3325 count = l->filelen / sizeof(*in);
3326 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3329 loadmodel->num = count;
3331 for (i = 0;i < count;i++, in++, out++)
3337 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3344 in = (void *)(mod_base + l->fileofs);
3345 if (l->filelen % sizeof(*in))
3346 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3347 count = l->filelen / sizeof(*in);
3348 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3351 loadmodel->num = count;
3353 for (i = 0;i < count;i++, in++, out++)
3359 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3366 in = (void *)(mod_base + l->fileofs);
3367 if (l->filelen % sizeof(*in))
3368 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3369 count = l->filelen / sizeof(*in);
3370 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3373 loadmodel->num = count;
3375 for (i = 0;i < count;i++, in++, out++)
3381 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3388 in = (void *)(mod_base + l->fileofs);
3389 if (l->filelen % sizeof(*in))
3390 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3391 count = l->filelen / sizeof(*in);
3392 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3395 loadmodel->num = count;
3397 for (i = 0;i < count;i++, in++, out++)
3403 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3410 in = (void *)(mod_base + l->fileofs);
3411 if (l->filelen % sizeof(*in))
3412 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3413 count = l->filelen / sizeof(*in);
3414 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3417 loadmodel->num = count;
3419 for (i = 0;i < count;i++, in++, out++)
3425 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3432 in = (void *)(mod_base + l->fileofs);
3433 if (l->filelen % sizeof(*in))
3434 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3435 count = l->filelen / sizeof(*in);
3436 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3439 loadmodel->num = count;
3441 for (i = 0;i < count;i++, in++, out++)
3447 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3454 in = (void *)(mod_base + l->fileofs);
3455 if (l->filelen % sizeof(*in))
3456 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3457 count = l->filelen / sizeof(*in);
3458 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3461 loadmodel->num = count;
3463 for (i = 0;i < count;i++, in++, out++)
3469 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3476 in = (void *)(mod_base + l->fileofs);
3477 if (l->filelen % sizeof(*in))
3478 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3479 count = l->filelen / sizeof(*in);
3480 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3483 loadmodel->num = count;
3485 for (i = 0;i < count;i++, in++, out++)
3491 static void Mod_Q2BSP_LoadEdges(lump_t *l)
3498 in = (void *)(mod_base + l->fileofs);
3499 if (l->filelen % sizeof(*in))
3500 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
3501 count = l->filelen / sizeof(*in);
3502 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3505 loadmodel->num = count;
3507 for (i = 0;i < count;i++, in++, out++)
3513 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
3520 in = (void *)(mod_base + l->fileofs);
3521 if (l->filelen % sizeof(*in))
3522 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
3523 count = l->filelen / sizeof(*in);
3524 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3527 loadmodel->num = count;
3529 for (i = 0;i < count;i++, in++, out++)
3535 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
3542 in = (void *)(mod_base + l->fileofs);
3543 if (l->filelen % sizeof(*in))
3544 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
3545 count = l->filelen / sizeof(*in);
3546 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3549 loadmodel->num = count;
3551 for (i = 0;i < count;i++, in++, out++)
3557 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
3564 in = (void *)(mod_base + l->fileofs);
3565 if (l->filelen % sizeof(*in))
3566 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
3567 count = l->filelen / sizeof(*in);
3568 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3571 loadmodel->num = count;
3573 for (i = 0;i < count;i++, in++, out++)
3579 static void Mod_Q2BSP_LoadAreas(lump_t *l)
3586 in = (void *)(mod_base + l->fileofs);
3587 if (l->filelen % sizeof(*in))
3588 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
3589 count = l->filelen / sizeof(*in);
3590 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3593 loadmodel->num = count;
3595 for (i = 0;i < count;i++, in++, out++)
3601 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
3608 in = (void *)(mod_base + l->fileofs);
3609 if (l->filelen % sizeof(*in))
3610 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
3611 count = l->filelen / sizeof(*in);
3612 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3615 loadmodel->num = count;
3617 for (i = 0;i < count;i++, in++, out++)
3623 static void Mod_Q2BSP_LoadModels(lump_t *l)
3630 in = (void *)(mod_base + l->fileofs);
3631 if (l->filelen % sizeof(*in))
3632 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
3633 count = l->filelen / sizeof(*in);
3634 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3637 loadmodel->num = count;
3639 for (i = 0;i < count;i++, in++, out++)
3645 void static Mod_Q2BSP_Load(model_t *mod, void *buffer, void *bufferend)
3648 q2dheader_t *header;
3650 Host_Error("Mod_Q2BSP_Load: not yet implemented\n");
3652 mod->type = mod_brushq2;
3654 header = (q2dheader_t *)buffer;
3656 i = LittleLong(header->version);
3657 if (i != Q2BSPVERSION)
3658 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
3659 mod->brush.ishlbsp = false;
3660 mod->brush.ismcbsp = false;
3661 if (loadmodel->isworldmodel)
3663 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
3664 Cvar_SetValue("mcbsp", mod->brush.ismcbsp);
3667 mod_base = (qbyte *)header;
3669 // swap all the lumps
3670 for (i = 0;i < (int) sizeof(*header) / 4;i++)
3671 ((int *)header)[i] = LittleLong(((int *)header)[i]);
3673 // store which lightmap format to use
3674 mod->brushq1.lightmaprgba = r_lightmaprgba.integer;
3676 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
3677 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
3678 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
3679 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
3680 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
3681 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
3682 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
3683 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
3684 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
3685 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
3686 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
3687 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
3688 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
3689 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
3690 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
3691 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
3692 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
3693 // LordHavoc: must go last because this makes the submodels
3694 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
3697 static int Mod_Q3BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents);
3698 static int Mod_Q3BSP_NativeContentsFromSuperContents(model_t *model, int supercontents);
3700 static void Mod_Q3BSP_LoadEntities(lump_t *l)
3703 char key[128], value[4096];
3705 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
3706 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
3707 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
3710 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen);
3711 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
3712 data = loadmodel->brush.entities;
3713 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
3714 if (data && COM_ParseToken(&data, false) && com_token[0] == '{')
3718 if (!COM_ParseToken(&data, false))
3720 if (com_token[0] == '}')
3721 break; // end of worldspawn
3722 if (com_token[0] == '_')
3723 strcpy(key, com_token + 1);
3725 strcpy(key, com_token);
3726 while (key[strlen(key)-1] == ' ') // remove trailing spaces
3727 key[strlen(key)-1] = 0;
3728 if (!COM_ParseToken(&data, false))
3730 strcpy(value, com_token);
3731 if (!strcmp("gridsize", key))
3733 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
3734 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
3740 static void Mod_Q3BSP_LoadTextures(lump_t *l)
3749 int flags, flags2, numparameters, passnumber;
3750 char shadername[Q3PATHLENGTH];
3751 char sky[Q3PATHLENGTH];
3752 char firstpasstexturename[Q3PATHLENGTH];
3753 char parameter[4][Q3PATHLENGTH];
3755 in = (q3dtexture_t *)(mod_base + l->fileofs);
3756 if (l->filelen % sizeof(*in))
3757 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
3758 count = l->filelen / sizeof(*in);
3759 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3761 loadmodel->data_textures = out;
3762 loadmodel->num_textures = count;
3764 for (i = 0;i < count;i++, in++, out++)
3766 strlcpy (out->name, in->name, sizeof (out->name));
3767 out->surfaceflags = LittleLong(in->surfaceflags);
3768 out->supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in->contents));
3769 out->surfaceparms = -1;
3772 // do a quick parse of shader files to get surfaceparms
3773 if ((search = FS_Search("scripts/*.shader", true, false)))
3775 for (i = 0;i < search->numfilenames;i++)
3777 if ((f = (char *)FS_LoadFile(search->filenames[i], tempmempool, false)))
3780 while (COM_ParseToken(&text, false))
3782 strlcpy (shadername, com_token, sizeof (shadername));
3787 firstpasstexturename[0] = 0;
3788 if (COM_ParseToken(&text, false) && !strcasecmp(com_token, "{"))
3790 while (COM_ParseToken(&text, false))
3792 if (!strcasecmp(com_token, "}"))
3794 else if (!strcasecmp(com_token, "{"))
3796 while (COM_ParseToken(&text, false))
3798 if (!strcasecmp(com_token, "}"))
3800 if (!strcasecmp(com_token, "\n"))
3803 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
3807 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
3808 numparameters = j + 1;
3810 if (!COM_ParseToken(&text, true))
3813 if (developer.integer >= 2)
3815 Con_Printf("%s %i: ", shadername, passnumber);
3816 for (j = 0;j < numparameters;j++)
3817 Con_Printf(" %s", parameter[j]);
3820 if (passnumber == 0 && numparameters >= 1)
3822 if (!strcasecmp(parameter[0], "blendfunc") && (flags & Q3SURFACEPARM_TRANS))
3824 if (numparameters == 2 && !strcasecmp(parameter[1], "add"))
3825 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3826 else if (numparameters == 3 && !strcasecmp(parameter[1], "gl_one") && !strcasecmp(parameter[2], "gl_one"))
3827 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3828 else if (numparameters == 3 && !strcasecmp(parameter[1], "gl_src_alpha") && !strcasecmp(parameter[2], "gl_one"))
3829 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3831 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
3832 strlcpy(firstpasstexturename, parameter[1], sizeof(firstpasstexturename));
3833 else if (numparameters >= 3 && !strcasecmp(parameter[0], "animmap"))
3834 strlcpy(firstpasstexturename, parameter[2], sizeof(firstpasstexturename));
3835 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
3836 flags2 |= Q3TEXTUREFLAG_ALPHATEST;
3838 // break out a level if it was }
3839 if (!strcasecmp(com_token, "}"))
3846 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
3850 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
3851 numparameters = j + 1;
3853 if (!COM_ParseToken(&text, true))
3856 if (i == 0 && !strcasecmp(com_token, "}"))
3858 if (developer.integer >= 2)
3860 Con_Printf("%s: ", shadername);
3861 for (j = 0;j < numparameters;j++)
3862 Con_Printf(" %s", parameter[j]);
3865 if (numparameters < 1)
3867 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
3869 if (!strcasecmp(parameter[1], "alphashadow"))
3870 flags |= Q3SURFACEPARM_ALPHASHADOW;
3871 else if (!strcasecmp(parameter[1], "areaportal"))
3872 flags |= Q3SURFACEPARM_AREAPORTAL;
3873 else if (!strcasecmp(parameter[1], "clusterportal"))
3874 flags |= Q3SURFACEPARM_CLUSTERPORTAL;
3875 else if (!strcasecmp(parameter[1], "detail"))
3876 flags |= Q3SURFACEPARM_DETAIL;
3877 else if (!strcasecmp(parameter[1], "donotenter"))
3878 flags |= Q3SURFACEPARM_DONOTENTER;
3879 else if (!strcasecmp(parameter[1], "fog"))
3880 flags |= Q3SURFACEPARM_FOG;
3881 else if (!strcasecmp(parameter[1], "lava"))
3882 flags |= Q3SURFACEPARM_LAVA;
3883 else if (!strcasecmp(parameter[1], "lightfilter"))
3884 flags |= Q3SURFACEPARM_LIGHTFILTER;
3885 else if (!strcasecmp(parameter[1], "metalsteps"))
3886 flags |= Q3SURFACEPARM_METALSTEPS;
3887 else if (!strcasecmp(parameter[1], "nodamage"))
3888 flags |= Q3SURFACEPARM_NODAMAGE;
3889 else if (!strcasecmp(parameter[1], "nodlight"))
3890 flags |= Q3SURFACEPARM_NODLIGHT;
3891 else if (!strcasecmp(parameter[1], "nodraw"))
3892 flags |= Q3SURFACEPARM_NODRAW;
3893 else if (!strcasecmp(parameter[1], "nodrop"))
3894 flags |= Q3SURFACEPARM_NODROP;
3895 else if (!strcasecmp(parameter[1], "noimpact"))
3896 flags |= Q3SURFACEPARM_NOIMPACT;
3897 else if (!strcasecmp(parameter[1], "nolightmap"))
3898 flags |= Q3SURFACEPARM_NOLIGHTMAP;
3899 else if (!strcasecmp(parameter[1], "nomarks"))
3900 flags |= Q3SURFACEPARM_NOMARKS;
3901 else if (!strcasecmp(parameter[1], "nomipmaps"))
3902 flags |= Q3SURFACEPARM_NOMIPMAPS;
3903 else if (!strcasecmp(parameter[1], "nonsolid"))
3904 flags |= Q3SURFACEPARM_NONSOLID;
3905 else if (!strcasecmp(parameter[1], "origin"))
3906 flags |= Q3SURFACEPARM_ORIGIN;
3907 else if (!strcasecmp(parameter[1], "playerclip"))
3908 flags |= Q3SURFACEPARM_PLAYERCLIP;
3909 else if (!strcasecmp(parameter[1], "sky"))
3910 flags |= Q3SURFACEPARM_SKY;
3911 else if (!strcasecmp(parameter[1], "slick"))
3912 flags |= Q3SURFACEPARM_SLICK;
3913 else if (!strcasecmp(parameter[1], "slime"))
3914 flags |= Q3SURFACEPARM_SLIME;
3915 else if (!strcasecmp(parameter[1], "structural"))
3916 flags |= Q3SURFACEPARM_STRUCTURAL;
3917 else if (!strcasecmp(parameter[1], "trans"))
3918 flags |= Q3SURFACEPARM_TRANS;
3919 else if (!strcasecmp(parameter[1], "water"))
3920 flags |= Q3SURFACEPARM_WATER;
3921 else if (!strcasecmp(parameter[1], "pointlight"))
3922 flags |= Q3SURFACEPARM_POINTLIGHT;
3924 Con_Printf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[i], parameter[1]);
3926 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
3927 strlcpy(sky, parameter[1], sizeof(sky));
3928 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
3930 if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
3931 strlcpy(sky, parameter[1], sizeof(sky));
3933 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
3935 if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
3936 flags2 |= Q3TEXTUREFLAG_TWOSIDED;
3938 else if (!strcasecmp(parameter[0], "nomipmaps"))
3939 flags2 |= Q3TEXTUREFLAG_NOMIPMAPS;
3940 else if (!strcasecmp(parameter[0], "nopicmip"))
3941 flags2 |= Q3TEXTUREFLAG_NOPICMIP;
3942 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
3944 if (!strcasecmp(parameter[1], "autosprite") && numparameters == 2)
3945 flags2 |= Q3TEXTUREFLAG_AUTOSPRITE;
3946 if (!strcasecmp(parameter[1], "autosprite2") && numparameters == 2)
3947 flags2 |= Q3TEXTUREFLAG_AUTOSPRITE2;
3950 // add shader to list (shadername and flags)
3951 // actually here we just poke into the texture settings
3952 for (j = 0, out = loadmodel->data_textures;j < loadmodel->num_textures;j++, out++)
3954 if (!strcasecmp(out->name, shadername))
3956 out->surfaceparms = flags;
3957 out->textureflags = flags2;
3958 out->basematerialflags = 0;
3959 if (out->surfaceparms & Q3SURFACEPARM_NODRAW)
3960 out->basematerialflags |= MATERIALFLAG_NODRAW;
3961 else if (out->surfaceparms & Q3SURFACEPARM_SKY)
3962 out->basematerialflags |= MATERIALFLAG_SKY;
3963 else if (out->surfaceparms & Q3SURFACEPARM_LAVA)
3964 out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_FULLBRIGHT;
3965 else if (out->surfaceparms & Q3SURFACEPARM_SLIME)
3966 out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_WATERALPHA;
3967 else if (out->surfaceparms & Q3SURFACEPARM_WATER)
3968 out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_WATERALPHA;
3970 out->basematerialflags |= MATERIALFLAG_WALL;
3971 if (out->textureflags & Q3TEXTUREFLAG_ALPHATEST)
3973 // FIXME: support alpha test?
3974 out->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
3976 else if (out->surfaceparms & Q3SURFACEPARM_TRANS)
3978 if (out->textureflags & Q3TEXTUREFLAG_ADDITIVE)
3979 out->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_TRANSPARENT;
3981 out->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
3983 strlcpy(out->firstpasstexturename, firstpasstexturename, sizeof(out->firstpasstexturename));
3984 if ((flags & Q3SURFACEPARM_SKY) && sky[0])
3986 // quake3 seems to append a _ to the skybox name, so this must do so as well
3987 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", sky);
3994 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[i], com_token);
4005 for (j = 0, out = loadmodel->data_textures;j < loadmodel->num_textures;j++, out++)
4007 if (out->surfaceparms == -1)
4010 Con_DPrintf("%s: No shader found for texture \"%s\"\n", loadmodel->name, out->name);
4011 out->surfaceparms = 0;
4012 if (out->surfaceflags & Q3SURFACEFLAG_NODRAW)
4013 out->basematerialflags |= MATERIALFLAG_NODRAW;
4014 else if (out->surfaceflags & Q3SURFACEFLAG_SKY)
4015 out->basematerialflags |= MATERIALFLAG_SKY;
4017 out->basematerialflags |= MATERIALFLAG_WALL;
4018 // these are defaults
4019 //if (!strncmp(out->name, "textures/skies/", 15))
4020 // out->surfaceparms |= Q3SURFACEPARM_SKY;
4021 //if (!strcmp(out->name, "caulk") || !strcmp(out->name, "common/caulk") || !strcmp(out->name, "textures/common/caulk")
4022 // || !strcmp(out->name, "nodraw") || !strcmp(out->name, "common/nodraw") || !strcmp(out->name, "textures/common/nodraw"))
4023 // out->surfaceparms |= Q3SURFACEPARM_NODRAW;
4024 //if (R_TextureHasAlpha(out->skin.base))
4025 // out->surfaceparms |= Q3SURFACEPARM_TRANS;
4027 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))
4028 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))
4029 if (cls.state != ca_dedicated)
4030 Con_Printf("%s: texture loading for shader \"%s\" failed (first layer \"%s\" not found either)\n", loadmodel->name, out->name, out->firstpasstexturename);
4032 out->currentframe = out;
4035 Con_DPrintf("%s: %i textures missing shaders\n", loadmodel->name, c);
4038 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4044 in = (q3dplane_t *)(mod_base + l->fileofs);
4045 if (l->filelen % sizeof(*in))
4046 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4047 count = l->filelen / sizeof(*in);
4048 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4050 loadmodel->brush.data_planes = out;
4051 loadmodel->brush.num_planes = count;
4053 for (i = 0;i < count;i++, in++, out++)
4055 out->normal[0] = LittleFloat(in->normal[0]);
4056 out->normal[1] = LittleFloat(in->normal[1]);
4057 out->normal[2] = LittleFloat(in->normal[2]);
4058 out->dist = LittleFloat(in->dist);
4063 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4066 q3mbrushside_t *out;
4069 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4070 if (l->filelen % sizeof(*in))
4071 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4072 count = l->filelen / sizeof(*in);
4073 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4075 loadmodel->brush.data_brushsides = out;
4076 loadmodel->brush.num_brushsides = count;
4078 for (i = 0;i < count;i++, in++, out++)
4080 n = LittleLong(in->planeindex);
4081 if (n < 0 || n >= loadmodel->brush.num_planes)
4082 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)\n", n, loadmodel->brush.num_planes);
4083 out->plane = loadmodel->brush.data_planes + n;
4084 n = LittleLong(in->textureindex);
4085 if (n < 0 || n >= loadmodel->num_textures)
4086 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)\n", n, loadmodel->num_textures);
4087 out->texture = loadmodel->data_textures + n;
4091 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4095 int i, j, n, c, count, maxplanes;
4098 in = (q3dbrush_t *)(mod_base + l->fileofs);
4099 if (l->filelen % sizeof(*in))
4100 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4101 count = l->filelen / sizeof(*in);
4102 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4104 loadmodel->brush.data_brushes = out;
4105 loadmodel->brush.num_brushes = count;
4110 for (i = 0;i < count;i++, in++, out++)
4112 n = LittleLong(in->firstbrushside);
4113 c = LittleLong(in->numbrushsides);
4114 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4115 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)\n", n, n + c, loadmodel->brush.num_brushsides);
4116 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4117 out->numbrushsides = c;
4118 n = LittleLong(in->textureindex);
4119 if (n < 0 || n >= loadmodel->num_textures)
4120 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)\n", n, loadmodel->num_textures);
4121 out->texture = loadmodel->data_textures + n;
4123 // make a list of mplane_t structs to construct a colbrush from
4124 if (maxplanes < out->numbrushsides)
4126 maxplanes = out->numbrushsides;
4129 planes = (mplane_t *)Mem_Alloc(tempmempool, sizeof(mplane_t) * maxplanes);
4131 for (j = 0;j < out->numbrushsides;j++)
4133 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4134 planes[j].dist = out->firstbrushside[j].plane->dist;
4136 // make the colbrush from the planes
4137 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents);
4143 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4149 in = (q3deffect_t *)(mod_base + l->fileofs);
4150 if (l->filelen % sizeof(*in))
4151 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4152 count = l->filelen / sizeof(*in);
4153 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4155 loadmodel->brushq3.data_effects = out;
4156 loadmodel->brushq3.num_effects = count;
4158 for (i = 0;i < count;i++, in++, out++)
4160 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4161 n = LittleLong(in->brushindex);
4162 if (n >= loadmodel->brush.num_brushes)
4164 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4167 out->brushindex = n;
4168 out->unknown = LittleLong(in->unknown);
4172 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4177 in = (q3dvertex_t *)(mod_base + l->fileofs);
4178 if (l->filelen % sizeof(*in))
4179 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4180 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4181 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 2 + 2 + 4)));
4182 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_vertex3f + count * 3;
4183 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4184 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4186 for (i = 0;i < count;i++, in++)
4188 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4189 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4190 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4191 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4192 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4193 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4194 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4195 // svector/tvector are calculated later in face loading
4196 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4197 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4198 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4199 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4203 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4209 in = (int *)(mod_base + l->fileofs);
4210 if (l->filelen % sizeof(int[3]))
4211 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4212 count = l->filelen / sizeof(*in);
4213 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4215 loadmodel->brushq3.num_triangles = count / 3;
4216 loadmodel->brushq3.data_element3i = out;
4218 for (i = 0;i < count;i++, in++, out++)
4220 *out = LittleLong(*in);
4221 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4223 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4229 static void Mod_Q3BSP_LoadLightmaps(lump_t *l)
4237 in = (q3dlightmap_t *)(mod_base + l->fileofs);
4238 if (l->filelen % sizeof(*in))
4239 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4240 count = l->filelen / sizeof(*in);
4241 out = (rtexture_t **)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4243 loadmodel->brushq3.data_lightmaps = out;
4244 loadmodel->brushq3.num_lightmaps = count;
4246 for (i = 0;i < count;i++, in++, out++)
4247 *out = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", i), 128, 128, in->rgb, TEXTYPE_RGB, TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
4250 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4252 q3dface_t *in, *oldin;
4253 msurface_t *out, *oldout;
4254 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;
4255 //int *originalelement3i;
4256 //int *originalneighbor3i;
4257 float *originalvertex3f;
4258 //float *originalsvector3f;
4259 //float *originaltvector3f;
4260 //float *originalnormal3f;
4261 float *originalcolor4f;
4262 float *originaltexcoordtexture2f;
4263 float *originaltexcoordlightmap2f;
4265 surfmesh_t *mesh, *tempmeshlist[1024];
4267 in = (q3dface_t *)(mod_base + l->fileofs);
4268 if (l->filelen % sizeof(*in))
4269 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4270 count = l->filelen / sizeof(*in);
4271 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4273 loadmodel->data_surfaces = out;
4274 loadmodel->num_surfaces = count;
4277 for (meshnum = 0;i < count;meshnum++)
4284 for (;i < count;i++, in++, out++)
4286 // check face type first
4287 type = LittleLong(in->type);
4288 if (type != Q3FACETYPE_POLYGON
4289 && type != Q3FACETYPE_PATCH
4290 && type != Q3FACETYPE_MESH
4291 && type != Q3FACETYPE_FLARE)
4293 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4297 n = LittleLong(in->textureindex);
4298 if (n < 0 || n >= loadmodel->num_textures)
4300 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4303 out->texture = loadmodel->data_textures + n;
4304 n = LittleLong(in->effectindex);
4305 if (n < -1 || n >= loadmodel->brushq3.num_effects)
4307 if (developer.integer >= 2)
4308 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4314 out->effect = loadmodel->brushq3.data_effects + n;
4315 n = LittleLong(in->lightmapindex);
4316 if (n >= loadmodel->brushq3.num_lightmaps)
4318 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_lightmaps);
4324 out->lightmaptexture = NULL;
4326 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n];
4328 firstvertex = LittleLong(in->firstvertex);
4329 numvertices = LittleLong(in->numvertices);
4330 firstelement = LittleLong(in->firstelement);
4331 numtriangles = LittleLong(in->numelements) / 3;
4332 if (numtriangles * 3 != LittleLong(in->numelements))
4334 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));
4337 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4339 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);
4342 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4344 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);
4349 case Q3FACETYPE_POLYGON:
4350 case Q3FACETYPE_MESH:
4351 // no processing necessary
4353 case Q3FACETYPE_PATCH:
4354 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4355 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4356 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))
4358 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
4361 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4362 // convert patch to Q3FACETYPE_MESH
4363 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4364 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4365 // bound to user settings
4366 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4367 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4368 // bound to sanity settings
4369 xtess = bound(1, xtess, 1024);
4370 ytess = bound(1, ytess, 1024);
4371 // bound to user limit on vertices
4372 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_maxvertices.integer, 262144))
4379 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4380 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4381 numvertices = finalwidth * finalheight;
4382 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4384 case Q3FACETYPE_FLARE:
4385 if (developer.integer >= 2)
4386 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
4390 out->num_vertices = numvertices;
4391 out->num_triangles = numtriangles;
4392 if (meshvertices + out->num_vertices > 65536)
4394 meshvertices += out->num_vertices;
4395 meshtriangles += out->num_triangles;
4401 mesh = tempmeshlist[meshnum] = Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
4404 for (;i < count && meshvertices + out->num_vertices <= mesh->num_vertices;i++, in++, out++)
4406 if (out->num_vertices < 3 || out->num_triangles < 1)
4409 type = LittleLong(in->type);
4410 firstvertex = LittleLong(in->firstvertex);
4411 firstelement = LittleLong(in->firstelement);
4412 out->groupmesh = mesh;
4413 out->num_firstvertex = meshvertices;
4414 out->num_firsttriangle = meshtriangles;
4417 case Q3FACETYPE_POLYGON:
4418 case Q3FACETYPE_MESH:
4419 // no processing necessary
4420 for (j = 0;j < out->num_vertices;j++)
4422 (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
4423 (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
4424 (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
4425 (out->groupmesh->data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
4426 (out->groupmesh->data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
4427 (out->groupmesh->data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
4428 (out->groupmesh->data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
4429 (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
4430 (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
4431 (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
4432 (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
4434 for (j = 0;j < out->num_triangles*3;j++)
4435 (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
4437 case Q3FACETYPE_PATCH:
4438 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4439 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4440 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4441 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
4442 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
4443 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
4444 // convert patch to Q3FACETYPE_MESH
4445 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4446 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4447 // bound to user settings
4448 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4449 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4450 // bound to sanity settings
4451 xtess = bound(1, xtess, 1024);
4452 ytess = bound(1, ytess, 1024);
4453 // bound to user limit on vertices
4454 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_maxvertices.integer, 262144))
4461 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4462 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4463 finalvertices = finalwidth * finalheight;
4464 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4465 type = Q3FACETYPE_MESH;
4466 // generate geometry
4467 // (note: normals are skipped because they get recalculated)
4468 Q3PatchTesselateFloat(3, sizeof(float[3]), (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
4469 Q3PatchTesselateFloat(2, sizeof(float[2]), (out->groupmesh->data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
4470 Q3PatchTesselateFloat(2, sizeof(float[2]), (out->groupmesh->data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
4471 Q3PatchTesselateFloat(4, sizeof(float[4]), (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
4472 Q3PatchTriangleElements((out->groupmesh->data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
4473 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);
4474 if (developer.integer >= 2)
4476 if (out->num_triangles < finaltriangles)
4477 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);
4479 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);
4481 // q3map does not put in collision brushes for curves... ugh
4482 // build the lower quality collision geometry
4483 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4484 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4485 // bound to user settings
4486 xtess = bound(r_subdivisions_collision_mintess.integer, xtess, r_subdivisions_collision_maxtess.integer);
4487 ytess = bound(r_subdivisions_collision_mintess.integer, ytess, r_subdivisions_collision_maxtess.integer);
4488 // bound to sanity settings
4489 xtess = bound(1, xtess, 1024);
4490 ytess = bound(1, ytess, 1024);
4491 // bound to user limit on vertices
4492 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_collision_maxvertices.integer, 262144))
4499 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4500 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4501 finalvertices = finalwidth * finalheight;
4502 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4504 out->data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
4505 out->data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
4506 out->num_collisionvertices = finalvertices;
4507 out->num_collisiontriangles = finaltriangles;
4508 Q3PatchTesselateFloat(3, sizeof(float[3]), out->data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
4509 Q3PatchTriangleElements(out->data_collisionelement3i, finalwidth, finalheight, 0);
4511 //Mod_SnapVertices(3, out->num_vertices, (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), 0.25);
4512 Mod_SnapVertices(3, out->num_collisionvertices, out->data_collisionvertex3f, 1);
4514 oldnumtriangles = out->num_triangles;
4515 oldnumtriangles2 = out->num_collisiontriangles;
4516 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->num_collisiontriangles, out->data_collisionelement3i, out->data_collisionelement3i, out->data_collisionvertex3f);
4517 if (developer.integer)
4518 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);
4523 meshvertices += out->num_vertices;
4524 meshtriangles += out->num_triangles;
4525 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
4526 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)
4528 if (invalidelements)
4530 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);
4531 for (j = 0;j < out->num_triangles * 3;j++)
4533 Con_Printf(" %i", (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
4534 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)
4535 (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
4539 // for per pixel lighting
4540 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);
4541 // calculate a bounding box
4542 VectorClear(out->mins);
4543 VectorClear(out->maxs);
4544 if (out->num_vertices)
4546 VectorCopy((out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), out->mins);
4547 VectorCopy((out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), out->maxs);
4548 for (j = 1, v = (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
4550 out->mins[0] = min(out->mins[0], v[0]);
4551 out->maxs[0] = max(out->maxs[0], v[0]);
4552 out->mins[1] = min(out->mins[1], v[1]);
4553 out->maxs[1] = max(out->maxs[1], v[1]);
4554 out->mins[2] = min(out->mins[2], v[2]);
4555 out->maxs[2] = max(out->maxs[2], v[2]);
4557 out->mins[0] -= 1.0f;
4558 out->mins[1] -= 1.0f;
4559 out->mins[2] -= 1.0f;
4560 out->maxs[0] += 1.0f;
4561 out->maxs[1] += 1.0f;
4562 out->maxs[2] += 1.0f;
4564 // set lightmap styles for consistency with q1bsp
4565 //out->lightmapinfo->styles[0] = 0;
4566 //out->lightmapinfo->styles[1] = 255;
4567 //out->lightmapinfo->styles[2] = 255;
4568 //out->lightmapinfo->styles[3] = 255;
4572 // now store the completed list of meshes
4573 loadmodel->nummeshes = meshnum;
4574 if (loadmodel->nummeshes)
4576 loadmodel->meshlist = (surfmesh_t **)Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *) * loadmodel->nummeshes);
4577 memcpy(loadmodel->meshlist, tempmeshlist, sizeof(surfmesh_t *) * loadmodel->nummeshes);
4580 // free the no longer needed vertex data
4581 loadmodel->brushq3.num_vertices = 0;
4582 Mem_Free(loadmodel->brushq3.data_vertex3f);
4583 loadmodel->brushq3.data_vertex3f = NULL;
4584 loadmodel->brushq3.data_texcoordtexture2f = NULL;
4585 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
4586 loadmodel->brushq3.data_color4f = NULL;
4587 // free the no longer needed triangle data
4588 loadmodel->brushq3.num_triangles = 0;
4589 Mem_Free(loadmodel->brushq3.data_element3i);
4590 loadmodel->brushq3.data_element3i = NULL;
4593 static void Mod_Q3BSP_LoadModels(lump_t *l)
4597 int i, j, n, c, count;
4599 in = (q3dmodel_t *)(mod_base + l->fileofs);
4600 if (l->filelen % sizeof(*in))
4601 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
4602 count = l->filelen / sizeof(*in);
4603 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4605 loadmodel->brushq3.data_models = out;
4606 loadmodel->brushq3.num_models = count;
4608 for (i = 0;i < count;i++, in++, out++)
4610 for (j = 0;j < 3;j++)
4612 out->mins[j] = LittleFloat(in->mins[j]);
4613 out->maxs[j] = LittleFloat(in->maxs[j]);
4615 n = LittleLong(in->firstface);
4616 c = LittleLong(in->numfaces);
4617 if (n < 0 || n + c > loadmodel->num_surfaces)
4618 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)\n", n, n + c, loadmodel->num_surfaces);
4621 n = LittleLong(in->firstbrush);
4622 c = LittleLong(in->numbrushes);
4623 if (n < 0 || n + c > loadmodel->brush.num_brushes)
4624 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)\n", n, n + c, loadmodel->brush.num_brushes);
4625 out->firstbrush = n;
4626 out->numbrushes = c;
4630 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
4636 in = (int *)(mod_base + l->fileofs);
4637 if (l->filelen % sizeof(*in))
4638 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4639 count = l->filelen / sizeof(*in);
4640 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4642 loadmodel->brush.data_leafbrushes = out;
4643 loadmodel->brush.num_leafbrushes = count;
4645 for (i = 0;i < count;i++, in++, out++)
4647 n = LittleLong(*in);
4648 if (n < 0 || n >= loadmodel->brush.num_brushes)
4649 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)\n", n, loadmodel->brush.num_brushes);
4654 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
4660 in = (int *)(mod_base + l->fileofs);
4661 if (l->filelen % sizeof(*in))
4662 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4663 count = l->filelen / sizeof(*in);
4664 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4666 loadmodel->brush.data_leafsurfaces = out;
4667 loadmodel->brush.num_leafsurfaces = count;
4669 for (i = 0;i < count;i++, in++, out++)
4671 n = LittleLong(*in);
4672 if (n < 0 || n >= loadmodel->num_surfaces)
4673 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)\n", n, loadmodel->num_surfaces);
4678 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
4682 int i, j, n, c, count;
4684 in = (q3dleaf_t *)(mod_base + l->fileofs);
4685 if (l->filelen % sizeof(*in))
4686 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4687 count = l->filelen / sizeof(*in);
4688 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4690 loadmodel->brush.data_leafs = out;
4691 loadmodel->brush.num_leafs = count;
4693 for (i = 0;i < count;i++, in++, out++)
4697 out->clusterindex = LittleLong(in->clusterindex);
4698 out->areaindex = LittleLong(in->areaindex);
4699 for (j = 0;j < 3;j++)
4701 // yes the mins/maxs are ints
4702 out->mins[j] = LittleLong(in->mins[j]) - 1;
4703 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
4705 n = LittleLong(in->firstleafface);
4706 c = LittleLong(in->numleaffaces);
4707 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
4708 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)\n", n, n + c, loadmodel->brush.num_leafsurfaces);
4709 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
4710 out->numleafsurfaces = c;
4711 n = LittleLong(in->firstleafbrush);
4712 c = LittleLong(in->numleafbrushes);
4713 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
4714 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)\n", n, n + c, loadmodel->brush.num_leafbrushes);
4715 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
4716 out->numleafbrushes = c;
4720 static void Mod_Q3BSP_LoadNodes(lump_t *l)
4726 in = (q3dnode_t *)(mod_base + l->fileofs);
4727 if (l->filelen % sizeof(*in))
4728 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4729 count = l->filelen / sizeof(*in);
4730 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4732 loadmodel->brush.data_nodes = out;
4733 loadmodel->brush.num_nodes = count;
4735 for (i = 0;i < count;i++, in++, out++)
4738 n = LittleLong(in->planeindex);
4739 if (n < 0 || n >= loadmodel->brush.num_planes)
4740 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)\n", n, loadmodel->brush.num_planes);
4741 out->plane = loadmodel->brush.data_planes + n;
4742 for (j = 0;j < 2;j++)
4744 n = LittleLong(in->childrenindex[j]);
4747 if (n >= loadmodel->brush.num_nodes)
4748 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)\n", n, loadmodel->brush.num_nodes);
4749 out->children[j] = loadmodel->brush.data_nodes + n;
4754 if (n >= loadmodel->brush.num_leafs)
4755 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)\n", n, loadmodel->brush.num_leafs);
4756 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
4759 for (j = 0;j < 3;j++)
4761 // yes the mins/maxs are ints
4762 out->mins[j] = LittleLong(in->mins[j]) - 1;
4763 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
4767 // set the parent pointers
4768 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
4771 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
4774 q3dlightgrid_t *out;
4777 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
4778 if (l->filelen % sizeof(*in))
4779 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
4780 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
4781 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
4782 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
4783 loadmodel->brushq3.num_lightgrid_imins[0] = ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
4784 loadmodel->brushq3.num_lightgrid_imins[1] = ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
4785 loadmodel->brushq3.num_lightgrid_imins[2] = ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
4786 loadmodel->brushq3.num_lightgrid_imaxs[0] = floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
4787 loadmodel->brushq3.num_lightgrid_imaxs[1] = floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
4788 loadmodel->brushq3.num_lightgrid_imaxs[2] = floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
4789 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
4790 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
4791 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
4792 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
4793 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]);
4794 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]);
4796 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
4799 if (l->filelen < count * (int)sizeof(*in))
4800 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]);
4801 if (l->filelen != count * (int)sizeof(*in))
4802 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", count * sizeof(*in), l->filelen);
4803 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4804 loadmodel->brushq3.data_lightgrid = out;
4805 loadmodel->brushq3.num_lightgrid = count;
4806 // no swapping or validation necessary
4807 memcpy(out, in, count * (int)sizeof(*out));
4811 static void Mod_Q3BSP_LoadPVS(lump_t *l)
4816 if (l->filelen == 0)
4819 // unvised maps often have cluster indices even without pvs, so check
4820 // leafs to find real number of clusters
4821 loadmodel->brush.num_pvsclusters = 1;
4822 for (i = 0;i < loadmodel->brush.num_leafs;i++)
4823 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
4826 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
4827 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
4828 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
4829 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
4833 in = (q3dpvs_t *)(mod_base + l->fileofs);
4835 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
4837 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
4838 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
4839 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
4840 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8\n", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
4841 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
4842 if (l->filelen < totalchains + (int)sizeof(*in))
4843 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);
4845 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
4846 memcpy(loadmodel->brush.data_pvsclusters, (qbyte *)(in + 1), totalchains);
4849 static void Mod_Q3BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
4851 int i, j, k, index[3];
4852 float transformed[3], blend1, blend2, blend, yaw, pitch, sinpitch;
4853 q3dlightgrid_t *a, *s;
4854 if (!model->brushq3.num_lightgrid)
4856 ambientcolor[0] = 1;
4857 ambientcolor[1] = 1;
4858 ambientcolor[2] = 1;
4861 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
4862 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
4863 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
4864 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
4865 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
4866 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
4867 index[0] = (int)floor(transformed[0]);
4868 index[1] = (int)floor(transformed[1]);
4869 index[2] = (int)floor(transformed[2]);
4870 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
4871 // now lerp the values
4872 VectorClear(diffusenormal);
4873 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
4874 for (k = 0;k < 2;k++)
4876 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
4877 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
4879 for (j = 0;j < 2;j++)
4881 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
4882 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
4884 for (i = 0;i < 2;i++)
4886 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0])));
4887 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
4889 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
4890 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
4891 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
4892 pitch = s->diffusepitch * M_PI / 128;
4893 yaw = s->diffuseyaw * M_PI / 128;
4894 sinpitch = sin(pitch);
4895 diffusenormal[0] += blend * (cos(yaw) * sinpitch);
4896 diffusenormal[1] += blend * (sin(yaw) * sinpitch);
4897 diffusenormal[2] += blend * (cos(pitch));
4898 //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 VectorNormalize(diffusenormal);
4903 //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]);
4906 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, model_t *model, mnode_t *node, const vec3_t point, int markframe)
4911 // find which leaf the point is in
4913 node = node->children[DotProduct(point, node->plane->normal) < node->plane->dist];
4914 // point trace the brushes
4915 leaf = (mleaf_t *)node;
4916 for (i = 0;i < leaf->numleafbrushes;i++)
4918 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
4919 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
4921 brush->markframe = markframe;
4922 Collision_TracePointBrushFloat(trace, point, brush);
4925 // can't do point traces on curves (they have no thickness)
4928 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)
4930 int i, startside, endside;
4931 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
4933 msurface_t *surface;
4935 if (startfrac > trace->realfraction)
4937 // note: all line fragments past first impact fraction are ignored
4938 if (VectorCompare(start, end))
4940 // find which leaf the point is in
4942 node = node->children[DotProduct(start, node->plane->normal) < node->plane->dist];
4946 // find which nodes the line is in and recurse for them
4949 // recurse down node sides
4950 dist1 = PlaneDiff(start, node->plane);
4951 dist2 = PlaneDiff(end, node->plane);
4952 startside = dist1 < 0;
4953 endside = dist2 < 0;
4954 if (startside == endside)
4956 // most of the time the line fragment is on one side of the plane
4957 node = node->children[startside];
4961 // line crosses node plane, split the line
4962 midfrac = dist1 / (dist1 - dist2);
4963 VectorLerp(start, midfrac, end, mid);
4964 // take the near side first
4965 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
4966 if (midfrac <= trace->realfraction)
4967 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
4973 nodesegmentmins[0] = min(start[0], end[0]);
4974 nodesegmentmins[1] = min(start[1], end[1]);
4975 nodesegmentmins[2] = min(start[2], end[2]);
4976 nodesegmentmaxs[0] = max(start[0], end[0]);
4977 nodesegmentmaxs[1] = max(start[1], end[1]);
4978 nodesegmentmaxs[2] = max(start[2], end[2]);
4979 // line trace the brushes
4980 leaf = (mleaf_t *)node;
4981 for (i = 0;i < leaf->numleafbrushes;i++)
4983 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
4984 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
4986 brush->markframe = markframe;
4987 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
4988 if (startfrac > trace->realfraction)
4992 // can't do point traces on curves (they have no thickness)
4993 if (mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
4995 // line trace the curves
4996 for (i = 0;i < leaf->numleafsurfaces;i++)
4998 surface = model->data_surfaces + leaf->firstleafsurface[i];
4999 if (surface->num_collisiontriangles && surface->collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
5001 surface->collisionmarkframe = markframe;
5002 Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5003 if (startfrac > trace->realfraction)
5010 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 float nodesegmentmins[3], nodesegmentmaxs[3];
5017 msurface_t *surface;
5019 // find which nodes the line is in and recurse for them
5022 // recurse down node sides
5023 int startside, endside;
5024 float dist1near, dist1far, dist2near, dist2far;
5025 BoxPlaneCornerDistances(thisbrush_start->mins, thisbrush_start->maxs, node->plane, &dist1near, &dist1far);
5026 BoxPlaneCornerDistances(thisbrush_end->mins, thisbrush_end->maxs, node->plane, &dist2near, &dist2far);
5027 startside = dist1near < 0;
5028 startside = dist1near < 0 ? (dist1far < 0 ? 1 : 2) : (dist1far < 0 ? 2 : 0);
5029 endside = dist2near < 0 ? (dist2far < 0 ? 1 : 2) : (dist2far < 0 ? 2 : 0);
5030 if (startside == 2 || endside == 2)
5032 // brushes cross plane
5033 // do not clip anything, just take both sides
5034 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5035 node = node->children[1];
5042 node = node->children[0];
5047 //midf0 = dist1near / (dist1near - dist2near);
5048 //midf1 = dist1far / (dist1far - dist2far);
5049 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5050 node = node->children[1];
5058 //midf0 = dist1near / (dist1near - dist2near);
5059 //midf1 = dist1far / (dist1far - dist2far);
5060 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5061 node = node->children[1];
5066 node = node->children[1];
5071 if (dist1near < 0 && dist2near < 0 && dist1far < 0 && dist2far < 0){node = node->children[1];continue;}
5072 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;}
5073 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;}
5074 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;}
5075 if (dist1near < 0 && dist2near >= 0 && dist1far < 0 && dist2far < 0){node = node->children[1];continue;}
5076 if (dist1near < 0 && dist2near >= 0 && dist1far < 0 && dist2far >= 0){}
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){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5079 if (dist1near >= 0 && dist2near < 0 && dist1far < 0 && dist2far < 0){node = node->children[1];continue;}
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){}
5082 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;}
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){node = node->children[0];continue;}
5085 if (dist1near >= 0 && dist2near >= 0 && dist1far >= 0 && dist2far < 0){node = node->children[0];continue;}
5086 if (dist1near >= 0 && dist2near >= 0 && dist1far >= 0 && dist2far >= 0){node = node->children[0];continue;}
5088 if (dist2near < 0) // d1n<0 && d2n<0
5090 if (dist2near < 0) // d1n<0 && d2n<0
5092 if (dist2near < 0) // d1n<0 && d2n<0
5095 else // d1n<0 && d2n>0
5099 else // d1n<0 && d2n>0
5101 if (dist2near < 0) // d1n<0 && d2n<0
5104 else // d1n<0 && d2n>0
5109 else // d1n<0 && d2n>0
5115 if (dist2near < 0) // d1n>0 && d2n<0
5118 else // d1n>0 && d2n>0
5122 if (dist1near < 0 == dist1far < 0 == dist2near < 0 == dist2far < 0)
5124 node = node->children[startside];
5127 if (dist1near < dist2near)
5132 node = node->children[0];
5137 node = node->children[1];
5140 // dist1near < 0 && dist2far >= 0
5146 startside = dist1near < 0 ? (dist1far < 0 ? 1 : 2) : (dist1far < 0 ? 2 : 0);
5147 endside = dist2near < 0 ? (dist2far < 0 ? 1 : 2) : (dist2far < 0 ? 2 : 0);
5148 if (startside == 2 || endside == 2)
5150 // brushes cross plane
5151 // do not clip anything, just take both sides
5152 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5153 node = node->children[1];
5155 else if (startside == endside)
5156 node = node->children[startside];
5157 else if (startside == 0) // endside = 1 (start infront, end behind)
5160 else // startside == 1 endside = 0 (start behind, end infront)
5166 node = node->children[startside];
5169 // start and end brush cross plane
5175 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5176 node = node->children[1];
5177 else if (dist1near < 0 && dist1far < 0 && dist2near >= 0 && dist2far >= 0)
5178 else if (dist1near >= 0 && dist1far >= 0 && dist2near < 0 && dist2far < 0)
5179 else if (dist1near >= 0 && dist1far >= 0 && dist2near >= 0 && dist2far >= 0)
5180 node = node->children[0];
5182 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5183 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5184 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5185 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5186 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5189 else if (dist1near >= 0 && dist1far >= 0)
5192 else // mixed (lying on plane)
5196 if (dist2near < 0 && dist2far < 0)
5200 node = node->children[1];
5202 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5203 node = node->children[0];
5204 else if (dist1near >= 0 && dist1far >= 0 && dist2near >= 0 && dist2far >= 0)
5205 node = node->children[1];
5209 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5210 node = node->children[1];
5212 sides = dist1near || dist1near < 0 | dist1far < 0 | dist2near < 0 | dist
5213 startside = dist1 < 0;
5214 endside = dist2 < 0;
5215 if (startside == endside)
5217 // most of the time the line fragment is on one side of the plane
5218 node = node->children[startside];
5222 // line crosses node plane, split the line
5223 midfrac = dist1 / (dist1 - dist2);
5224 VectorLerp(start, midfrac, end, mid);
5225 // take the near side first
5226 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5227 if (midfrac <= trace->fraction)
5228 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5236 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5237 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5238 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5239 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5240 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5241 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5242 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5246 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5247 node = node->children[1];
5250 // FIXME: could be made faster by copying TraceLine code and making it use
5251 // box plane distances... (variant on the BoxOnPlaneSide code)
5254 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5255 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5256 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5257 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5258 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5259 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5260 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5264 if (mod_q3bsp_debugtracebrush.integer == 2)
5266 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5267 node = node->children[1];
5270 else if (mod_q3bsp_debugtracebrush.integer == 1)
5272 // recurse down node sides
5273 sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5276 // segment box crosses plane
5277 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5278 node = node->children[1];
5281 // take whichever side the segment box is on
5282 node = node->children[sides - 1];
5287 // recurse down node sides
5288 sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5291 // segment box crosses plane
5292 // now check start and end brush boxes to handle a lot of 'diagonal' cases more efficiently...
5293 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, node->plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, node->plane);
5296 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5297 node = node->children[1];
5301 // take whichever side the segment box is on
5302 node = node->children[sides - 1];
5308 // FIXME: could be made faster by copying TraceLine code and making it use
5309 // box plane distances... (variant on the BoxOnPlaneSide code)
5312 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5313 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5314 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5315 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5316 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5317 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5318 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5322 if (mod_q3bsp_debugtracebrush.integer == 2)
5324 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5325 node = node->children[1];
5327 else if (mod_q3bsp_debugtracebrush.integer == 1)
5329 // recurse down node sides
5330 sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5333 // segment box crosses plane
5334 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5335 node = node->children[1];
5339 // take whichever side the segment box is on
5340 node = node->children[sides - 1];
5345 // recurse down node sides
5346 sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5349 // segment box crosses plane
5350 // now check start and end brush boxes to handle a lot of 'diagonal' cases more efficiently...
5351 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, node->plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, node->plane);
5354 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5358 // take whichever side the segment box is on
5359 node = node->children[sides - 1];
5364 leaf = (mleaf_t *)node;
5365 for (i = 0;i < leaf->numleafbrushes;i++)
5367 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
5368 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
5370 brush->markframe = markframe;
5371 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
5374 if (mod_q3bsp_curves_collisions.integer)
5376 for (i = 0;i < leaf->numleafsurfaces;i++)
5378 surface = model->data_surfaces + leaf->firstleafsurface[i];
5379 if (surface->num_collisiontriangles && surface->collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
5381 surface->collisionmarkframe = markframe;
5382 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5388 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)
5391 float segmentmins[3], segmentmaxs[3];
5392 colbrushf_t *thisbrush_start, *thisbrush_end;
5393 matrix4x4_t startmatrix, endmatrix;
5394 static int markframe = 0;
5395 msurface_t *surface;
5397 memset(trace, 0, sizeof(*trace));
5398 trace->fraction = 1;
5399 trace->realfraction = 1;
5400 trace->hitsupercontentsmask = hitsupercontentsmask;
5401 Matrix4x4_CreateIdentity(&startmatrix);
5402 Matrix4x4_CreateIdentity(&endmatrix);
5403 segmentmins[0] = min(boxstartmins[0], boxendmins[0]);
5404 segmentmins[1] = min(boxstartmins[1], boxendmins[1]);
5405 segmentmins[2] = min(boxstartmins[2], boxendmins[2]);
5406 segmentmaxs[0] = max(boxstartmaxs[0], boxendmaxs[0]);
5407 segmentmaxs[1] = max(boxstartmaxs[1], boxendmaxs[1]);
5408 segmentmaxs[2] = max(boxstartmaxs[2], boxendmaxs[2]);
5409 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxstartmins, boxstartmaxs) && VectorCompare(boxendmins, boxendmaxs))
5411 if (VectorCompare(boxstartmins, boxendmins))
5414 if (model->brush.submodel)
5416 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5417 if (brush->colbrushf)
5418 Collision_TracePointBrushFloat(trace, boxstartmins, brush->colbrushf);
5421 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, boxstartmins, ++markframe);
5426 if (model->brush.submodel)
5428 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5429 if (brush->colbrushf)
5430 Collision_TraceLineBrushFloat(trace, boxstartmins, boxendmins, brush->colbrushf, brush->colbrushf);
5431 if (mod_q3bsp_curves_collisions.integer)
5432 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
5433 if (surface->num_collisiontriangles)
5434 Collision_TraceLineTriangleMeshFloat(trace, boxstartmins, boxendmins, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5437 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, boxstartmins, boxendmins, 0, 1, boxstartmins, boxendmins, ++markframe, segmentmins, segmentmaxs);
5442 // box trace, performed as brush trace
5443 thisbrush_start = Collision_BrushForBox(&startmatrix, boxstartmins, boxstartmaxs);
5444 thisbrush_end = Collision_BrushForBox(&endmatrix, boxendmins, boxendmaxs);
5445 if (model->brush.submodel)
5447 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5448 if (brush->colbrushf)
5449 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush->colbrushf, brush->colbrushf);
5450 if (mod_q3bsp_curves_collisions.integer)
5451 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
5452 if (surface->num_collisiontriangles)
5453 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5456 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, thisbrush_start, thisbrush_end, ++markframe, segmentmins, segmentmaxs);
5460 static int Mod_Q3BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents)
5462 int supercontents = 0;
5463 if (nativecontents & CONTENTSQ3_SOLID)
5464 supercontents |= SUPERCONTENTS_SOLID;
5465 if (nativecontents & CONTENTSQ3_WATER)
5466 supercontents |= SUPERCONTENTS_WATER;
5467 if (nativecontents & CONTENTSQ3_SLIME)
5468 supercontents |= SUPERCONTENTS_SLIME;
5469 if (nativecontents & CONTENTSQ3_LAVA)
5470 supercontents |= SUPERCONTENTS_LAVA;
5471 if (nativecontents & CONTENTSQ3_BODY)
5472 supercontents |= SUPERCONTENTS_BODY;
5473 if (nativecontents & CONTENTSQ3_CORPSE)
5474 supercontents |= SUPERCONTENTS_CORPSE;
5475 if (nativecontents & CONTENTSQ3_NODROP)
5476 supercontents |= SUPERCONTENTS_NODROP;
5477 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
5478 supercontents |= SUPERCONTENTS_PLAYERCLIP;
5479 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
5480 supercontents |= SUPERCONTENTS_MONSTERCLIP;
5481 if (nativecontents & CONTENTSQ3_DONOTENTER)
5482 supercontents |= SUPERCONTENTS_DONOTENTER;
5483 return supercontents;
5486 static int Mod_Q3BSP_NativeContentsFromSuperContents(model_t *model, int supercontents)
5488 int nativecontents = 0;
5489 if (supercontents & SUPERCONTENTS_SOLID)
5490 nativecontents |= CONTENTSQ3_SOLID;
5491 if (supercontents & SUPERCONTENTS_WATER)
5492 nativecontents |= CONTENTSQ3_WATER;
5493 if (supercontents & SUPERCONTENTS_SLIME)
5494 nativecontents |= CONTENTSQ3_SLIME;
5495 if (supercontents & SUPERCONTENTS_LAVA)
5496 nativecontents |= CONTENTSQ3_LAVA;
5497 if (supercontents & SUPERCONTENTS_BODY)
5498 nativecontents |= CONTENTSQ3_BODY;
5499 if (supercontents & SUPERCONTENTS_CORPSE)
5500 nativecontents |= CONTENTSQ3_CORPSE;
5501 if (supercontents & SUPERCONTENTS_NODROP)
5502 nativecontents |= CONTENTSQ3_NODROP;
5503 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
5504 nativecontents |= CONTENTSQ3_PLAYERCLIP;
5505 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
5506 nativecontents |= CONTENTSQ3_MONSTERCLIP;
5507 if (supercontents & SUPERCONTENTS_DONOTENTER)
5508 nativecontents |= CONTENTSQ3_DONOTENTER;
5509 return nativecontents;
5512 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
5517 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
5518 node = node->children[1];
5520 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
5521 if (loadmodel->brush.num_leafs < numleafs)
5522 loadmodel->brush.num_leafs = numleafs;
5525 void Mod_Q3BSP_Load(model_t *mod, void *buffer, void *bufferend)
5527 int i, j, numshadowmeshtriangles;
5528 q3dheader_t *header;
5529 float corner[3], yawradius, modelradius;
5530 msurface_t *surface;
5532 mod->type = mod_brushq3;
5533 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
5536 header = (q3dheader_t *)buffer;
5538 i = LittleLong(header->version);
5539 if (i != Q3BSPVERSION)
5540 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
5541 mod->brush.ishlbsp = false;
5542 mod->brush.ismcbsp = false;
5543 if (loadmodel->isworldmodel)
5545 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
5546 Cvar_SetValue("mcbsp", mod->brush.ismcbsp);
5549 mod->soundfromcenter = true;
5550 mod->TraceBox = Mod_Q3BSP_TraceBox;
5551 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
5552 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
5553 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
5554 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
5555 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
5556 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
5557 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
5558 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
5559 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
5560 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
5561 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
5562 mod->Draw = R_Q1BSP_Draw;
5563 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
5564 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
5565 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
5566 mod->DrawLight = R_Q1BSP_DrawLight;
5568 mod_base = (qbyte *)header;
5570 // swap all the lumps
5571 header->ident = LittleLong(header->ident);
5572 header->version = LittleLong(header->version);
5573 for (i = 0;i < Q3HEADER_LUMPS;i++)
5575 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
5576 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
5579 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
5580 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
5581 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
5582 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
5583 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
5584 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
5585 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
5586 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
5587 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS]);
5588 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
5589 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
5590 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
5591 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
5592 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
5593 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
5594 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
5595 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
5596 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
5598 // the MakePortals code works fine on the q3bsp data as well
5599 Mod_Q1BSP_MakePortals();
5601 // make a single combined shadow mesh to allow optimized shadow volume creation
5602 numshadowmeshtriangles = 0;
5603 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
5605 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
5606 numshadowmeshtriangles += surface->num_triangles;
5608 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
5609 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
5610 if (surface->groupmesh)
5611 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));
5612 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true);
5613 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
5615 loadmodel->brush.num_leafs = 0;
5616 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
5618 if (loadmodel->isworldmodel)
5620 // clear out any stale submodels or worldmodels lying around
5621 // if we did this clear before now, an error might abort loading and
5622 // leave things in a bad state
5623 Mod_RemoveStaleWorldModels(loadmodel);
5627 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
5632 // LordHavoc: only register submodels if it is the world
5633 // (prevents external bsp models from replacing world submodels with
5635 if (!loadmodel->isworldmodel)
5637 // duplicate the basic information
5638 sprintf(name, "*%i", i);
5639 mod = Mod_FindName(name);
5641 strcpy(mod->name, name);
5642 // textures and memory belong to the main model
5643 mod->texturepool = NULL;
5644 mod->mempool = NULL;
5645 mod->brush.GetPVS = NULL;
5646 mod->brush.FatPVS = NULL;
5647 mod->brush.BoxTouchingPVS = NULL;
5648 mod->brush.BoxTouchingLeafPVS = NULL;
5649 mod->brush.BoxTouchingVisibleLeafs = NULL;
5650 mod->brush.FindBoxClusters = NULL;
5651 mod->brush.LightPoint = NULL;
5652 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
5654 mod->brush.submodel = i;
5656 // make the model surface list (used by shadowing/lighting)
5657 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
5658 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
5659 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
5660 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
5661 mod->surfacelist = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->surfacelist));
5662 for (j = 0;j < mod->nummodelsurfaces;j++)
5663 mod->surfacelist[j] = mod->firstmodelsurface + j;
5665 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
5666 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
5667 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5668 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5669 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5670 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
5671 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
5672 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5673 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5674 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
5675 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
5676 mod->yawmins[2] = mod->normalmins[2];
5677 mod->yawmaxs[2] = mod->normalmaxs[2];
5678 mod->radius = modelradius;
5679 mod->radius2 = modelradius * modelradius;
5681 for (j = 0;j < mod->nummodelsurfaces;j++)
5682 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->surfaceflags & Q3SURFACEFLAG_SKY)
5684 if (j < mod->nummodelsurfaces)
5685 mod->DrawSky = R_Q1BSP_DrawSky;
5689 void Mod_IBSP_Load(model_t *mod, void *buffer, void *bufferend)
5691 int i = LittleLong(((int *)buffer)[1]);
5692 if (i == Q3BSPVERSION)
5693 Mod_Q3BSP_Load(mod,buffer, bufferend);
5694 else if (i == Q2BSPVERSION)
5695 Mod_Q2BSP_Load(mod,buffer, bufferend);
5697 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i\n", i);
5700 void Mod_MAP_Load(model_t *mod, void *buffer, void *bufferend)
5702 Host_Error("Mod_MAP_Load: not yet implemented\n");