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 qbyte mod_q1bsp_novis[(MAX_MAP_LEAFS + 7)/ 8];
31 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128"};
32 cvar_t halflifebsp = {0, "halflifebsp", "0"};
33 cvar_t r_novis = {0, "r_novis", "0"};
34 cvar_t r_miplightmaps = {CVAR_SAVE, "r_miplightmaps", "0"};
35 cvar_t r_lightmaprgba = {0, "r_lightmaprgba", "1"};
36 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0"};
37 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4"};
38 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "1"};
39 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024"};
40 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536"};
41 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15"};
42 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "1"};
43 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024"};
44 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225"};
45 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1"};
46 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1"};
47 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0"};
49 static void Mod_Q1BSP_Collision_Init (void);
50 void Mod_BrushInit(void)
52 // Cvar_RegisterVariable(&r_subdivide_size);
53 Cvar_RegisterVariable(&halflifebsp);
54 Cvar_RegisterVariable(&r_novis);
55 Cvar_RegisterVariable(&r_miplightmaps);
56 Cvar_RegisterVariable(&r_lightmaprgba);
57 Cvar_RegisterVariable(&r_nosurftextures);
58 Cvar_RegisterVariable(&r_subdivisions_tolerance);
59 Cvar_RegisterVariable(&r_subdivisions_mintess);
60 Cvar_RegisterVariable(&r_subdivisions_maxtess);
61 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
62 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
63 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
64 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
65 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
66 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
67 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
68 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
69 memset(mod_q1bsp_novis, 0xff, sizeof(mod_q1bsp_novis));
70 Mod_Q1BSP_Collision_Init();
73 static mleaf_t *Mod_Q1BSP_PointInLeaf(model_t *model, const vec3_t p)
80 Mod_CheckLoaded(model);
82 // LordHavoc: modified to start at first clip node,
83 // in other words: first node of the (sub)model
84 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
86 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
88 return (mleaf_t *)node;
91 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(model_t *model, const vec3_t p, qbyte *out, int outsize)
95 leaf = Mod_Q1BSP_PointInLeaf(model, p);
98 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
101 memcpy(out, leaf->ambient_sound_level, i);
107 memset(out, 0, outsize);
110 static int Mod_Q1BSP_BoxTouchingPVS(model_t *model, const qbyte *pvs, const vec3_t mins, const vec3_t maxs)
112 int clusterindex, side, nodestackindex = 0;
113 mnode_t *node, *nodestack[1024];
114 if (!model->brush.num_pvsclusters)
116 node = model->brush.data_nodes;
121 // node - recurse down the BSP tree
122 side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
125 // box is on one side of plane, take that path
126 node = node->children[side];
130 // box crosses plane, take one path and remember the other
131 if (nodestackindex < 1024)
132 nodestack[nodestackindex++] = node->children[0];
133 node = node->children[1];
138 // leaf - check cluster bit
139 clusterindex = ((mleaf_t *)node)->clusterindex;
140 if (CHECKPVSBIT(pvs, clusterindex))
142 // it is visible, return immediately with the news
147 // nothing to see here, try another path we didn't take earlier
148 if (nodestackindex == 0)
150 node = nodestack[--nodestackindex];
158 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(model_t *model, const qbyte *visibleleafs, const vec3_t mins, const vec3_t maxs)
160 int side, nodestackindex = 0;
161 mnode_t *node, *nodestack[1024];
162 node = model->brush.data_nodes;
167 // node - recurse down the BSP tree
168 side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
171 // box is on one side of plane, take that path
172 node = node->children[side];
176 // box crosses plane, take one path and remember the other
177 if (nodestackindex < 1024)
178 nodestack[nodestackindex++] = node->children[0];
179 node = node->children[1];
184 // leaf - check if it is visible
185 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
187 // it is visible, return immediately with the news
192 // nothing to see here, try another path we didn't take earlier
193 if (nodestackindex == 0)
195 node = nodestack[--nodestackindex];
203 typedef struct findnonsolidlocationinfo_s
211 findnonsolidlocationinfo_t;
213 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
215 int i, surfacenum, k, *tri, *mark;
216 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
218 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
220 surface = info->model->brush.data_surfaces + *mark;
221 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
223 for (k = 0;k < surface->mesh.num_triangles;k++)
225 tri = surface->mesh.data_element3i + k * 3;
226 VectorCopy((surface->mesh.data_vertex3f + tri[0] * 3), vert[0]);
227 VectorCopy((surface->mesh.data_vertex3f + tri[1] * 3), vert[1]);
228 VectorCopy((surface->mesh.data_vertex3f + tri[2] * 3), vert[2]);
229 VectorSubtract(vert[1], vert[0], edge[0]);
230 VectorSubtract(vert[2], vert[1], edge[1]);
231 CrossProduct(edge[1], edge[0], facenormal);
232 if (facenormal[0] || facenormal[1] || facenormal[2])
234 VectorNormalize(facenormal);
235 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
236 if (f <= info->bestdist && f >= -info->bestdist)
238 VectorSubtract(vert[0], vert[2], edge[2]);
239 VectorNormalize(edge[0]);
240 VectorNormalize(edge[1]);
241 VectorNormalize(edge[2]);
242 CrossProduct(facenormal, edge[0], edgenormal[0]);
243 CrossProduct(facenormal, edge[1], edgenormal[1]);
244 CrossProduct(facenormal, edge[2], edgenormal[2]);
246 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
247 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
248 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
250 // we got lucky, the center is within the face
251 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
255 if (info->bestdist > dist)
257 info->bestdist = dist;
258 VectorScale(facenormal, (info->radius - -dist), info->nudge);
263 if (info->bestdist > dist)
265 info->bestdist = dist;
266 VectorScale(facenormal, (info->radius - dist), info->nudge);
272 // check which edge or vertex the center is nearest
273 for (i = 0;i < 3;i++)
275 f = DotProduct(info->center, edge[i]);
276 if (f >= DotProduct(vert[0], edge[i])
277 && f <= DotProduct(vert[1], edge[i]))
280 VectorMA(info->center, -f, edge[i], point);
281 dist = sqrt(DotProduct(point, point));
282 if (info->bestdist > dist)
284 info->bestdist = dist;
285 VectorScale(point, (info->radius / dist), info->nudge);
287 // skip both vertex checks
288 // (both are further away than this edge)
293 // not on edge, check first vertex of edge
294 VectorSubtract(info->center, vert[i], point);
295 dist = sqrt(DotProduct(point, point));
296 if (info->bestdist > dist)
298 info->bestdist = dist;
299 VectorScale(point, (info->radius / dist), info->nudge);
311 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
315 float f = PlaneDiff(info->center, node->plane);
316 if (f >= -info->bestdist)
317 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
318 if (f <= info->bestdist)
319 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
323 if (((mleaf_t *)node)->numleafsurfaces)
324 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
328 static void Mod_Q1BSP_FindNonSolidLocation(model_t *model, const vec3_t in, vec3_t out, float radius)
331 findnonsolidlocationinfo_t info;
337 VectorCopy(in, info.center);
338 info.radius = radius;
343 VectorClear(info.nudge);
344 info.bestdist = radius;
345 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
346 VectorAdd(info.center, info.nudge, info.center);
348 while (info.bestdist < radius && ++i < 10);
349 VectorCopy(info.center, out);
352 int Mod_Q1BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents)
354 switch(nativecontents)
359 return SUPERCONTENTS_SOLID;
361 return SUPERCONTENTS_WATER;
363 return SUPERCONTENTS_SLIME;
365 return SUPERCONTENTS_LAVA;
367 return SUPERCONTENTS_SKY;
372 int Mod_Q1BSP_NativeContentsFromSuperContents(model_t *model, int supercontents)
374 if (supercontents & SUPERCONTENTS_SOLID)
375 return CONTENTS_SOLID;
376 if (supercontents & SUPERCONTENTS_SKY)
378 if (supercontents & SUPERCONTENTS_LAVA)
379 return CONTENTS_LAVA;
380 if (supercontents & SUPERCONTENTS_SLIME)
381 return CONTENTS_SLIME;
382 if (supercontents & SUPERCONTENTS_WATER)
383 return CONTENTS_WATER;
384 return CONTENTS_EMPTY;
389 // the hull we're tracing through
392 // the trace structure to fill in
395 // start, end, and end - start (in model space)
400 RecursiveHullCheckTraceInfo_t;
402 // 1/32 epsilon to keep floating point happy
403 #define DIST_EPSILON (0.03125)
405 #define HULLCHECKSTATE_EMPTY 0
406 #define HULLCHECKSTATE_SOLID 1
407 #define HULLCHECKSTATE_DONE 2
409 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
411 // status variables, these don't need to be saved on the stack when
412 // recursing... but are because this should be thread-safe
413 // (note: tracing against a bbox is not thread-safe, yet)
418 // variables that need to be stored on the stack when recursing
423 // LordHavoc: a goto! everyone flee in terror... :)
428 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
429 if (!t->trace->startfound)
431 t->trace->startfound = true;
432 t->trace->startsupercontents |= num;
434 if (num & SUPERCONTENTS_LIQUIDSMASK)
435 t->trace->inwater = true;
437 t->trace->inopen = true;
438 if (num & t->trace->hitsupercontentsmask)
440 // if the first leaf is solid, set startsolid
441 if (t->trace->allsolid)
442 t->trace->startsolid = true;
443 #if COLLISIONPARANOID >= 3
446 return HULLCHECKSTATE_SOLID;
450 t->trace->allsolid = false;
451 #if COLLISIONPARANOID >= 3
454 return HULLCHECKSTATE_EMPTY;
458 // find the point distances
459 node = t->hull->clipnodes + num;
461 plane = t->hull->planes + node->planenum;
464 t1 = p1[plane->type] - plane->dist;
465 t2 = p2[plane->type] - plane->dist;
469 t1 = DotProduct (plane->normal, p1) - plane->dist;
470 t2 = DotProduct (plane->normal, p2) - plane->dist;
477 #if COLLISIONPARANOID >= 3
480 num = node->children[1];
489 #if COLLISIONPARANOID >= 3
492 num = node->children[0];
498 // the line intersects, find intersection point
499 // LordHavoc: this uses the original trace for maximum accuracy
500 #if COLLISIONPARANOID >= 3
505 t1 = t->start[plane->type] - plane->dist;
506 t2 = t->end[plane->type] - plane->dist;
510 t1 = DotProduct (plane->normal, t->start) - plane->dist;
511 t2 = DotProduct (plane->normal, t->end) - plane->dist;
514 midf = t1 / (t1 - t2);
515 midf = bound(p1f, midf, p2f);
516 VectorMA(t->start, midf, t->dist, mid);
518 // recurse both sides, front side first
519 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
520 // if this side is not empty, return what it is (solid or done)
521 if (ret != HULLCHECKSTATE_EMPTY)
524 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
525 // if other side is not solid, return what it is (empty or done)
526 if (ret != HULLCHECKSTATE_SOLID)
529 // front is air and back is solid, this is the impact point...
532 t->trace->plane.dist = -plane->dist;
533 VectorNegate (plane->normal, t->trace->plane.normal);
537 t->trace->plane.dist = plane->dist;
538 VectorCopy (plane->normal, t->trace->plane.normal);
541 // calculate the true fraction
542 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
543 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
544 midf = t1 / (t1 - t2);
545 t->trace->realfraction = bound(0, midf, 1);
547 // calculate the return fraction which is nudged off the surface a bit
548 midf = (t1 - DIST_EPSILON) / (t1 - t2);
549 t->trace->fraction = bound(0, midf, 1);
551 #if COLLISIONPARANOID >= 3
554 return HULLCHECKSTATE_DONE;
557 #if COLLISIONPARANOID < 2
558 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
561 num = t->hull->clipnodes[num].children[(t->hull->planes[t->hull->clipnodes[num].planenum].type < 3 ? t->start[t->hull->planes[t->hull->clipnodes[num].planenum].type] : DotProduct(t->hull->planes[t->hull->clipnodes[num].planenum].normal, t->start)) < t->hull->planes[t->hull->clipnodes[num].planenum].dist];
562 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
563 t->trace->startsupercontents |= num;
564 if (num & SUPERCONTENTS_LIQUIDSMASK)
565 t->trace->inwater = true;
567 t->trace->inopen = true;
568 if (num & t->trace->hitsupercontentsmask)
570 t->trace->allsolid = t->trace->startsolid = true;
571 return HULLCHECKSTATE_SOLID;
575 t->trace->allsolid = t->trace->startsolid = false;
576 return HULLCHECKSTATE_EMPTY;
581 static void Mod_Q1BSP_TraceBox(struct model_s *model, int frame, trace_t *trace, const vec3_t boxstartmins, const vec3_t boxstartmaxs, const vec3_t boxendmins, const vec3_t boxendmaxs, int hitsupercontentsmask)
583 // this function currently only supports same size start and end
585 RecursiveHullCheckTraceInfo_t rhc;
587 memset(&rhc, 0, sizeof(rhc));
588 memset(trace, 0, sizeof(trace_t));
590 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
591 rhc.trace->fraction = 1;
592 rhc.trace->realfraction = 1;
593 rhc.trace->allsolid = true;
594 VectorSubtract(boxstartmaxs, boxstartmins, boxsize);
596 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
597 else if (model->brush.ishlbsp)
599 // LordHavoc: this has to have a minor tolerance (the .1) because of
600 // minor float precision errors from the box being transformed around
601 if (boxsize[0] < 32.1)
603 if (boxsize[2] < 54) // pick the nearest of 36 or 72
604 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
606 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
609 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
613 // LordHavoc: this has to have a minor tolerance (the .1) because of
614 // minor float precision errors from the box being transformed around
615 if (boxsize[0] < 32.1)
616 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
618 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
620 VectorSubtract(boxstartmins, rhc.hull->clip_mins, rhc.start);
621 VectorSubtract(boxendmins, rhc.hull->clip_mins, rhc.end);
622 VectorSubtract(rhc.end, rhc.start, rhc.dist);
623 #if COLLISIONPARANOID >= 2
624 Con_Printf("t(%f %f %f,%f %f %f,%i %f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2], rhc.hull - model->brushq1.hulls, rhc.hull->clip_mins[0], rhc.hull->clip_mins[1], rhc.hull->clip_mins[2]);
625 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
628 if (DotProduct(rhc.dist, rhc.dist))
629 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
631 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
635 static hull_t box_hull;
636 static dclipnode_t box_clipnodes[6];
637 static mplane_t box_planes[6];
639 static void Mod_Q1BSP_Collision_Init (void)
644 //Set up the planes and clipnodes so that the six floats of a bounding box
645 //can just be stored out and get a proper hull_t structure.
647 box_hull.clipnodes = box_clipnodes;
648 box_hull.planes = box_planes;
649 box_hull.firstclipnode = 0;
650 box_hull.lastclipnode = 5;
652 for (i = 0;i < 6;i++)
654 box_clipnodes[i].planenum = i;
658 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
660 box_clipnodes[i].children[side^1] = i + 1;
662 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
664 box_planes[i].type = i>>1;
665 box_planes[i].normal[i>>1] = 1;
669 void Collision_ClipTrace_Box(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontentsmask, int boxsupercontents)
673 colplanef_t cbox_planes[6];
674 cbox.supercontents = boxsupercontents;
677 cbox.numtriangles = 0;
678 cbox.planes = cbox_planes;
680 cbox.elements = NULL;
688 cbox_planes[0].normal[0] = 1;cbox_planes[0].normal[1] = 0;cbox_planes[0].normal[2] = 0;cbox_planes[0].dist = cmaxs[0] - mins[0];
689 cbox_planes[1].normal[0] = -1;cbox_planes[1].normal[1] = 0;cbox_planes[1].normal[2] = 0;cbox_planes[1].dist = maxs[0] - cmins[0];
690 cbox_planes[2].normal[0] = 0;cbox_planes[2].normal[1] = 1;cbox_planes[2].normal[2] = 0;cbox_planes[2].dist = cmaxs[1] - mins[1];
691 cbox_planes[3].normal[0] = 0;cbox_planes[3].normal[1] = -1;cbox_planes[3].normal[2] = 0;cbox_planes[3].dist = maxs[1] - cmins[1];
692 cbox_planes[4].normal[0] = 0;cbox_planes[4].normal[1] = 0;cbox_planes[4].normal[2] = 1;cbox_planes[4].dist = cmaxs[2] - mins[2];
693 cbox_planes[5].normal[0] = 0;cbox_planes[5].normal[1] = 0;cbox_planes[5].normal[2] = -1;cbox_planes[5].dist = maxs[2] - cmins[2];
694 memset(trace, 0, sizeof(trace_t));
695 trace->hitsupercontentsmask = hitsupercontentsmask;
697 trace->realfraction = 1;
698 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
700 RecursiveHullCheckTraceInfo_t rhc;
701 // fill in a default trace
702 memset(&rhc, 0, sizeof(rhc));
703 memset(trace, 0, sizeof(trace_t));
704 //To keep everything totally uniform, bounding boxes are turned into small
705 //BSP trees instead of being compared directly.
706 // create a temp hull from bounding box sizes
707 box_planes[0].dist = cmaxs[0] - mins[0];
708 box_planes[1].dist = cmins[0] - maxs[0];
709 box_planes[2].dist = cmaxs[1] - mins[1];
710 box_planes[3].dist = cmins[1] - maxs[1];
711 box_planes[4].dist = cmaxs[2] - mins[2];
712 box_planes[5].dist = cmins[2] - maxs[2];
713 #if COLLISIONPARANOID >= 3
714 Con_Printf("box_planes %f:%f %f:%f %f:%f\ncbox %f %f %f:%f %f %f\nbox %f %f %f:%f %f %f\n", box_planes[0].dist, box_planes[1].dist, box_planes[2].dist, box_planes[3].dist, box_planes[4].dist, box_planes[5].dist, cmins[0], cmins[1], cmins[2], cmaxs[0], cmaxs[1], cmaxs[2], mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
716 // trace a line through the generated clipping hull
717 //rhc.boxsupercontents = boxsupercontents;
718 rhc.hull = &box_hull;
720 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
721 rhc.trace->fraction = 1;
722 rhc.trace->realfraction = 1;
723 rhc.trace->allsolid = true;
724 VectorCopy(start, rhc.start);
725 VectorCopy(end, rhc.end);
726 VectorSubtract(rhc.end, rhc.start, rhc.dist);
727 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
728 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
729 if (rhc.trace->startsupercontents)
730 rhc.trace->startsupercontents = boxsupercontents;
734 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
736 int side, distz = endz - startz;
742 return false; // didn't hit anything
744 switch (node->plane->type)
747 node = node->children[x < node->plane->dist];
750 node = node->children[y < node->plane->dist];
753 side = startz < node->plane->dist;
754 if ((endz < node->plane->dist) == side)
756 node = node->children[side];
759 // found an intersection
760 mid = node->plane->dist;
763 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
764 front += startz * node->plane->normal[2];
765 back += endz * node->plane->normal[2];
766 side = front < node->plane->dist;
767 if ((back < node->plane->dist) == side)
769 node = node->children[side];
772 // found an intersection
773 mid = startz + distz * (front - node->plane->dist) / (front - back);
777 // go down front side
778 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
779 return true; // hit something
782 // check for impact on this node
783 if (node->numsurfaces)
788 surface = r_refdef.worldmodel->brush.data_surfaces + node->firstsurface;
789 for (i = 0;i < node->numsurfaces;i++, surface++)
791 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo->samples)
792 continue; // no lightmaps
794 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];
795 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];
797 if (ds >= 0 && ds < surface->lightmapinfo->extents[0] && dt >= 0 && dt < surface->lightmapinfo->extents[1])
800 int lmwidth, lmheight, maps, line3, size3, dsfrac = ds & 15, dtfrac = dt & 15, scale = 0, r00 = 0, g00 = 0, b00 = 0, r01 = 0, g01 = 0, b01 = 0, r10 = 0, g10 = 0, b10 = 0, r11 = 0, g11 = 0, b11 = 0;
801 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
802 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
803 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
804 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
806 lightmap = surface->lightmapinfo->samples + ((dt>>4) * lmwidth + (ds>>4))*3; // LordHavoc: *3 for colored lighting
808 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
810 scale = d_lightstylevalue[surface->lightmapinfo->styles[maps]];
811 r00 += lightmap[ 0] * scale;g00 += lightmap[ 1] * scale;b00 += lightmap[ 2] * scale;
812 r01 += lightmap[ 3] * scale;g01 += lightmap[ 4] * scale;b01 += lightmap[ 5] * scale;
813 r10 += lightmap[line3+0] * scale;g10 += lightmap[line3+1] * scale;b10 += lightmap[line3+2] * scale;
814 r11 += lightmap[line3+3] * scale;g11 += lightmap[line3+4] * scale;b11 += lightmap[line3+5] * scale;
819 LordHavoc: here's the readable version of the interpolation
820 code, not quite as easy for the compiler to optimize...
822 dsfrac is the X position in the lightmap pixel, * 16
823 dtfrac is the Y position in the lightmap pixel, * 16
824 r00 is top left corner, r01 is top right corner
825 r10 is bottom left corner, r11 is bottom right corner
826 g and b are the same layout.
827 r0 and r1 are the top and bottom intermediate results
829 first we interpolate the top two points, to get the top
832 r0 = (((r01-r00) * dsfrac) >> 4) + r00;
833 g0 = (((g01-g00) * dsfrac) >> 4) + g00;
834 b0 = (((b01-b00) * dsfrac) >> 4) + b00;
836 then we interpolate the bottom two points, to get the
839 r1 = (((r11-r10) * dsfrac) >> 4) + r10;
840 g1 = (((g11-g10) * dsfrac) >> 4) + g10;
841 b1 = (((b11-b10) * dsfrac) >> 4) + b10;
843 then we interpolate the top and bottom samples to get the
844 middle sample (the one which was requested)
846 r = (((r1-r0) * dtfrac) >> 4) + r0;
847 g = (((g1-g0) * dtfrac) >> 4) + g0;
848 b = (((b1-b0) * dtfrac) >> 4) + b0;
851 ambientcolor[0] += (float) ((((((((r11-r10) * dsfrac) >> 4) + r10)-((((r01-r00) * dsfrac) >> 4) + r00)) * dtfrac) >> 4) + ((((r01-r00) * dsfrac) >> 4) + r00)) * (1.0f / 32768.0f);
852 ambientcolor[1] += (float) ((((((((g11-g10) * dsfrac) >> 4) + g10)-((((g01-g00) * dsfrac) >> 4) + g00)) * dtfrac) >> 4) + ((((g01-g00) * dsfrac) >> 4) + g00)) * (1.0f / 32768.0f);
853 ambientcolor[2] += (float) ((((((((b11-b10) * dsfrac) >> 4) + b10)-((((b01-b00) * dsfrac) >> 4) + b00)) * dtfrac) >> 4) + ((((b01-b00) * dsfrac) >> 4) + b00)) * (1.0f / 32768.0f);
854 return true; // success
860 node = node->children[side ^ 1];
862 distz = endz - startz;
867 void Mod_Q1BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
869 Mod_Q1BSP_LightPoint_RecursiveBSPNode(ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2], p[2] - 65536);
872 static void Mod_Q1BSP_DecompressVis(const qbyte *in, const qbyte *inend, qbyte *out, qbyte *outend)
875 qbyte *outstart = out;
880 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
890 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun (during zero-run) on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
893 for (c = *in++;c > 0;c--)
897 Con_Printf("Mod_Q1BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
910 A sky texture is 256*128, with the right side being a masked overlay
913 void R_Q1BSP_LoadSplitSky (qbyte *src, int width, int height, int bytesperpixel)
916 unsigned solidpixels[128*128], alphapixels[128*128];
918 // if sky isn't the right size, just use it as a solid layer
919 if (width != 256 || height != 128)
921 loadmodel->brush.solidskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_solidtexture", width, height, src, bytesperpixel == 4 ? TEXTYPE_RGBA : TEXTYPE_PALETTE, TEXF_PRECACHE, bytesperpixel == 1 ? palette_complete : NULL);
922 loadmodel->brush.alphaskytexture = NULL;;
926 if (bytesperpixel == 4)
928 for (i = 0;i < 128;i++)
930 for (j = 0;j < 128;j++)
932 solidpixels[(i*128) + j] = ((unsigned *)src)[i*256+j+128];
933 alphapixels[(i*128) + j] = ((unsigned *)src)[i*256+j];
939 // make an average value for the back to avoid
940 // a fringe on the top level
949 for (i = 0;i < 128;i++)
951 for (j = 0;j < 128;j++)
953 rgba.i = palette_complete[src[i*256 + j + 128]];
959 rgba.b[0] = r/(128*128);
960 rgba.b[1] = g/(128*128);
961 rgba.b[2] = b/(128*128);
963 for (i = 0;i < 128;i++)
965 for (j = 0;j < 128;j++)
967 solidpixels[(i*128) + j] = palette_complete[src[i*256 + j + 128]];
968 alphapixels[(i*128) + j] = (p = src[i*256 + j]) ? palette_complete[p] : rgba.i;
973 loadmodel->brush.solidskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_solidtexture", 128, 128, (qbyte *) solidpixels, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
974 loadmodel->brush.alphaskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_alphatexture", 128, 128, (qbyte *) alphapixels, TEXTYPE_RGBA, TEXF_ALPHA | TEXF_PRECACHE, NULL);
977 static void Mod_Q1BSP_LoadTextures(lump_t *l)
979 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
981 texture_t *tx, *tx2, *anims[10], *altanims[10];
983 qbyte *data, *mtdata;
986 loadmodel->brush.data_textures = NULL;
988 // add two slots for notexture walls and notexture liquids
991 m = (dmiptexlump_t *)(mod_base + l->fileofs);
992 m->nummiptex = LittleLong (m->nummiptex);
993 loadmodel->brush.num_textures = m->nummiptex + 2;
998 loadmodel->brush.num_textures = 2;
1001 loadmodel->brush.data_textures = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_textures * sizeof(texture_t));
1003 // fill out all slots with notexture
1004 for (i = 0, tx = loadmodel->brush.data_textures;i < loadmodel->brush.num_textures;i++, tx++)
1006 strcpy(tx->name, "NO TEXTURE FOUND");
1009 tx->skin.base = r_texture_notexture;
1010 if (i == loadmodel->brush.num_textures - 1)
1012 tx->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES;
1013 tx->supercontents = SUPERCONTENTS_WATER;
1017 tx->basematerialflags |= MATERIALFLAG_WALL;
1018 tx->supercontents = SUPERCONTENTS_SOLID;
1020 tx->basematerialflags = 0;
1021 tx->currentframe = tx;
1027 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1029 // LordHavoc: mostly rewritten map texture loader
1030 for (i = 0;i < m->nummiptex;i++)
1032 dofs[i] = LittleLong(dofs[i]);
1033 if (dofs[i] == -1 || r_nosurftextures.integer)
1035 dmiptex = (miptex_t *)((qbyte *)m + dofs[i]);
1037 // make sure name is no more than 15 characters
1038 for (j = 0;dmiptex->name[j] && j < 15;j++)
1039 name[j] = dmiptex->name[j];
1042 mtwidth = LittleLong(dmiptex->width);
1043 mtheight = LittleLong(dmiptex->height);
1045 j = LittleLong(dmiptex->offsets[0]);
1049 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1051 Con_Printf("Texture \"%s\" in \"%s\"is corrupt or incomplete\n", dmiptex->name, loadmodel->name);
1054 mtdata = (qbyte *)dmiptex + j;
1057 if ((mtwidth & 15) || (mtheight & 15))
1058 Con_Printf("warning: texture \"%s\" in \"%s\" is not 16 aligned\n", dmiptex->name, loadmodel->name);
1060 // LordHavoc: force all names to lowercase
1061 for (j = 0;name[j];j++)
1062 if (name[j] >= 'A' && name[j] <= 'Z')
1063 name[j] += 'a' - 'A';
1065 tx = loadmodel->brush.data_textures + i;
1066 strcpy(tx->name, name);
1067 tx->width = mtwidth;
1068 tx->height = mtheight;
1072 sprintf(tx->name, "unnamed%i", i);
1073 Con_Printf("warning: unnamed texture in %s, renaming to %s\n", loadmodel->name, tx->name);
1076 // LordHavoc: HL sky textures are entirely different than quake
1077 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == 256 && mtheight == 128)
1079 if (loadmodel->isworldmodel)
1081 data = loadimagepixels(tx->name, false, 0, 0);
1084 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1087 else if (mtdata != NULL)
1088 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1093 if (!Mod_LoadSkinFrame(&tx->skin, tx->name, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, false, tx->name[0] != '*', true))
1095 // did not find external texture, load it from the bsp or wad3
1096 if (loadmodel->brush.ishlbsp)
1098 // internal texture overrides wad
1099 qbyte *pixels, *freepixels, *fogpixels;
1100 pixels = freepixels = NULL;
1102 pixels = W_ConvertWAD3Texture(dmiptex);
1104 pixels = freepixels = W_GetTexture(tx->name);
1107 tx->width = image_width;
1108 tx->height = image_height;
1109 tx->skin.base = tx->skin.merged = R_LoadTexture2D(loadmodel->texturepool, tx->name, image_width, image_height, pixels, TEXTYPE_RGBA, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, NULL);
1110 if (Image_CheckAlpha(pixels, image_width * image_height, true))
1112 fogpixels = Mem_Alloc(tempmempool, image_width * image_height * 4);
1113 for (j = 0;j < image_width * image_height * 4;j += 4)
1115 fogpixels[j + 0] = 255;
1116 fogpixels[j + 1] = 255;
1117 fogpixels[j + 2] = 255;
1118 fogpixels[j + 3] = pixels[j + 3];
1120 tx->skin.fog = R_LoadTexture2D(loadmodel->texturepool, tx->name, image_width, image_height, pixels, TEXTYPE_RGBA, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, NULL);
1121 Mem_Free(fogpixels);
1125 Mem_Free(freepixels);
1127 else if (mtdata) // texture included
1128 Mod_LoadSkinFrame_Internal(&tx->skin, tx->name, TEXF_MIPMAP | TEXF_PRECACHE | TEXF_PICMIP, false, tx->name[0] != '*', tx->name[0] != '*' && r_fullbrights.integer, mtdata, tx->width, tx->height);
1131 if (tx->skin.base == NULL)
1136 tx->skin.base = r_texture_notexture;
1139 tx->basematerialflags = 0;
1140 if (tx->name[0] == '*')
1142 // turb does not block movement
1143 tx->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES;
1144 // LordHavoc: some turbulent textures should be fullbright and solid
1145 if (!strncmp(tx->name,"*lava",5)
1146 || !strncmp(tx->name,"*teleport",9)
1147 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1148 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
1150 tx->basematerialflags |= MATERIALFLAG_WATERALPHA;
1151 if (!strncmp(tx->name, "*lava", 5))
1152 tx->supercontents = SUPERCONTENTS_LAVA;
1153 else if (!strncmp(tx->name, "*slime", 6))
1154 tx->supercontents = SUPERCONTENTS_SLIME;
1156 tx->supercontents = SUPERCONTENTS_WATER;
1158 else if (tx->name[0] == 's' && tx->name[1] == 'k' && tx->name[2] == 'y')
1160 tx->supercontents = SUPERCONTENTS_SKY;
1161 tx->basematerialflags |= MATERIALFLAG_SKY;
1165 tx->supercontents = SUPERCONTENTS_SOLID;
1166 tx->basematerialflags |= MATERIALFLAG_WALL;
1169 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
1171 // start out with no animation
1172 tx->currentframe = tx;
1175 // sequence the animations
1176 for (i = 0;i < m->nummiptex;i++)
1178 tx = loadmodel->brush.data_textures + i;
1179 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1181 if (tx->anim_total[0] || tx->anim_total[1])
1182 continue; // already sequenced
1184 // find the number of frames in the animation
1185 memset(anims, 0, sizeof(anims));
1186 memset(altanims, 0, sizeof(altanims));
1188 for (j = i;j < m->nummiptex;j++)
1190 tx2 = loadmodel->brush.data_textures + j;
1191 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1195 if (num >= '0' && num <= '9')
1196 anims[num - '0'] = tx2;
1197 else if (num >= 'a' && num <= 'j')
1198 altanims[num - 'a'] = tx2;
1200 Con_Printf("Bad animating texture %s\n", tx->name);
1204 for (j = 0;j < 10;j++)
1211 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1214 for (j = 0;j < max;j++)
1218 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1222 for (j = 0;j < altmax;j++)
1226 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1235 // if there is no alternate animation, duplicate the primary
1236 // animation into the alternate
1238 for (k = 0;k < 10;k++)
1239 altanims[k] = anims[k];
1242 // link together the primary animation
1243 for (j = 0;j < max;j++)
1246 tx2->animated = true;
1247 tx2->anim_total[0] = max;
1248 tx2->anim_total[1] = altmax;
1249 for (k = 0;k < 10;k++)
1251 tx2->anim_frames[0][k] = anims[k];
1252 tx2->anim_frames[1][k] = altanims[k];
1256 // if there really is an alternate anim...
1257 if (anims[0] != altanims[0])
1259 // link together the alternate animation
1260 for (j = 0;j < altmax;j++)
1263 tx2->animated = true;
1264 // the primary/alternate are reversed here
1265 tx2->anim_total[0] = altmax;
1266 tx2->anim_total[1] = max;
1267 for (k = 0;k < 10;k++)
1269 tx2->anim_frames[0][k] = altanims[k];
1270 tx2->anim_frames[1][k] = anims[k];
1277 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1280 qbyte *in, *out, *data, d;
1281 char litfilename[1024];
1282 loadmodel->brushq1.lightdata = NULL;
1283 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1285 loadmodel->brushq1.lightdata = Mem_Alloc(loadmodel->mempool, l->filelen);
1286 for (i=0; i<l->filelen; i++)
1287 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1289 else // LordHavoc: bsp version 29 (normal white lighting)
1291 // LordHavoc: hope is not lost yet, check for a .lit file to load
1292 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1293 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1294 strlcat (litfilename, ".lit", sizeof (litfilename));
1295 data = (qbyte*) FS_LoadFile(litfilename, tempmempool, false);
1298 if (fs_filesize > 8 && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1300 i = LittleLong(((int *)data)[1]);
1303 Con_DPrintf("loaded %s\n", litfilename);
1304 loadmodel->brushq1.lightdata = Mem_Alloc(loadmodel->mempool, fs_filesize - 8);
1305 memcpy(loadmodel->brushq1.lightdata, data + 8, fs_filesize - 8);
1311 Con_Printf("Unknown .lit file version (%d)\n", i);
1317 if (fs_filesize == 8)
1318 Con_Print("Empty .lit file, ignoring\n");
1320 Con_Print("Corrupt .lit file (old version?), ignoring\n");
1324 // LordHavoc: oh well, expand the white lighting data
1327 loadmodel->brushq1.lightdata = Mem_Alloc(loadmodel->mempool, l->filelen*3);
1328 in = loadmodel->brushq1.lightdata + l->filelen*2; // place the file at the end, so it will not be overwritten until the very last write
1329 out = loadmodel->brushq1.lightdata;
1330 memcpy(in, mod_base + l->fileofs, l->filelen);
1331 for (i = 0;i < l->filelen;i++)
1341 static void Mod_Q1BSP_LoadLightList(void)
1343 int a, n, numlights;
1344 char tempchar, *s, *t, *lightsstring, lightsfilename[1024];
1347 strlcpy (lightsfilename, loadmodel->name, sizeof (lightsfilename));
1348 FS_StripExtension (lightsfilename, lightsfilename, sizeof(lightsfilename));
1349 strlcat (lightsfilename, ".lights", sizeof (lightsfilename));
1350 s = lightsstring = (char *) FS_LoadFile(lightsfilename, tempmempool, false);
1356 while (*s && *s != '\n' && *s != '\r')
1360 Mem_Free(lightsstring);
1361 Con_Printf("lights file must end with a newline\n");
1367 loadmodel->brushq1.lights = Mem_Alloc(loadmodel->mempool, numlights * sizeof(mlight_t));
1370 while (*s && n < numlights)
1373 while (*s && *s != '\n' && *s != '\r')
1377 Con_Printf("misparsed lights file!\n");
1380 e = loadmodel->brushq1.lights + n;
1383 a = sscanf(t, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d", &e->origin[0], &e->origin[1], &e->origin[2], &e->falloff, &e->light[0], &e->light[1], &e->light[2], &e->subtract, &e->spotdir[0], &e->spotdir[1], &e->spotdir[2], &e->spotcone, &e->distbias, &e->style);
1387 Con_Printf("invalid lights file, found %d parameters on line %i, should be 14 parameters (origin[0] origin[1] origin[2] falloff light[0] light[1] light[2] subtract spotdir[0] spotdir[1] spotdir[2] spotcone distancebias style)\n", a, n + 1);
1397 Con_Printf("misparsed lights file!\n");
1398 loadmodel->brushq1.numlights = numlights;
1399 Mem_Free(lightsstring);
1403 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1405 loadmodel->brushq1.num_compressedpvs = 0;
1406 loadmodel->brushq1.data_compressedpvs = NULL;
1409 loadmodel->brushq1.num_compressedpvs = l->filelen;
1410 loadmodel->brushq1.data_compressedpvs = Mem_Alloc(loadmodel->mempool, l->filelen);
1411 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1414 // used only for HalfLife maps
1415 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1417 char key[128], value[4096];
1422 if (!COM_ParseToken(&data, false))
1424 if (com_token[0] != '{')
1428 if (!COM_ParseToken(&data, false))
1430 if (com_token[0] == '}')
1431 break; // end of worldspawn
1432 if (com_token[0] == '_')
1433 strcpy(key, com_token + 1);
1435 strcpy(key, com_token);
1436 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1437 key[strlen(key)-1] = 0;
1438 if (!COM_ParseToken(&data, false))
1440 strcpy(value, com_token);
1441 if (!strcmp("wad", key)) // for HalfLife maps
1443 if (loadmodel->brush.ishlbsp)
1446 for (i = 0;i < 4096;i++)
1447 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1453 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1454 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1456 else if (value[i] == ';' || value[i] == 0)
1460 strcpy(wadname, "textures/");
1461 strcat(wadname, &value[j]);
1462 W_LoadTextureWadFile(wadname, false);
1474 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1476 loadmodel->brush.entities = NULL;
1479 loadmodel->brush.entities = Mem_Alloc(loadmodel->mempool, l->filelen);
1480 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1481 if (loadmodel->brush.ishlbsp)
1482 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1486 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1492 in = (void *)(mod_base + l->fileofs);
1493 if (l->filelen % sizeof(*in))
1494 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1495 count = l->filelen / sizeof(*in);
1496 out = Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1498 loadmodel->brushq1.vertexes = out;
1499 loadmodel->brushq1.numvertexes = count;
1501 for ( i=0 ; i<count ; i++, in++, out++)
1503 out->position[0] = LittleFloat(in->point[0]);
1504 out->position[1] = LittleFloat(in->point[1]);
1505 out->position[2] = LittleFloat(in->point[2]);
1509 static void Mod_Q1BSP_LoadSubmodels(lump_t *l)
1515 in = (void *)(mod_base + l->fileofs);
1516 if (l->filelen % sizeof(*in))
1517 Host_Error("Mod_Q1BSP_LoadSubmodels: funny lump size in %s",loadmodel->name);
1518 count = l->filelen / sizeof(*in);
1519 out = Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1521 loadmodel->brushq1.submodels = out;
1522 loadmodel->brush.numsubmodels = count;
1524 for ( i=0 ; i<count ; i++, in++, out++)
1526 for (j=0 ; j<3 ; j++)
1528 // spread the mins / maxs by a pixel
1529 out->mins[j] = LittleFloat(in->mins[j]) - 1;
1530 out->maxs[j] = LittleFloat(in->maxs[j]) + 1;
1531 out->origin[j] = LittleFloat(in->origin[j]);
1533 for (j=0 ; j<MAX_MAP_HULLS ; j++)
1534 out->headnode[j] = LittleLong(in->headnode[j]);
1535 out->visleafs = LittleLong(in->visleafs);
1536 out->firstface = LittleLong(in->firstface);
1537 out->numfaces = LittleLong(in->numfaces);
1541 static void Mod_Q1BSP_LoadEdges(lump_t *l)
1547 in = (void *)(mod_base + l->fileofs);
1548 if (l->filelen % sizeof(*in))
1549 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
1550 count = l->filelen / sizeof(*in);
1551 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
1553 loadmodel->brushq1.edges = out;
1554 loadmodel->brushq1.numedges = count;
1556 for ( i=0 ; i<count ; i++, in++, out++)
1558 out->v[0] = (unsigned short)LittleShort(in->v[0]);
1559 out->v[1] = (unsigned short)LittleShort(in->v[1]);
1563 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
1567 int i, j, k, count, miptex;
1569 in = (void *)(mod_base + l->fileofs);
1570 if (l->filelen % sizeof(*in))
1571 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
1572 count = l->filelen / sizeof(*in);
1573 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
1575 loadmodel->brushq1.texinfo = out;
1576 loadmodel->brushq1.numtexinfo = count;
1578 for (i = 0;i < count;i++, in++, out++)
1580 for (k = 0;k < 2;k++)
1581 for (j = 0;j < 4;j++)
1582 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
1584 miptex = LittleLong(in->miptex);
1585 out->flags = LittleLong(in->flags);
1587 out->texture = NULL;
1588 if (loadmodel->brush.data_textures)
1590 if ((unsigned int) miptex >= (unsigned int) loadmodel->brush.num_textures)
1591 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->brush.num_textures);
1593 out->texture = loadmodel->brush.data_textures + miptex;
1595 if (out->flags & TEX_SPECIAL)
1597 // if texture chosen is NULL or the shader needs a lightmap,
1598 // force to notexture water shader
1599 if (out->texture == NULL || out->texture->basematerialflags & MATERIALFLAG_WALL)
1600 out->texture = loadmodel->brush.data_textures + (loadmodel->brush.num_textures - 1);
1604 // if texture chosen is NULL, force to notexture
1605 if (out->texture == NULL)
1606 out->texture = loadmodel->brush.data_textures + (loadmodel->brush.num_textures - 2);
1612 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
1617 mins[0] = mins[1] = mins[2] = 9999;
1618 maxs[0] = maxs[1] = maxs[2] = -9999;
1620 for (i = 0;i < numverts;i++)
1622 for (j = 0;j < 3;j++, v++)
1632 #define MAX_SUBDIVPOLYTRIANGLES 4096
1633 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
1635 static int subdivpolyverts, subdivpolytriangles;
1636 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
1637 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
1639 static int subdivpolylookupvert(vec3_t v)
1642 for (i = 0;i < subdivpolyverts;i++)
1643 if (subdivpolyvert[i][0] == v[0]
1644 && subdivpolyvert[i][1] == v[1]
1645 && subdivpolyvert[i][2] == v[2])
1647 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
1648 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
1649 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
1650 return subdivpolyverts++;
1653 static void SubdividePolygon(int numverts, float *verts)
1655 int i, i1, i2, i3, f, b, c, p;
1656 vec3_t mins, maxs, front[256], back[256];
1657 float m, *pv, *cv, dist[256], frac;
1660 Host_Error("SubdividePolygon: ran out of verts in buffer");
1662 BoundPoly(numverts, verts, mins, maxs);
1664 for (i = 0;i < 3;i++)
1666 m = (mins[i] + maxs[i]) * 0.5;
1667 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
1668 if (maxs[i] - m < 8)
1670 if (m - mins[i] < 8)
1674 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
1675 dist[c] = cv[i] - m;
1678 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
1682 VectorCopy(pv, front[f]);
1687 VectorCopy(pv, back[b]);
1690 if (dist[p] == 0 || dist[c] == 0)
1692 if ((dist[p] > 0) != (dist[c] > 0) )
1695 frac = dist[p] / (dist[p] - dist[c]);
1696 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
1697 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
1698 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
1704 SubdividePolygon(f, front[0]);
1705 SubdividePolygon(b, back[0]);
1709 i1 = subdivpolylookupvert(verts);
1710 i2 = subdivpolylookupvert(verts + 3);
1711 for (i = 2;i < numverts;i++)
1713 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
1715 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
1719 i3 = subdivpolylookupvert(verts + i * 3);
1720 subdivpolyindex[subdivpolytriangles][0] = i1;
1721 subdivpolyindex[subdivpolytriangles][1] = i2;
1722 subdivpolyindex[subdivpolytriangles][2] = i3;
1724 subdivpolytriangles++;
1728 //Breaks a polygon up along axial 64 unit
1729 //boundaries so that turbulent and sky warps
1730 //can be done reasonably.
1731 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
1737 subdivpolytriangles = 0;
1738 subdivpolyverts = 0;
1739 SubdividePolygon(surface->mesh.num_vertices, surface->mesh.data_vertex3f);
1740 if (subdivpolytriangles < 1)
1741 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?\n");
1743 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
1744 mesh->num_vertices = subdivpolyverts;
1745 mesh->num_triangles = subdivpolytriangles;
1746 mesh->vertex = (surfvertex_t *)(mesh + 1);
1747 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
1748 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
1750 for (i = 0;i < mesh->num_triangles;i++)
1751 for (j = 0;j < 3;j++)
1752 mesh->index[i*3+j] = subdivpolyindex[i][j];
1754 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
1756 VectorCopy(subdivpolyvert[i], v->v);
1757 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
1758 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
1763 static void Mod_Q1BSP_LoadFaces(lump_t *l)
1766 msurface_t *surface;
1767 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris;
1768 float texmins[2], texmaxs[2], val;
1770 in = (void *)(mod_base + l->fileofs);
1771 if (l->filelen % sizeof(*in))
1772 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
1773 count = l->filelen / sizeof(*in);
1774 loadmodel->brush.data_surfaces = Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
1775 loadmodel->brush.data_surfaces_lightmapinfo = Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
1777 loadmodel->brush.num_surfaces = count;
1781 for (surfacenum = 0, in = (void *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
1783 numedges = LittleShort(in->numedges);
1784 totalverts += numedges;
1785 totaltris += numedges - 2;
1788 // TODO: split up into multiple meshes as needed to avoid exceeding 65536
1790 loadmodel->nummeshes = 1;
1791 loadmodel->meshlist = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *));
1792 loadmodel->meshlist[0] = Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, true, false);
1796 for (surfacenum = 0, in = (void *)(mod_base + l->fileofs), surface = loadmodel->brush.data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
1798 surface->lightmapinfo = loadmodel->brush.data_surfaces_lightmapinfo + surfacenum;
1800 // FIXME: validate edges, texinfo, etc?
1801 firstedge = LittleLong(in->firstedge);
1802 numedges = LittleShort(in->numedges);
1803 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)
1804 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)\n", firstedge, numedges, loadmodel->brushq1.numsurfedges);
1805 i = LittleShort(in->texinfo);
1806 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
1807 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)\n", i, loadmodel->brushq1.numtexinfo);
1808 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
1809 surface->texture = surface->lightmapinfo->texinfo->texture;
1811 planenum = LittleShort(in->planenum);
1812 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
1813 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)\n", planenum, loadmodel->brush.num_planes);
1815 //surface->flags = surface->texture->flags;
1816 //if (LittleShort(in->side))
1817 // surface->flags |= SURF_PLANEBACK;
1818 //surface->plane = loadmodel->brush.data_planes + planenum;
1820 surface->mesh.num_vertices = numedges;
1821 surface->mesh.num_triangles = numedges - 2;
1822 surface->mesh.data_vertex3f = loadmodel->meshlist[0]->data_vertex3f + totalverts * 3;
1823 surface->mesh.data_texcoordtexture2f = loadmodel->meshlist[0]->data_texcoordtexture2f + totalverts * 2;
1824 surface->mesh.data_texcoordlightmap2f = loadmodel->meshlist[0]->data_texcoordlightmap2f + totalverts * 2;
1825 surface->mesh.data_texcoorddetail2f = loadmodel->meshlist[0]->data_texcoorddetail2f + totalverts * 2;
1826 surface->mesh.data_svector3f = loadmodel->meshlist[0]->data_svector3f + totalverts * 3;
1827 surface->mesh.data_tvector3f = loadmodel->meshlist[0]->data_tvector3f + totalverts * 3;
1828 surface->mesh.data_normal3f = loadmodel->meshlist[0]->data_normal3f + totalverts * 3;
1829 surface->mesh.data_lightmapoffsets = loadmodel->meshlist[0]->data_lightmapoffsets + totalverts;
1830 surface->mesh.data_element3i = loadmodel->meshlist[0]->data_element3i + totaltris * 3;
1831 surface->mesh.data_neighbor3i = loadmodel->meshlist[0]->data_neighbor3i + totaltris * 3;
1832 totalverts += numedges;
1833 totaltris += numedges - 2;
1835 // convert edges back to a normal polygon
1836 for (i = 0;i < surface->mesh.num_vertices;i++)
1838 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
1841 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, surface->mesh.data_vertex3f + i * 3);
1843 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, surface->mesh.data_vertex3f + i * 3);
1844 s = DotProduct((surface->mesh.data_vertex3f + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
1845 t = DotProduct((surface->mesh.data_vertex3f + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
1846 surface->mesh.data_texcoordtexture2f[i * 2 + 0] = s / surface->texture->width;
1847 surface->mesh.data_texcoordtexture2f[i * 2 + 1] = t / surface->texture->height;
1848 surface->mesh.data_texcoorddetail2f[i * 2 + 0] = s * (1.0f / 16.0f);
1849 surface->mesh.data_texcoorddetail2f[i * 2 + 1] = t * (1.0f / 16.0f);
1850 surface->mesh.data_texcoordlightmap2f[i * 2 + 0] = 0;
1851 surface->mesh.data_texcoordlightmap2f[i * 2 + 1] = 0;
1852 surface->mesh.data_lightmapoffsets[i] = 0;
1855 for (i = 0;i < surface->mesh.num_triangles;i++)
1857 surface->mesh.data_element3i[i * 3 + 0] = 0;
1858 surface->mesh.data_element3i[i * 3 + 1] = i + 1;
1859 surface->mesh.data_element3i[i * 3 + 2] = i + 2;
1862 // compile additional data about the surface geometry
1863 Mod_BuildTriangleNeighbors(surface->mesh.data_neighbor3i, surface->mesh.data_element3i, surface->mesh.num_triangles);
1864 Mod_BuildTextureVectorsAndNormals(surface->mesh.num_vertices, surface->mesh.num_triangles, surface->mesh.data_vertex3f, surface->mesh.data_texcoordtexture2f, surface->mesh.data_element3i, surface->mesh.data_svector3f, surface->mesh.data_tvector3f, surface->mesh.data_normal3f);
1865 BoxFromPoints(surface->mins, surface->maxs, surface->mesh.num_vertices, surface->mesh.data_vertex3f);
1867 // generate surface extents information
1868 texmins[0] = texmaxs[0] = DotProduct(surface->mesh.data_vertex3f, surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
1869 texmins[1] = texmaxs[1] = DotProduct(surface->mesh.data_vertex3f, surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
1870 for (i = 1;i < surface->mesh.num_vertices;i++)
1872 for (j = 0;j < 2;j++)
1874 val = DotProduct(surface->mesh.data_vertex3f + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
1875 texmins[j] = min(texmins[j], val);
1876 texmaxs[j] = max(texmaxs[j], val);
1879 for (i = 0;i < 2;i++)
1881 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
1882 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
1885 smax = surface->lightmapinfo->extents[0] >> 4;
1886 tmax = surface->lightmapinfo->extents[1] >> 4;
1887 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
1888 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
1891 for (i = 0;i < MAXLIGHTMAPS;i++)
1892 surface->lightmapinfo->styles[i] = in->styles[i];
1893 // force lightmap upload on first time seeing the surface
1894 surface->cached_dlight = true;
1895 surface->lightmapinfo->lightmaptexturestride = 0;
1896 surface->lightmaptexture = NULL;
1897 i = LittleLong(in->lightofs);
1900 surface->lightmapinfo->samples = NULL;
1901 // give non-lightmapped water a 1x white lightmap
1902 if ((surface->texture->basematerialflags & MATERIALFLAG_WATER) && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
1904 surface->lightmapinfo->samples = Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
1905 surface->lightmapinfo->styles[0] = 0;
1906 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
1909 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
1910 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
1911 else // LordHavoc: white lighting (bsp version 29)
1912 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
1914 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
1917 float u, v, ubase, vbase, uscale, vscale;
1919 if (ssize > 256 || tsize > 256)
1920 Host_Error("Bad surface extents");
1921 // stainmap for permanent marks on walls
1922 surface->lightmapinfo->stainsamples = Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
1924 memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
1926 if (r_miplightmaps.integer)
1928 surface->lightmapinfo->lightmaptexturestride = ssize;
1929 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);
1933 surface->lightmapinfo->lightmaptexturestride = R_CompatibleFragmentWidth(ssize, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, 0);
1934 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);
1936 R_FragmentLocation(surface->lightmaptexture, NULL, NULL, &ubase, &vbase, &uscale, &vscale);
1937 uscale = (uscale - ubase) / ssize;
1938 vscale = (vscale - vbase) / tsize;
1940 for (i = 0;i < surface->mesh.num_vertices;i++)
1942 u = ((DotProduct((surface->mesh.data_vertex3f + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3]) + 8 - surface->lightmapinfo->texturemins[0]) * (1.0 / 16.0);
1943 v = ((DotProduct((surface->mesh.data_vertex3f + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3]) + 8 - surface->lightmapinfo->texturemins[1]) * (1.0 / 16.0);
1944 surface->mesh.data_texcoordlightmap2f[i * 2 + 0] = u * uscale + ubase;
1945 surface->mesh.data_texcoordlightmap2f[i * 2 + 1] = v * vscale + vbase;
1946 // LordHavoc: calc lightmap data offset for vertex lighting to use
1949 surface->mesh.data_lightmapoffsets[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
1955 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
1958 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion\n");
1959 node->parent = parent;
1962 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
1963 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
1967 static void Mod_Q1BSP_LoadNodes(lump_t *l)
1973 in = (void *)(mod_base + l->fileofs);
1974 if (l->filelen % sizeof(*in))
1975 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
1976 count = l->filelen / sizeof(*in);
1977 out = Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1979 loadmodel->brush.data_nodes = out;
1980 loadmodel->brush.num_nodes = count;
1982 for ( i=0 ; i<count ; i++, in++, out++)
1984 for (j=0 ; j<3 ; j++)
1986 out->mins[j] = LittleShort(in->mins[j]);
1987 out->maxs[j] = LittleShort(in->maxs[j]);
1990 p = LittleLong(in->planenum);
1991 out->plane = loadmodel->brush.data_planes + p;
1993 out->firstsurface = LittleShort(in->firstface);
1994 out->numsurfaces = LittleShort(in->numfaces);
1996 for (j=0 ; j<2 ; j++)
1998 p = LittleShort(in->children[j]);
2000 out->children[j] = loadmodel->brush.data_nodes + p;
2002 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + (-1 - p));
2006 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2009 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2015 in = (void *)(mod_base + l->fileofs);
2016 if (l->filelen % sizeof(*in))
2017 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2018 count = l->filelen / sizeof(*in);
2019 out = Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2021 loadmodel->brush.data_leafs = out;
2022 loadmodel->brush.num_leafs = count;
2023 // get visleafs from the submodel data
2024 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2025 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2026 loadmodel->brush.data_pvsclusters = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2027 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2029 for ( i=0 ; i<count ; i++, in++, out++)
2031 for (j=0 ; j<3 ; j++)
2033 out->mins[j] = LittleShort(in->mins[j]);
2034 out->maxs[j] = LittleShort(in->maxs[j]);
2037 // FIXME: this function could really benefit from some error checking
2039 out->contents = LittleLong(in->contents);
2041 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + LittleShort(in->firstmarksurface);
2042 out->numleafsurfaces = LittleShort(in->nummarksurfaces);
2043 if (out->firstleafsurface < 0 || LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2045 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);
2046 out->firstleafsurface = NULL;
2047 out->numleafsurfaces = 0;
2050 out->clusterindex = i - 1;
2051 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2052 out->clusterindex = -1;
2054 p = LittleLong(in->visofs);
2055 // ignore visofs errors on leaf 0 (solid)
2056 if (p >= 0 && out->clusterindex >= 0)
2058 if (p >= loadmodel->brushq1.num_compressedpvs)
2059 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2061 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);
2064 for (j = 0;j < 4;j++)
2065 out->ambient_sound_level[j] = in->ambient_level[j];
2067 // FIXME: Insert caustics here
2071 static void Mod_Q1BSP_LoadClipnodes(lump_t *l)
2073 dclipnode_t *in, *out;
2077 in = (void *)(mod_base + l->fileofs);
2078 if (l->filelen % sizeof(*in))
2079 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2080 count = l->filelen / sizeof(*in);
2081 out = Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2083 loadmodel->brushq1.clipnodes = out;
2084 loadmodel->brushq1.numclipnodes = count;
2086 if (loadmodel->brush.ishlbsp)
2088 hull = &loadmodel->brushq1.hulls[1];
2089 hull->clipnodes = out;
2090 hull->firstclipnode = 0;
2091 hull->lastclipnode = count-1;
2092 hull->planes = loadmodel->brush.data_planes;
2093 hull->clip_mins[0] = -16;
2094 hull->clip_mins[1] = -16;
2095 hull->clip_mins[2] = -36;
2096 hull->clip_maxs[0] = 16;
2097 hull->clip_maxs[1] = 16;
2098 hull->clip_maxs[2] = 36;
2099 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2101 hull = &loadmodel->brushq1.hulls[2];
2102 hull->clipnodes = out;
2103 hull->firstclipnode = 0;
2104 hull->lastclipnode = count-1;
2105 hull->planes = loadmodel->brush.data_planes;
2106 hull->clip_mins[0] = -32;
2107 hull->clip_mins[1] = -32;
2108 hull->clip_mins[2] = -32;
2109 hull->clip_maxs[0] = 32;
2110 hull->clip_maxs[1] = 32;
2111 hull->clip_maxs[2] = 32;
2112 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2114 hull = &loadmodel->brushq1.hulls[3];
2115 hull->clipnodes = out;
2116 hull->firstclipnode = 0;
2117 hull->lastclipnode = count-1;
2118 hull->planes = loadmodel->brush.data_planes;
2119 hull->clip_mins[0] = -16;
2120 hull->clip_mins[1] = -16;
2121 hull->clip_mins[2] = -18;
2122 hull->clip_maxs[0] = 16;
2123 hull->clip_maxs[1] = 16;
2124 hull->clip_maxs[2] = 18;
2125 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2129 hull = &loadmodel->brushq1.hulls[1];
2130 hull->clipnodes = out;
2131 hull->firstclipnode = 0;
2132 hull->lastclipnode = count-1;
2133 hull->planes = loadmodel->brush.data_planes;
2134 hull->clip_mins[0] = -16;
2135 hull->clip_mins[1] = -16;
2136 hull->clip_mins[2] = -24;
2137 hull->clip_maxs[0] = 16;
2138 hull->clip_maxs[1] = 16;
2139 hull->clip_maxs[2] = 32;
2140 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2142 hull = &loadmodel->brushq1.hulls[2];
2143 hull->clipnodes = out;
2144 hull->firstclipnode = 0;
2145 hull->lastclipnode = count-1;
2146 hull->planes = loadmodel->brush.data_planes;
2147 hull->clip_mins[0] = -32;
2148 hull->clip_mins[1] = -32;
2149 hull->clip_mins[2] = -24;
2150 hull->clip_maxs[0] = 32;
2151 hull->clip_maxs[1] = 32;
2152 hull->clip_maxs[2] = 64;
2153 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2156 for (i=0 ; i<count ; i++, out++, in++)
2158 out->planenum = LittleLong(in->planenum);
2159 out->children[0] = LittleShort(in->children[0]);
2160 out->children[1] = LittleShort(in->children[1]);
2161 if (out->children[0] >= count || out->children[1] >= count)
2162 Host_Error("Corrupt clipping hull(out of range child)\n");
2166 //Duplicate the drawing hull structure as a clipping hull
2167 static void Mod_Q1BSP_MakeHull0(void)
2174 hull = &loadmodel->brushq1.hulls[0];
2176 in = loadmodel->brush.data_nodes;
2177 out = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(dclipnode_t));
2179 hull->clipnodes = out;
2180 hull->firstclipnode = 0;
2181 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2182 hull->planes = loadmodel->brush.data_planes;
2184 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2186 out->planenum = in->plane - loadmodel->brush.data_planes;
2187 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2188 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2192 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2197 in = (void *)(mod_base + l->fileofs);
2198 if (l->filelen % sizeof(*in))
2199 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2200 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2201 loadmodel->brush.data_leafsurfaces = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2203 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2205 j = (unsigned) LittleShort(in[i]);
2206 if (j >= loadmodel->brush.num_surfaces)
2207 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2208 loadmodel->brush.data_leafsurfaces[i] = j;
2212 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2217 in = (void *)(mod_base + l->fileofs);
2218 if (l->filelen % sizeof(*in))
2219 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2220 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2221 loadmodel->brushq1.surfedges = Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2223 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2224 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2228 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2234 in = (void *)(mod_base + l->fileofs);
2235 if (l->filelen % sizeof(*in))
2236 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2238 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2239 loadmodel->brush.data_planes = out = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2241 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2243 out->normal[0] = LittleFloat(in->normal[0]);
2244 out->normal[1] = LittleFloat(in->normal[1]);
2245 out->normal[2] = LittleFloat(in->normal[2]);
2246 out->dist = LittleFloat(in->dist);
2252 static void Mod_Q1BSP_LoadMapBrushes(void)
2256 int submodel, numbrushes;
2257 qboolean firstbrush;
2258 char *text, *maptext;
2259 char mapfilename[MAX_QPATH];
2260 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2261 strlcat (mapfilename, ".map", sizeof (mapfilename));
2262 maptext = (qbyte*) FS_LoadFile(mapfilename, tempmempool, false);
2266 if (!COM_ParseToken(&data, false))
2271 if (!COM_ParseToken(&data, false))
2273 if (com_token[0] != '{')
2279 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2282 if (!COM_ParseToken(&data, false))
2284 if (com_token[0] == '}')
2285 break; // end of entity
2286 if (com_token[0] == '{')
2293 if (submodel > loadmodel->brush.numsubmodels)
2295 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2299 model = loadmodel->brush.submodels[submodel];
2306 if (!COM_ParseToken(&data, false))
2308 if (com_token[0] == '}')
2309 break; // end of brush
2310 // each brush face should be this format:
2311 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2312 // FIXME: support hl .map format
2313 for (pointnum = 0;pointnum < 3;pointnum++)
2315 COM_ParseToken(&data, false);
2316 for (componentnum = 0;componentnum < 3;componentnum++)
2318 COM_ParseToken(&data, false);
2319 point[pointnum][componentnum] = atof(com_token);
2321 COM_ParseToken(&data, false);
2323 COM_ParseToken(&data, false);
2324 strlcpy(facetexture, com_token, sizeof(facetexture));
2325 COM_ParseToken(&data, false);
2326 //scroll_s = atof(com_token);
2327 COM_ParseToken(&data, false);
2328 //scroll_t = atof(com_token);
2329 COM_ParseToken(&data, false);
2330 //rotate = atof(com_token);
2331 COM_ParseToken(&data, false);
2332 //scale_s = atof(com_token);
2333 COM_ParseToken(&data, false);
2334 //scale_t = atof(com_token);
2335 TriangleNormal(point[0], point[1], point[2], planenormal);
2336 VectorNormalizeDouble(planenormal);
2337 planedist = DotProduct(point[0], planenormal);
2338 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2348 #define MAX_PORTALPOINTS 64
2350 typedef struct portal_s
2353 mnode_t *nodes[2]; // [0] = front side of plane
2354 struct portal_s *next[2];
2356 double points[3*MAX_PORTALPOINTS];
2357 struct portal_s *chain; // all portals are linked into a list
2361 static portal_t *portalchain;
2368 static portal_t *AllocPortal(void)
2371 p = Mem_Alloc(loadmodel->mempool, sizeof(portal_t));
2372 p->chain = portalchain;
2377 static void FreePortal(portal_t *p)
2382 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2384 // process only nodes (leafs already had their box calculated)
2388 // calculate children first
2389 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2390 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2392 // make combined bounding box from children
2393 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2394 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2395 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2396 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2397 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2398 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2401 static void Mod_Q1BSP_FinalizePortals(void)
2403 int i, j, numportals, numpoints;
2404 portal_t *p, *pnext;
2407 mleaf_t *leaf, *endleaf;
2409 // recalculate bounding boxes for all leafs(because qbsp is very sloppy)
2410 leaf = loadmodel->brush.data_leafs;
2411 endleaf = leaf + loadmodel->brush.num_leafs;
2412 for (;leaf < endleaf;leaf++)
2414 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
2415 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2420 if (p->numpoints >= 3)
2422 for (i = 0;i < 2;i++)
2424 leaf = (mleaf_t *)p->nodes[i];
2425 for (j = 0;j < p->numpoints;j++)
2427 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
2428 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
2429 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
2430 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
2431 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
2432 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
2439 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes);
2441 // tally up portal and point counts
2447 // note: this check must match the one below or it will usually corrupt memory
2448 // 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
2449 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2452 numpoints += p->numpoints * 2;
2456 loadmodel->brush.data_portals = Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
2457 loadmodel->brush.num_portals = numportals;
2458 loadmodel->brush.data_portalpoints = (void *)((qbyte *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
2459 loadmodel->brush.num_portalpoints = numpoints;
2460 // clear all leaf portal chains
2461 for (i = 0;i < loadmodel->brush.num_leafs;i++)
2462 loadmodel->brush.data_leafs[i].portals = NULL;
2463 // process all portals in the global portal chain, while freeing them
2464 portal = loadmodel->brush.data_portals;
2465 point = loadmodel->brush.data_portalpoints;
2472 // note: this check must match the one above or it will usually corrupt memory
2473 // 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
2474 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2476 // first make the back to front portal(forward portal)
2477 portal->points = point;
2478 portal->numpoints = p->numpoints;
2479 portal->plane.dist = p->plane.dist;
2480 VectorCopy(p->plane.normal, portal->plane.normal);
2481 portal->here = (mleaf_t *)p->nodes[1];
2482 portal->past = (mleaf_t *)p->nodes[0];
2484 for (j = 0;j < portal->numpoints;j++)
2486 VectorCopy(p->points + j*3, point->position);
2489 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
2490 PlaneClassify(&portal->plane);
2492 // link into leaf's portal chain
2493 portal->next = portal->here->portals;
2494 portal->here->portals = portal;
2496 // advance to next portal
2499 // then make the front to back portal(backward portal)
2500 portal->points = point;
2501 portal->numpoints = p->numpoints;
2502 portal->plane.dist = -p->plane.dist;
2503 VectorNegate(p->plane.normal, portal->plane.normal);
2504 portal->here = (mleaf_t *)p->nodes[0];
2505 portal->past = (mleaf_t *)p->nodes[1];
2507 for (j = portal->numpoints - 1;j >= 0;j--)
2509 VectorCopy(p->points + j*3, point->position);
2512 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
2513 PlaneClassify(&portal->plane);
2515 // link into leaf's portal chain
2516 portal->next = portal->here->portals;
2517 portal->here->portals = portal;
2519 // advance to next portal
2532 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
2535 Host_Error("AddPortalToNodes: NULL front node");
2537 Host_Error("AddPortalToNodes: NULL back node");
2538 if (p->nodes[0] || p->nodes[1])
2539 Host_Error("AddPortalToNodes: already included");
2540 // 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
2542 p->nodes[0] = front;
2543 p->next[0] = (portal_t *)front->portals;
2544 front->portals = (mportal_t *)p;
2547 p->next[1] = (portal_t *)back->portals;
2548 back->portals = (mportal_t *)p;
2553 RemovePortalFromNode
2556 static void RemovePortalFromNodes(portal_t *portal)
2560 void **portalpointer;
2562 for (i = 0;i < 2;i++)
2564 node = portal->nodes[i];
2566 portalpointer = (void **) &node->portals;
2571 Host_Error("RemovePortalFromNodes: portal not in leaf");
2575 if (portal->nodes[0] == node)
2577 *portalpointer = portal->next[0];
2578 portal->nodes[0] = NULL;
2580 else if (portal->nodes[1] == node)
2582 *portalpointer = portal->next[1];
2583 portal->nodes[1] = NULL;
2586 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
2590 if (t->nodes[0] == node)
2591 portalpointer = (void **) &t->next[0];
2592 else if (t->nodes[1] == node)
2593 portalpointer = (void **) &t->next[1];
2595 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
2600 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
2603 mnode_t *front, *back, *other_node;
2604 mplane_t clipplane, *plane;
2605 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
2606 int numfrontpoints, numbackpoints;
2607 double frontpoints[3*MAX_PORTALPOINTS], backpoints[3*MAX_PORTALPOINTS];
2609 // if a leaf, we're done
2613 plane = node->plane;
2615 front = node->children[0];
2616 back = node->children[1];
2618 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
2620 // create the new portal by generating a polygon for the node plane,
2621 // and clipping it by all of the other portals(which came from nodes above this one)
2622 nodeportal = AllocPortal();
2623 nodeportal->plane = *plane;
2625 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);
2626 nodeportal->numpoints = 4;
2627 side = 0; // shut up compiler warning
2628 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
2630 clipplane = portal->plane;
2631 if (portal->nodes[0] == portal->nodes[1])
2632 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
2633 if (portal->nodes[0] == node)
2635 else if (portal->nodes[1] == node)
2637 clipplane.dist = -clipplane.dist;
2638 VectorNegate(clipplane.normal, clipplane.normal);
2642 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
2644 for (i = 0;i < nodeportal->numpoints*3;i++)
2645 frontpoints[i] = nodeportal->points[i];
2646 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);
2647 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
2651 if (nodeportal->numpoints < 3)
2653 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
2654 nodeportal->numpoints = 0;
2656 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
2658 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
2659 nodeportal->numpoints = 0;
2663 AddPortalToNodes(nodeportal, front, back);
2665 // split the portals of this node along this node's plane and assign them to the children of this node
2666 // (migrating the portals downward through the tree)
2667 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
2669 if (portal->nodes[0] == portal->nodes[1])
2670 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
2671 if (portal->nodes[0] == node)
2673 else if (portal->nodes[1] == node)
2676 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
2677 nextportal = portal->next[side];
2679 other_node = portal->nodes[!side];
2680 RemovePortalFromNodes(portal);
2682 // cut the portal into two portals, one on each side of the node plane
2683 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);
2685 if (!numfrontpoints)
2688 AddPortalToNodes(portal, back, other_node);
2690 AddPortalToNodes(portal, other_node, back);
2696 AddPortalToNodes(portal, front, other_node);
2698 AddPortalToNodes(portal, other_node, front);
2702 // the portal is split
2703 splitportal = AllocPortal();
2704 temp = splitportal->chain;
2705 *splitportal = *portal;
2706 splitportal->chain = temp;
2707 for (i = 0;i < numbackpoints*3;i++)
2708 splitportal->points[i] = backpoints[i];
2709 splitportal->numpoints = numbackpoints;
2710 for (i = 0;i < numfrontpoints*3;i++)
2711 portal->points[i] = frontpoints[i];
2712 portal->numpoints = numfrontpoints;
2716 AddPortalToNodes(portal, front, other_node);
2717 AddPortalToNodes(splitportal, back, other_node);
2721 AddPortalToNodes(portal, other_node, front);
2722 AddPortalToNodes(splitportal, other_node, back);
2727 Mod_Q1BSP_RecursiveNodePortals(front);
2728 Mod_Q1BSP_RecursiveNodePortals(back);
2731 static void Mod_Q1BSP_MakePortals(void)
2734 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes);
2735 Mod_Q1BSP_FinalizePortals();
2738 static void Mod_Q1BSP_BuildLightmapUpdateChains(mempool_t *mempool, model_t *model)
2740 int i, j, stylecounts[256], totalcount, remapstyles[256];
2741 msurface_t *surface;
2742 memset(stylecounts, 0, sizeof(stylecounts));
2743 for (i = 0;i < model->nummodelsurfaces;i++)
2745 surface = model->brush.data_surfaces + model->firstmodelsurface + i;
2746 for (j = 0;j < MAXLIGHTMAPS;j++)
2747 stylecounts[surface->lightmapinfo->styles[j]]++;
2750 model->brushq1.light_styles = 0;
2751 for (i = 0;i < 255;i++)
2755 remapstyles[i] = model->brushq1.light_styles++;
2756 totalcount += stylecounts[i] + 1;
2761 model->brushq1.light_style = Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(qbyte));
2762 model->brushq1.light_stylevalue = Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(int));
2763 model->brushq1.light_styleupdatechains = Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(msurface_t **));
2764 model->brushq1.light_styleupdatechainsbuffer = Mem_Alloc(mempool, totalcount * sizeof(msurface_t *));
2765 model->brushq1.light_styles = 0;
2766 for (i = 0;i < 255;i++)
2768 model->brushq1.light_style[model->brushq1.light_styles++] = i;
2770 for (i = 0;i < model->brushq1.light_styles;i++)
2772 model->brushq1.light_styleupdatechains[i] = model->brushq1.light_styleupdatechainsbuffer + j;
2773 j += stylecounts[model->brushq1.light_style[i]] + 1;
2775 for (i = 0;i < model->nummodelsurfaces;i++)
2777 surface = model->brush.data_surfaces + model->firstmodelsurface + i;
2778 for (j = 0;j < MAXLIGHTMAPS;j++)
2779 if (surface->lightmapinfo->styles[j] != 255)
2780 *model->brushq1.light_styleupdatechains[remapstyles[surface->lightmapinfo->styles[j]]]++ = surface;
2783 for (i = 0;i < model->brushq1.light_styles;i++)
2785 *model->brushq1.light_styleupdatechains[i] = NULL;
2786 model->brushq1.light_styleupdatechains[i] = model->brushq1.light_styleupdatechainsbuffer + j;
2787 j += stylecounts[model->brushq1.light_style[i]] + 1;
2791 //Returns PVS data for a given point
2792 //(note: can return NULL)
2793 static qbyte *Mod_Q1BSP_GetPVS(model_t *model, const vec3_t p)
2796 Mod_CheckLoaded(model);
2797 node = model->brush.data_nodes;
2799 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
2800 if (((mleaf_t *)node)->clusterindex >= 0)
2801 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
2806 static void Mod_Q1BSP_FatPVS_RecursiveBSPNode(model_t *model, const vec3_t org, vec_t radius, qbyte *pvsbuffer, int pvsbytes, mnode_t *node)
2810 float d = PlaneDiff(org, node->plane);
2812 node = node->children[0];
2813 else if (d < -radius)
2814 node = node->children[1];
2817 // go down both sides
2818 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
2819 node = node->children[1];
2822 // if this leaf is in a cluster, accumulate the pvs bits
2823 if (((mleaf_t *)node)->clusterindex >= 0)
2826 qbyte *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
2827 for (i = 0;i < pvsbytes;i++)
2828 pvsbuffer[i] |= pvs[i];
2832 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
2833 //of the given point.
2834 static int Mod_Q1BSP_FatPVS(model_t *model, const vec3_t org, vec_t radius, qbyte *pvsbuffer, int pvsbufferlength)
2836 int bytes = model->brush.num_pvsclusterbytes;
2837 bytes = min(bytes, pvsbufferlength);
2838 if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
2840 memset(pvsbuffer, 0xFF, bytes);
2843 memset(pvsbuffer, 0, bytes);
2844 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes);
2848 static void Mod_Q1BSP_RoundUpToHullSize(model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
2853 VectorSubtract(inmaxs, inmins, size);
2854 if (cmodel->brush.ishlbsp)
2857 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2858 else if (size[0] <= 32)
2860 if (size[2] < 54) // pick the nearest of 36 or 72
2861 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
2863 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
2866 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
2871 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2872 else if (size[0] <= 32)
2873 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
2875 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
2877 VectorCopy(inmins, outmins);
2878 VectorAdd(inmins, hull->clip_size, outmaxs);
2881 extern void R_Q1BSP_DrawSky(entity_render_t *ent);
2882 extern void R_Q1BSP_Draw(entity_render_t *ent);
2883 extern void R_Q1BSP_GetLightInfo(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, vec3_t outmins, vec3_t outmaxs, int *outclusterlist, qbyte *outclusterpvs, int *outnumclusterspointer, int *outsurfacelist, qbyte *outsurfacepvs, int *outnumsurfacespointer);
2884 extern void R_Q1BSP_DrawShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, int numsurfaces, const int *surfacelist, const vec3_t lightmins, const vec3_t lightmaxs);
2885 extern void R_Q1BSP_DrawLight(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativeeyeorigin, float lightradius, float *lightcolor, const matrix4x4_t *matrix_modeltolight, const matrix4x4_t *matrix_modeltoattenuationxyz, const matrix4x4_t *matrix_modeltoattenuationz, rtexture_t *lightcubemap, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int numsurfaces, const int *surfacelist);
2886 void Mod_Q1BSP_Load(model_t *mod, void *buffer)
2891 mempool_t *mainmempool;
2892 float dist, modelyawradius, modelradius, *vec;
2893 msurface_t *surface;
2894 int numshadowmeshtriangles;
2896 mod->type = mod_brushq1;
2898 header = (dheader_t *)buffer;
2900 i = LittleLong(header->version);
2901 if (i != BSPVERSION && i != 30)
2902 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife))", mod->name, i, BSPVERSION);
2903 mod->brush.ishlbsp = i == 30;
2905 mod->soundfromcenter = true;
2906 mod->TraceBox = Mod_Q1BSP_TraceBox;
2907 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
2908 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
2909 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
2910 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
2911 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
2912 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
2913 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
2914 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
2915 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
2916 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
2917 mod->brushq1.PointInLeaf = Mod_Q1BSP_PointInLeaf;
2919 if (loadmodel->isworldmodel)
2920 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
2922 // swap all the lumps
2923 mod_base = (qbyte *)header;
2925 header->version = LittleLong(header->version);
2926 for (i = 0;i < HEADER_LUMPS;i++)
2928 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
2929 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
2934 // store which lightmap format to use
2935 mod->brushq1.lightmaprgba = r_lightmaprgba.integer;
2937 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
2938 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
2939 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
2940 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
2941 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
2942 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
2943 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
2944 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
2945 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
2946 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
2947 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
2948 // load submodels before leafs because they contain the number of vis leafs
2949 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS]);
2950 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
2951 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
2952 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES]);
2954 if (!mod->brushq1.lightdata)
2955 mod->brush.LightPoint = NULL;
2957 if (mod->brushq1.data_compressedpvs)
2958 Mem_Free(mod->brushq1.data_compressedpvs);
2959 mod->brushq1.data_compressedpvs = NULL;
2960 mod->brushq1.num_compressedpvs = 0;
2962 Mod_Q1BSP_MakeHull0();
2963 Mod_Q1BSP_MakePortals();
2965 mod->numframes = 2; // regular and alternate animation
2968 mainmempool = mod->mempool;
2970 Mod_Q1BSP_LoadLightList();
2972 // make a single combined shadow mesh to allow optimized shadow volume creation
2973 numshadowmeshtriangles = 0;
2974 for (j = 0, surface = loadmodel->brush.data_surfaces;j < loadmodel->brush.num_surfaces;j++, surface++)
2976 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
2977 numshadowmeshtriangles += surface->mesh.num_triangles;
2979 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
2980 for (j = 0, surface = loadmodel->brush.data_surfaces;j < loadmodel->brush.num_surfaces;j++, surface++)
2981 Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, surface->mesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->mesh.num_triangles, surface->mesh.data_element3i);
2982 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true);
2983 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
2985 if (loadmodel->brush.numsubmodels)
2986 loadmodel->brush.submodels = Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
2988 if (loadmodel->isworldmodel)
2990 // clear out any stale submodels or worldmodels lying around
2991 // if we did this clear before now, an error might abort loading and
2992 // leave things in a bad state
2993 Mod_RemoveStaleWorldModels(loadmodel);
2996 // LordHavoc: to clear the fog around the original quake submodel code, I
2998 // first of all, some background info on the submodels:
2999 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3000 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3001 // now the weird for loop itself:
3002 // the loop functions in an odd way, on each iteration it sets up the
3003 // current 'mod' model (which despite the confusing code IS the model of
3004 // the number i), at the end of the loop it duplicates the model to become
3005 // the next submodel, and loops back to set up the new submodel.
3007 // LordHavoc: now the explanation of my sane way (which works identically):
3008 // set up the world model, then on each submodel copy from the world model
3009 // and set up the submodel with the respective model info.
3010 for (i = 0;i < mod->brush.numsubmodels;i++)
3012 // LordHavoc: this code was originally at the end of this loop, but
3013 // has been transformed to something more readable at the start here.
3018 // LordHavoc: only register submodels if it is the world
3019 // (prevents external bsp models from replacing world submodels with
3021 if (!loadmodel->isworldmodel)
3023 // duplicate the basic information
3024 sprintf(name, "*%i", i);
3025 mod = Mod_FindName(name);
3026 // copy the base model to this one
3028 // rename the clone back to its proper name
3029 strcpy(mod->name, name);
3030 // textures and memory belong to the main model
3031 mod->texturepool = NULL;
3032 mod->mempool = NULL;
3035 mod->brush.submodel = i;
3037 if (loadmodel->brush.submodels)
3038 loadmodel->brush.submodels[i] = mod;
3040 bm = &mod->brushq1.submodels[i];
3042 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3043 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3045 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3046 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3049 mod->firstmodelsurface = bm->firstface;
3050 mod->nummodelsurfaces = bm->numfaces;
3052 // make the model surface list (used by shadowing/lighting)
3053 mod->surfacelist = Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->surfacelist));
3054 for (j = 0;j < mod->nummodelsurfaces;j++)
3055 mod->surfacelist[j] = mod->firstmodelsurface + j;
3057 // this gets altered below if sky is used
3058 mod->DrawSky = NULL;
3059 mod->Draw = R_Q1BSP_Draw;
3060 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3061 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3062 mod->DrawLight = R_Q1BSP_DrawLight;
3065 mod->brush.GetPVS = NULL;
3066 mod->brush.FatPVS = NULL;
3067 mod->brush.BoxTouchingPVS = NULL;
3068 mod->brush.BoxTouchingVisibleLeafs = NULL;
3069 mod->brush.LightPoint = NULL;
3070 mod->brush.AmbientSoundLevelsForPoint = NULL;
3072 Mod_Q1BSP_BuildLightmapUpdateChains(loadmodel->mempool, mod);
3073 if (mod->nummodelsurfaces)
3075 // LordHavoc: calculate bmodel bounding box rather than trusting what it says
3076 mod->normalmins[0] = mod->normalmins[1] = mod->normalmins[2] = 1000000000.0f;
3077 mod->normalmaxs[0] = mod->normalmaxs[1] = mod->normalmaxs[2] = -1000000000.0f;
3080 for (j = 0, surface = &mod->brush.data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3082 // we only need to have a drawsky function if it is used(usually only on world model)
3083 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3084 mod->DrawSky = R_Q1BSP_DrawSky;
3085 // calculate bounding shapes
3086 for (k = 0, vec = surface->mesh.data_vertex3f;k < surface->mesh.num_vertices;k++, vec += 3)
3088 if (mod->normalmins[0] > vec[0]) mod->normalmins[0] = vec[0];
3089 if (mod->normalmins[1] > vec[1]) mod->normalmins[1] = vec[1];
3090 if (mod->normalmins[2] > vec[2]) mod->normalmins[2] = vec[2];
3091 if (mod->normalmaxs[0] < vec[0]) mod->normalmaxs[0] = vec[0];
3092 if (mod->normalmaxs[1] < vec[1]) mod->normalmaxs[1] = vec[1];
3093 if (mod->normalmaxs[2] < vec[2]) mod->normalmaxs[2] = vec[2];
3094 dist = vec[0]*vec[0]+vec[1]*vec[1];
3095 if (modelyawradius < dist)
3096 modelyawradius = dist;
3097 dist += vec[2]*vec[2];
3098 if (modelradius < dist)
3102 modelyawradius = sqrt(modelyawradius);
3103 modelradius = sqrt(modelradius);
3104 mod->yawmins[0] = mod->yawmins[1] = - (mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius);
3105 mod->yawmins[2] = mod->normalmins[2];
3106 mod->yawmaxs[2] = mod->normalmaxs[2];
3107 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3108 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3109 mod->radius = modelradius;
3110 mod->radius2 = modelradius * modelradius;
3114 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3115 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3117 //mod->brushq1.num_visleafs = bm->visleafs;
3120 Mod_Q1BSP_LoadMapBrushes();
3122 //Mod_Q1BSP_ProcessLightList();
3124 if (developer.integer)
3125 Con_Printf("Some stats for q1bsp model \"%s\": %i faces, %i nodes, %i leafs, %i visleafs, %i visleafportals\n", loadmodel->name, loadmodel->brush.num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brushq1.submodels[i].visleafs, loadmodel->brush.num_portals);
3128 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3132 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3139 in = (void *)(mod_base + l->fileofs);
3140 if (l->filelen % sizeof(*in))
3141 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3142 count = l->filelen / sizeof(*in);
3143 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3146 loadmodel->num = count;
3148 for (i = 0;i < count;i++, in++, out++)
3154 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3161 in = (void *)(mod_base + l->fileofs);
3162 if (l->filelen % sizeof(*in))
3163 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3164 count = l->filelen / sizeof(*in);
3165 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3168 loadmodel->num = count;
3170 for (i = 0;i < count;i++, in++, out++)
3176 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3183 in = (void *)(mod_base + l->fileofs);
3184 if (l->filelen % sizeof(*in))
3185 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3186 count = l->filelen / sizeof(*in);
3187 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3190 loadmodel->num = count;
3192 for (i = 0;i < count;i++, in++, out++)
3198 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3205 in = (void *)(mod_base + l->fileofs);
3206 if (l->filelen % sizeof(*in))
3207 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3208 count = l->filelen / sizeof(*in);
3209 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3212 loadmodel->num = count;
3214 for (i = 0;i < count;i++, in++, out++)
3220 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3227 in = (void *)(mod_base + l->fileofs);
3228 if (l->filelen % sizeof(*in))
3229 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3230 count = l->filelen / sizeof(*in);
3231 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3234 loadmodel->num = count;
3236 for (i = 0;i < count;i++, in++, out++)
3242 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3249 in = (void *)(mod_base + l->fileofs);
3250 if (l->filelen % sizeof(*in))
3251 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3252 count = l->filelen / sizeof(*in);
3253 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3256 loadmodel->num = count;
3258 for (i = 0;i < count;i++, in++, out++)
3264 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3271 in = (void *)(mod_base + l->fileofs);
3272 if (l->filelen % sizeof(*in))
3273 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3274 count = l->filelen / sizeof(*in);
3275 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3278 loadmodel->num = count;
3280 for (i = 0;i < count;i++, in++, out++)
3286 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3293 in = (void *)(mod_base + l->fileofs);
3294 if (l->filelen % sizeof(*in))
3295 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3296 count = l->filelen / sizeof(*in);
3297 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3300 loadmodel->num = count;
3302 for (i = 0;i < count;i++, in++, out++)
3308 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3315 in = (void *)(mod_base + l->fileofs);
3316 if (l->filelen % sizeof(*in))
3317 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3318 count = l->filelen / sizeof(*in);
3319 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3322 loadmodel->num = count;
3324 for (i = 0;i < count;i++, in++, out++)
3330 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3337 in = (void *)(mod_base + l->fileofs);
3338 if (l->filelen % sizeof(*in))
3339 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3340 count = l->filelen / sizeof(*in);
3341 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3344 loadmodel->num = count;
3346 for (i = 0;i < count;i++, in++, out++)
3352 static void Mod_Q2BSP_LoadEdges(lump_t *l)
3359 in = (void *)(mod_base + l->fileofs);
3360 if (l->filelen % sizeof(*in))
3361 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
3362 count = l->filelen / sizeof(*in);
3363 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3366 loadmodel->num = count;
3368 for (i = 0;i < count;i++, in++, out++)
3374 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
3381 in = (void *)(mod_base + l->fileofs);
3382 if (l->filelen % sizeof(*in))
3383 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
3384 count = l->filelen / sizeof(*in);
3385 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3388 loadmodel->num = count;
3390 for (i = 0;i < count;i++, in++, out++)
3396 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
3403 in = (void *)(mod_base + l->fileofs);
3404 if (l->filelen % sizeof(*in))
3405 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
3406 count = l->filelen / sizeof(*in);
3407 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3410 loadmodel->num = count;
3412 for (i = 0;i < count;i++, in++, out++)
3418 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
3425 in = (void *)(mod_base + l->fileofs);
3426 if (l->filelen % sizeof(*in))
3427 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
3428 count = l->filelen / sizeof(*in);
3429 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3432 loadmodel->num = count;
3434 for (i = 0;i < count;i++, in++, out++)
3440 static void Mod_Q2BSP_LoadAreas(lump_t *l)
3447 in = (void *)(mod_base + l->fileofs);
3448 if (l->filelen % sizeof(*in))
3449 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
3450 count = l->filelen / sizeof(*in);
3451 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3454 loadmodel->num = count;
3456 for (i = 0;i < count;i++, in++, out++)
3462 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
3469 in = (void *)(mod_base + l->fileofs);
3470 if (l->filelen % sizeof(*in))
3471 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
3472 count = l->filelen / sizeof(*in);
3473 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3476 loadmodel->num = count;
3478 for (i = 0;i < count;i++, in++, out++)
3484 static void Mod_Q2BSP_LoadModels(lump_t *l)
3491 in = (void *)(mod_base + l->fileofs);
3492 if (l->filelen % sizeof(*in))
3493 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
3494 count = l->filelen / sizeof(*in);
3495 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3498 loadmodel->num = count;
3500 for (i = 0;i < count;i++, in++, out++)
3506 void static Mod_Q2BSP_Load(model_t *mod, void *buffer)
3509 q2dheader_t *header;
3511 Host_Error("Mod_Q2BSP_Load: not yet implemented\n");
3513 mod->type = mod_brushq2;
3515 header = (q2dheader_t *)buffer;
3517 i = LittleLong(header->version);
3518 if (i != Q2BSPVERSION)
3519 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
3520 mod->brush.ishlbsp = false;
3521 if (loadmodel->isworldmodel)
3522 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
3524 mod_base = (qbyte *)header;
3526 // swap all the lumps
3527 for (i = 0;i < (int) sizeof(*header) / 4;i++)
3528 ((int *)header)[i] = LittleLong(((int *)header)[i]);
3530 // store which lightmap format to use
3531 mod->brushq1.lightmaprgba = r_lightmaprgba.integer;
3533 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
3534 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
3535 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
3536 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
3537 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
3538 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
3539 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
3540 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
3541 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
3542 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
3543 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
3544 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
3545 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
3546 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
3547 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
3548 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
3549 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
3550 // LordHavoc: must go last because this makes the submodels
3551 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
3554 static int Mod_Q3BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents);
3555 static int Mod_Q3BSP_NativeContentsFromSuperContents(model_t *model, int supercontents);
3557 static void Mod_Q3BSP_LoadEntities(lump_t *l)
3560 char key[128], value[4096];
3562 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
3563 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
3564 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
3567 loadmodel->brush.entities = Mem_Alloc(loadmodel->mempool, l->filelen);
3568 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
3569 data = loadmodel->brush.entities;
3570 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
3571 if (data && COM_ParseToken(&data, false) && com_token[0] == '{')
3575 if (!COM_ParseToken(&data, false))
3577 if (com_token[0] == '}')
3578 break; // end of worldspawn
3579 if (com_token[0] == '_')
3580 strcpy(key, com_token + 1);
3582 strcpy(key, com_token);
3583 while (key[strlen(key)-1] == ' ') // remove trailing spaces
3584 key[strlen(key)-1] = 0;
3585 if (!COM_ParseToken(&data, false))
3587 strcpy(value, com_token);
3588 if (!strcmp("gridsize", key))
3590 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
3591 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
3597 static void Mod_Q3BSP_LoadTextures(lump_t *l)
3606 int flags, flags2, numparameters, passnumber;
3607 char shadername[Q3PATHLENGTH];
3608 char sky[Q3PATHLENGTH];
3609 char firstpasstexturename[Q3PATHLENGTH];
3610 char parameter[4][Q3PATHLENGTH];
3612 in = (void *)(mod_base + l->fileofs);
3613 if (l->filelen % sizeof(*in))
3614 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
3615 count = l->filelen / sizeof(*in);
3616 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3618 loadmodel->brush.data_textures = out;
3619 loadmodel->brush.num_textures = count;
3621 for (i = 0;i < count;i++, in++, out++)
3623 strlcpy (out->name, in->name, sizeof (out->name));
3624 out->surfaceflags = LittleLong(in->surfaceflags);
3625 out->supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in->contents));
3626 out->surfaceparms = -1;
3629 // do a quick parse of shader files to get surfaceparms
3630 if ((search = FS_Search("scripts/*.shader", true, false)))
3632 for (i = 0;i < search->numfilenames;i++)
3634 if ((f = FS_LoadFile(search->filenames[i], tempmempool, false)))
3637 while (COM_ParseToken(&text, false))
3639 strlcpy (shadername, com_token, sizeof (shadername));
3644 firstpasstexturename[0] = 0;
3645 if (COM_ParseToken(&text, false) && !strcasecmp(com_token, "{"))
3647 while (COM_ParseToken(&text, false))
3649 if (!strcasecmp(com_token, "}"))
3651 else if (!strcasecmp(com_token, "{"))
3653 while (COM_ParseToken(&text, false))
3655 if (!strcasecmp(com_token, "}"))
3657 if (!strcasecmp(com_token, "\n"))
3660 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
3664 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
3665 numparameters = j + 1;
3667 if (!COM_ParseToken(&text, true))
3670 if (developer.integer >= 2)
3672 Con_Printf("%s %i: ", shadername, passnumber);
3673 for (j = 0;j < numparameters;j++)
3674 Con_Printf(" %s", parameter[j]);
3677 if (passnumber == 0 && numparameters >= 1)
3679 if (!strcasecmp(parameter[0], "blendfunc"))
3681 if (numparameters == 2 && !strcasecmp(parameter[1], "add"))
3682 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3683 else if (numparameters == 3 && !strcasecmp(parameter[1], "gl_one") && !strcasecmp(parameter[2], "gl_one"))
3684 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3685 else if (numparameters == 3 && !strcasecmp(parameter[1], "gl_src_alpha") && !strcasecmp(parameter[2], "gl_one"))
3686 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3688 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
3689 strlcpy(firstpasstexturename, parameter[1], sizeof(firstpasstexturename));
3690 else if (numparameters >= 3 && !strcasecmp(parameter[0], "animmap"))
3691 strlcpy(firstpasstexturename, parameter[2], sizeof(firstpasstexturename));
3693 if (!strcasecmp(parameter[0], "alphafunc"))
3694 flags2 |= Q3TEXTUREFLAG_ALPHATEST;
3695 // break out a level if it was }
3696 if (!strcasecmp(com_token, "}"))
3703 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
3707 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
3708 numparameters = j + 1;
3710 if (!COM_ParseToken(&text, true))
3713 if (i == 0 && !strcasecmp(com_token, "}"))
3715 if (developer.integer >= 2)
3717 Con_Printf("%s: ", shadername);
3718 for (j = 0;j < numparameters;j++)
3719 Con_Printf(" %s", parameter[j]);
3722 if (numparameters < 1)
3724 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
3726 if (!strcasecmp(parameter[1], "alphashadow"))
3727 flags |= Q3SURFACEPARM_ALPHASHADOW;
3728 else if (!strcasecmp(parameter[1], "areaportal"))
3729 flags |= Q3SURFACEPARM_AREAPORTAL;
3730 else if (!strcasecmp(parameter[1], "clusterportal"))
3731 flags |= Q3SURFACEPARM_CLUSTERPORTAL;
3732 else if (!strcasecmp(parameter[1], "detail"))
3733 flags |= Q3SURFACEPARM_DETAIL;
3734 else if (!strcasecmp(parameter[1], "donotenter"))
3735 flags |= Q3SURFACEPARM_DONOTENTER;
3736 else if (!strcasecmp(parameter[1], "fog"))
3737 flags |= Q3SURFACEPARM_FOG;
3738 else if (!strcasecmp(parameter[1], "lava"))
3739 flags |= Q3SURFACEPARM_LAVA;
3740 else if (!strcasecmp(parameter[1], "lightfilter"))
3741 flags |= Q3SURFACEPARM_LIGHTFILTER;
3742 else if (!strcasecmp(parameter[1], "metalsteps"))
3743 flags |= Q3SURFACEPARM_METALSTEPS;
3744 else if (!strcasecmp(parameter[1], "nodamage"))
3745 flags |= Q3SURFACEPARM_NODAMAGE;
3746 else if (!strcasecmp(parameter[1], "nodlight"))
3747 flags |= Q3SURFACEPARM_NODLIGHT;
3748 else if (!strcasecmp(parameter[1], "nodraw"))
3749 flags |= Q3SURFACEPARM_NODRAW;
3750 else if (!strcasecmp(parameter[1], "nodrop"))
3751 flags |= Q3SURFACEPARM_NODROP;
3752 else if (!strcasecmp(parameter[1], "noimpact"))
3753 flags |= Q3SURFACEPARM_NOIMPACT;
3754 else if (!strcasecmp(parameter[1], "nolightmap"))
3755 flags |= Q3SURFACEPARM_NOLIGHTMAP;
3756 else if (!strcasecmp(parameter[1], "nomarks"))
3757 flags |= Q3SURFACEPARM_NOMARKS;
3758 else if (!strcasecmp(parameter[1], "nomipmaps"))
3759 flags |= Q3SURFACEPARM_NOMIPMAPS;
3760 else if (!strcasecmp(parameter[1], "nonsolid"))
3761 flags |= Q3SURFACEPARM_NONSOLID;
3762 else if (!strcasecmp(parameter[1], "origin"))
3763 flags |= Q3SURFACEPARM_ORIGIN;
3764 else if (!strcasecmp(parameter[1], "playerclip"))
3765 flags |= Q3SURFACEPARM_PLAYERCLIP;
3766 else if (!strcasecmp(parameter[1], "sky"))
3767 flags |= Q3SURFACEPARM_SKY;
3768 else if (!strcasecmp(parameter[1], "slick"))
3769 flags |= Q3SURFACEPARM_SLICK;
3770 else if (!strcasecmp(parameter[1], "slime"))
3771 flags |= Q3SURFACEPARM_SLIME;
3772 else if (!strcasecmp(parameter[1], "structural"))
3773 flags |= Q3SURFACEPARM_STRUCTURAL;
3774 else if (!strcasecmp(parameter[1], "trans"))
3775 flags |= Q3SURFACEPARM_TRANS;
3776 else if (!strcasecmp(parameter[1], "water"))
3777 flags |= Q3SURFACEPARM_WATER;
3778 else if (!strcasecmp(parameter[1], "pointlight"))
3779 flags |= Q3SURFACEPARM_POINTLIGHT;
3781 Con_Printf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[i], parameter[1]);
3783 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
3784 strlcpy(sky, parameter[1], sizeof(sky));
3785 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
3787 if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
3788 strlcpy(sky, parameter[1], sizeof(sky));
3790 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
3792 if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
3793 flags2 |= Q3TEXTUREFLAG_TWOSIDED;
3795 else if (!strcasecmp(parameter[0], "nomipmaps"))
3796 flags2 |= Q3TEXTUREFLAG_NOMIPMAPS;
3797 else if (!strcasecmp(parameter[0], "nopicmip"))
3798 flags2 |= Q3TEXTUREFLAG_NOPICMIP;
3799 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
3801 if (!strcasecmp(parameter[1], "autosprite") && numparameters == 2)
3802 flags2 |= Q3TEXTUREFLAG_AUTOSPRITE;
3803 if (!strcasecmp(parameter[1], "autosprite2") && numparameters == 2)
3804 flags2 |= Q3TEXTUREFLAG_AUTOSPRITE2;
3807 // force transparent render path for a number of odd
3808 // shader effects to avoid bogging down the normal
3809 // render path unnecessarily
3810 if (flags2 & (Q3TEXTUREFLAG_ADDITIVE | Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2 | Q3TEXTUREFLAG_ALPHATEST))
3811 flags |= Q3SURFACEPARM_TRANS;
3812 // add shader to list (shadername and flags)
3813 // actually here we just poke into the texture settings
3814 for (j = 0, out = loadmodel->brush.data_textures;j < loadmodel->brush.num_textures;j++, out++)
3816 if (!strcasecmp(out->name, shadername))
3818 out->surfaceparms = flags;
3819 out->textureflags = flags2;
3820 out->basematerialflags = 0;
3821 if (out->surfaceparms & Q3SURFACEPARM_NODRAW)
3822 out->basematerialflags |= MATERIALFLAG_NODRAW;
3823 else if (out->surfaceparms & Q3SURFACEPARM_SKY)
3824 out->basematerialflags |= MATERIALFLAG_SKY;
3825 else if (out->surfaceparms & Q3SURFACEPARM_LAVA)
3826 out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_FULLBRIGHT;
3827 else if (out->surfaceparms & Q3SURFACEPARM_SLIME)
3828 out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_WATERALPHA;
3829 else if (out->surfaceparms & Q3SURFACEPARM_WATER)
3830 out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_WATERALPHA;
3832 out->basematerialflags |= MATERIALFLAG_WALL;
3833 if (out->surfaceparms & Q3SURFACEPARM_TRANS)
3834 out->basematerialflags |= MATERIALFLAG_TRANSPARENT;
3835 if (out->textureflags & Q3TEXTUREFLAG_ADDITIVE)
3836 out->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_TRANSPARENT;
3837 strlcpy(out->firstpasstexturename, firstpasstexturename, sizeof(out->firstpasstexturename));
3838 if ((flags & Q3SURFACEPARM_SKY) && sky[0])
3840 // quake3 seems to append a _ to the skybox name, so this must do so as well
3841 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", sky);
3848 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[i], com_token);
3859 for (j = 0, out = loadmodel->brush.data_textures;j < loadmodel->brush.num_textures;j++, out++)
3861 if (out->surfaceparms == -1)
3864 Con_DPrintf("%s: No shader found for texture \"%s\"\n", loadmodel->name, out->name);
3865 out->surfaceparms = 0;
3866 if (out->surfaceflags & Q3SURFACEFLAG_NODRAW)
3867 out->basematerialflags |= MATERIALFLAG_NODRAW;
3868 else if (out->surfaceflags & Q3SURFACEFLAG_SKY)
3869 out->basematerialflags |= MATERIALFLAG_SKY;
3871 out->basematerialflags |= MATERIALFLAG_WALL;
3872 // these are defaults
3873 //if (!strncmp(out->name, "textures/skies/", 15))
3874 // out->surfaceparms |= Q3SURFACEPARM_SKY;
3875 //if (!strcmp(out->name, "caulk") || !strcmp(out->name, "common/caulk") || !strcmp(out->name, "textures/common/caulk")
3876 // || !strcmp(out->name, "nodraw") || !strcmp(out->name, "common/nodraw") || !strcmp(out->name, "textures/common/nodraw"))
3877 // out->surfaceparms |= Q3SURFACEPARM_NODRAW;
3878 //if (R_TextureHasAlpha(out->skin.base))
3879 // out->surfaceparms |= Q3SURFACEPARM_TRANS;
3881 if (!Mod_LoadSkinFrame(&out->skin, out->name, (((out->textureflags & Q3TEXTUREFLAG_NOMIPMAPS) || (out->surfaceparms & Q3SURFACEPARM_NOMIPMAPS)) ? 0 : TEXF_MIPMAP) | TEXF_ALPHA | TEXF_PRECACHE | (out->textureflags & Q3TEXTUREFLAG_NOPICMIP ? 0 : TEXF_PICMIP), false, false, true))
3882 if (!Mod_LoadSkinFrame(&out->skin, out->firstpasstexturename, (((out->textureflags & Q3TEXTUREFLAG_NOMIPMAPS) || (out->surfaceparms & Q3SURFACEPARM_NOMIPMAPS)) ? 0 : TEXF_MIPMAP) | TEXF_ALPHA | TEXF_PRECACHE | (out->textureflags & Q3TEXTUREFLAG_NOPICMIP ? 0 : TEXF_PICMIP), false, false, true))
3883 Con_Printf("%s: texture loading for shader \"%s\" failed (first layer \"%s\" not found either)\n", loadmodel->name, out->name, out->firstpasstexturename);
3885 out->basematerialflags |= (MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT);
3887 out->currentframe = out;
3890 Con_DPrintf("%s: %i textures missing shaders\n", loadmodel->name, c);
3893 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
3899 in = (void *)(mod_base + l->fileofs);
3900 if (l->filelen % sizeof(*in))
3901 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3902 count = l->filelen / sizeof(*in);
3903 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3905 loadmodel->brush.data_planes = out;
3906 loadmodel->brush.num_planes = count;
3908 for (i = 0;i < count;i++, in++, out++)
3910 out->normal[0] = LittleLong(in->normal[0]);
3911 out->normal[1] = LittleLong(in->normal[1]);
3912 out->normal[2] = LittleLong(in->normal[2]);
3913 out->dist = LittleLong(in->dist);
3918 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
3921 q3mbrushside_t *out;
3924 in = (void *)(mod_base + l->fileofs);
3925 if (l->filelen % sizeof(*in))
3926 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
3927 count = l->filelen / sizeof(*in);
3928 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3930 loadmodel->brush.data_brushsides = out;
3931 loadmodel->brush.num_brushsides = count;
3933 for (i = 0;i < count;i++, in++, out++)
3935 n = LittleLong(in->planeindex);
3936 if (n < 0 || n >= loadmodel->brush.num_planes)
3937 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)\n", n, loadmodel->brush.num_planes);
3938 out->plane = loadmodel->brush.data_planes + n;
3939 n = LittleLong(in->textureindex);
3940 if (n < 0 || n >= loadmodel->brush.num_textures)
3941 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)\n", n, loadmodel->brush.num_textures);
3942 out->texture = loadmodel->brush.data_textures + n;
3946 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
3950 int i, j, n, c, count, maxplanes;
3953 in = (void *)(mod_base + l->fileofs);
3954 if (l->filelen % sizeof(*in))
3955 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
3956 count = l->filelen / sizeof(*in);
3957 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3959 loadmodel->brush.data_brushes = out;
3960 loadmodel->brush.num_brushes = count;
3965 for (i = 0;i < count;i++, in++, out++)
3967 n = LittleLong(in->firstbrushside);
3968 c = LittleLong(in->numbrushsides);
3969 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
3970 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)\n", n, n + c, loadmodel->brush.num_brushsides);
3971 out->firstbrushside = loadmodel->brush.data_brushsides + n;
3972 out->numbrushsides = c;
3973 n = LittleLong(in->textureindex);
3974 if (n < 0 || n >= loadmodel->brush.num_textures)
3975 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)\n", n, loadmodel->brush.num_textures);
3976 out->texture = loadmodel->brush.data_textures + n;
3978 // make a list of mplane_t structs to construct a colbrush from
3979 if (maxplanes < out->numbrushsides)
3981 maxplanes = out->numbrushsides;
3984 planes = Mem_Alloc(tempmempool, sizeof(mplane_t) * maxplanes);
3986 for (j = 0;j < out->numbrushsides;j++)
3988 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
3989 planes[j].dist = out->firstbrushside[j].plane->dist;
3991 // make the colbrush from the planes
3992 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents);
3998 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4004 in = (void *)(mod_base + l->fileofs);
4005 if (l->filelen % sizeof(*in))
4006 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4007 count = l->filelen / sizeof(*in);
4008 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4010 loadmodel->brushq3.data_effects = out;
4011 loadmodel->brushq3.num_effects = count;
4013 for (i = 0;i < count;i++, in++, out++)
4015 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4016 n = LittleLong(in->brushindex);
4017 if (n < 0 || n >= loadmodel->brush.num_brushes)
4018 Host_Error("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes)\n", n, loadmodel->brush.num_brushes);
4019 out->brushindex = n;
4020 out->unknown = LittleLong(in->unknown);
4024 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4029 in = (void *)(mod_base + l->fileofs);
4030 if (l->filelen % sizeof(*in))
4031 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4032 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4033 loadmodel->brushq3.data_vertex3f = Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 2 + 2 + 4)));
4034 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_vertex3f + count * 3;
4035 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4036 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4038 for (i = 0;i < count;i++, in++)
4040 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4041 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4042 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4043 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4044 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4045 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4046 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4047 // svector/tvector are calculated later in face loading
4048 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4049 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4050 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4051 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4055 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4061 in = (void *)(mod_base + l->fileofs);
4062 if (l->filelen % sizeof(int[3]))
4063 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4064 count = l->filelen / sizeof(*in);
4065 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4067 loadmodel->brushq3.num_triangles = count / 3;
4068 loadmodel->brushq3.data_element3i = out;
4070 for (i = 0;i < count;i++, in++, out++)
4072 *out = LittleLong(*in);
4073 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4075 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4081 static void Mod_Q3BSP_LoadLightmaps(lump_t *l)
4089 in = (void *)(mod_base + l->fileofs);
4090 if (l->filelen % sizeof(*in))
4091 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4092 count = l->filelen / sizeof(*in);
4093 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4095 loadmodel->brushq3.data_lightmaps = out;
4096 loadmodel->brushq3.num_lightmaps = count;
4098 for (i = 0;i < count;i++, in++, out++)
4099 *out = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", i), 128, 128, in->rgb, TEXTYPE_RGB, TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
4102 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4104 q3dface_t *in, *oldin;
4105 msurface_t *out, *oldout;
4106 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;
4107 //int *originalelement3i;
4108 //int *originalneighbor3i;
4109 float *originalvertex3f;
4110 //float *originalsvector3f;
4111 //float *originaltvector3f;
4112 //float *originalnormal3f;
4113 float *originalcolor4f;
4114 float *originaltexcoordtexture2f;
4115 float *originaltexcoordlightmap2f;
4117 surfmesh_t *mesh, *tempmeshlist[1024];
4119 in = (void *)(mod_base + l->fileofs);
4120 if (l->filelen % sizeof(*in))
4121 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4122 count = l->filelen / sizeof(*in);
4123 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4125 loadmodel->brush.data_surfaces = out;
4126 loadmodel->brush.num_surfaces = count;
4129 for (meshnum = 0;i < count;meshnum++)
4136 for (;i < count;i++, in++, out++)
4138 // check face type first
4139 type = LittleLong(in->type);
4140 if (type != Q3FACETYPE_POLYGON
4141 && type != Q3FACETYPE_PATCH
4142 && type != Q3FACETYPE_MESH
4143 && type != Q3FACETYPE_FLARE)
4145 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4149 n = LittleLong(in->textureindex);
4150 if (n < 0 || n >= loadmodel->brush.num_textures)
4152 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->brush.num_textures);
4155 out->texture = loadmodel->brush.data_textures + n;
4156 n = LittleLong(in->effectindex);
4157 if (n < -1 || n >= loadmodel->brushq3.num_effects)
4159 if (developer.integer >= 2)
4160 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4166 out->effect = loadmodel->brushq3.data_effects + n;
4167 n = LittleLong(in->lightmapindex);
4168 if (n >= loadmodel->brushq3.num_lightmaps)
4170 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_lightmaps);
4176 out->lightmaptexture = NULL;
4178 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n];
4180 firstvertex = LittleLong(in->firstvertex);
4181 numvertices = LittleLong(in->numvertices);
4182 firstelement = LittleLong(in->firstelement);
4183 numtriangles = LittleLong(in->numelements) / 3;
4184 if (numtriangles * 3 != LittleLong(in->numelements))
4186 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));
4189 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4191 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);
4194 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4196 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);
4201 case Q3FACETYPE_POLYGON:
4202 case Q3FACETYPE_MESH:
4203 // no processing necessary
4205 case Q3FACETYPE_PATCH:
4206 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4207 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4208 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))
4210 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
4213 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4214 // convert patch to Q3FACETYPE_MESH
4215 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4216 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4217 // bound to user settings
4218 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4219 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4220 // bound to sanity settings
4221 xtess = bound(1, xtess, 1024);
4222 ytess = bound(1, ytess, 1024);
4223 // bound to user limit on vertices
4224 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_maxvertices.integer, 262144))
4231 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4232 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4233 numvertices = finalwidth * finalheight;
4234 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4236 case Q3FACETYPE_FLARE:
4237 if (developer.integer >= 2)
4238 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
4242 out->mesh.num_vertices = numvertices;
4243 out->mesh.num_triangles = numtriangles;
4244 if (meshvertices + out->mesh.num_vertices > 65536)
4246 meshvertices += out->mesh.num_vertices;
4247 meshtriangles += out->mesh.num_triangles;
4253 mesh = tempmeshlist[meshnum] = Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, false, true);
4256 for (;i < count && meshvertices + out->mesh.num_vertices <= mesh->num_vertices;i++, in++, out++)
4258 if (out->mesh.num_vertices < 3 || out->mesh.num_triangles < 1)
4261 type = LittleLong(in->type);
4262 firstvertex = LittleLong(in->firstvertex);
4263 firstelement = LittleLong(in->firstelement);
4264 out->mesh.data_vertex3f = mesh->data_vertex3f + meshvertices * 3;
4265 out->mesh.data_svector3f = mesh->data_svector3f + meshvertices * 3;
4266 out->mesh.data_tvector3f = mesh->data_tvector3f + meshvertices * 3;
4267 out->mesh.data_normal3f = mesh->data_normal3f + meshvertices * 3;
4268 out->mesh.data_texcoordtexture2f = mesh->data_texcoordtexture2f + meshvertices * 2;
4269 out->mesh.data_texcoordlightmap2f = mesh->data_texcoordlightmap2f + meshvertices * 2;
4270 out->mesh.data_lightmapcolor4f = mesh->data_lightmapcolor4f + meshvertices * 4;
4271 out->mesh.data_element3i = mesh->data_element3i + meshtriangles * 3;
4272 out->mesh.data_neighbor3i = mesh->data_neighbor3i + meshtriangles * 3;
4275 case Q3FACETYPE_POLYGON:
4276 case Q3FACETYPE_MESH:
4277 // no processing necessary
4278 for (j = 0;j < out->mesh.num_vertices;j++)
4280 out->mesh.data_vertex3f[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
4281 out->mesh.data_vertex3f[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
4282 out->mesh.data_vertex3f[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
4283 out->mesh.data_texcoordtexture2f[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
4284 out->mesh.data_texcoordtexture2f[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
4285 out->mesh.data_texcoordlightmap2f[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
4286 out->mesh.data_texcoordlightmap2f[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
4287 out->mesh.data_lightmapcolor4f[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
4288 out->mesh.data_lightmapcolor4f[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
4289 out->mesh.data_lightmapcolor4f[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
4290 out->mesh.data_lightmapcolor4f[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
4292 for (j = 0;j < out->mesh.num_triangles*3;j++)
4293 out->mesh.data_element3i[j] = loadmodel->brushq3.data_element3i[firstelement + j];
4295 case Q3FACETYPE_PATCH:
4296 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4297 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4298 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4299 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
4300 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
4301 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
4302 // convert patch to Q3FACETYPE_MESH
4303 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4304 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4305 // bound to user settings
4306 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4307 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4308 // bound to sanity settings
4309 xtess = bound(1, xtess, 1024);
4310 ytess = bound(1, ytess, 1024);
4311 // bound to user limit on vertices
4312 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_maxvertices.integer, 262144))
4319 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4320 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4321 finalvertices = finalwidth * finalheight;
4322 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4323 type = Q3FACETYPE_MESH;
4324 // generate geometry
4325 // (note: normals are skipped because they get recalculated)
4326 Q3PatchTesselateFloat(3, sizeof(float[3]), out->mesh.data_vertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
4327 Q3PatchTesselateFloat(2, sizeof(float[2]), out->mesh.data_texcoordtexture2f, patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
4328 Q3PatchTesselateFloat(2, sizeof(float[2]), out->mesh.data_texcoordlightmap2f, patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
4329 Q3PatchTesselateFloat(4, sizeof(float[4]), out->mesh.data_lightmapcolor4f, patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
4330 Q3PatchTriangleElements(out->mesh.data_element3i, finalwidth, finalheight);
4331 out->mesh.num_triangles = Mod_RemoveDegenerateTriangles(out->mesh.num_triangles, out->mesh.data_element3i, out->mesh.data_element3i, out->mesh.data_vertex3f);
4332 if (developer.integer >= 2)
4334 if (out->mesh.num_triangles < finaltriangles)
4335 Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles, %i degenerate triangles removed (leaving %i)\n", patchsize[0], patchsize[1], out->mesh.num_vertices, finaltriangles, finaltriangles - out->mesh.num_triangles, out->mesh.num_triangles);
4337 Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles\n", patchsize[0], patchsize[1], out->mesh.num_vertices, out->mesh.num_triangles);
4339 // q3map does not put in collision brushes for curves... ugh
4340 // build the lower quality collision geometry
4341 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4342 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4343 // bound to user settings
4344 xtess = bound(r_subdivisions_collision_mintess.integer, xtess, r_subdivisions_collision_maxtess.integer);
4345 ytess = bound(r_subdivisions_collision_mintess.integer, ytess, r_subdivisions_collision_maxtess.integer);
4346 // bound to sanity settings
4347 xtess = bound(1, xtess, 1024);
4348 ytess = bound(1, ytess, 1024);
4349 // bound to user limit on vertices
4350 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_collision_maxvertices.integer, 262144))
4357 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4358 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4359 finalvertices = finalwidth * finalheight;
4360 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4362 out->data_collisionvertex3f = Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
4363 out->data_collisionelement3i = Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
4364 out->num_collisionvertices = finalvertices;
4365 out->num_collisiontriangles = finaltriangles;
4366 Q3PatchTesselateFloat(3, sizeof(float[3]), out->data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
4367 Q3PatchTriangleElements(out->data_collisionelement3i, finalwidth, finalheight);
4369 //Mod_SnapVertices(3, out->mesh.num_vertices, out->mesh.data_vertex3f, 0.25);
4370 Mod_SnapVertices(3, out->num_collisionvertices, out->data_collisionvertex3f, 1);
4372 oldnumtriangles = out->mesh.num_triangles;
4373 oldnumtriangles2 = out->num_collisiontriangles;
4374 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->num_collisiontriangles, out->data_collisionelement3i, out->data_collisionelement3i, out->data_collisionvertex3f);
4375 if (developer.integer)
4376 Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve became %i:%i vertices / %i:%i triangles (%i:%i degenerate)\n", patchsize[0], patchsize[1], out->mesh.num_vertices, out->num_collisionvertices, oldnumtriangles, oldnumtriangles2, oldnumtriangles - out->mesh.num_triangles, oldnumtriangles2 - out->num_collisiontriangles);
4381 meshvertices += out->mesh.num_vertices;
4382 meshtriangles += out->mesh.num_triangles;
4383 for (j = 0, invalidelements = 0;j < out->mesh.num_triangles * 3;j++)
4384 if (out->mesh.data_element3i[j] < 0 || out->mesh.data_element3i[j] >= out->mesh.num_vertices)
4386 if (invalidelements)
4388 Con_Printf("Mod_Q3BSP_LoadFaces: Warning: face #%i has %i invalid elements, type = %i, texture->name = \"%s\", texture->surfaceflags = %i, firstvertex = %i, numvertices = %i, firstelement = %i, numelements = %i, elements list:\n", i, invalidelements, type, out->texture->name, out->texture->surfaceflags, firstvertex, out->mesh.num_vertices, firstelement, out->mesh.num_triangles * 3);
4389 for (j = 0;j < out->mesh.num_triangles * 3;j++)
4391 Con_Printf(" %i", out->mesh.data_element3i[j]);
4392 if (out->mesh.data_element3i[j] < 0 || out->mesh.data_element3i[j] >= out->mesh.num_vertices)
4393 out->mesh.data_element3i[j] = 0;
4397 // for shadow volumes
4398 Mod_BuildTriangleNeighbors(out->mesh.data_neighbor3i, out->mesh.data_element3i, out->mesh.num_triangles);
4399 // for per pixel lighting
4400 Mod_BuildTextureVectorsAndNormals(out->mesh.num_vertices, out->mesh.num_triangles, out->mesh.data_vertex3f, out->mesh.data_texcoordtexture2f, out->mesh.data_element3i, out->mesh.data_svector3f, out->mesh.data_tvector3f, out->mesh.data_normal3f);
4401 // calculate a bounding box
4402 VectorClear(out->mins);
4403 VectorClear(out->maxs);
4404 if (out->mesh.num_vertices)
4406 VectorCopy(out->mesh.data_vertex3f, out->mins);
4407 VectorCopy(out->mesh.data_vertex3f, out->maxs);
4408 for (j = 1, v = out->mesh.data_vertex3f + 3;j < out->mesh.num_vertices;j++, v += 3)
4410 out->mins[0] = min(out->mins[0], v[0]);
4411 out->maxs[0] = max(out->maxs[0], v[0]);
4412 out->mins[1] = min(out->mins[1], v[1]);
4413 out->maxs[1] = max(out->maxs[1], v[1]);
4414 out->mins[2] = min(out->mins[2], v[2]);
4415 out->maxs[2] = max(out->maxs[2], v[2]);
4417 out->mins[0] -= 1.0f;
4418 out->mins[1] -= 1.0f;
4419 out->mins[2] -= 1.0f;
4420 out->maxs[0] += 1.0f;
4421 out->maxs[1] += 1.0f;
4422 out->maxs[2] += 1.0f;
4424 // set lightmap styles for consistency with q1bsp
4425 //out->lightmapinfo->styles[0] = 0;
4426 //out->lightmapinfo->styles[1] = 255;
4427 //out->lightmapinfo->styles[2] = 255;
4428 //out->lightmapinfo->styles[3] = 255;
4432 // now store the completed list of meshes
4433 loadmodel->nummeshes = meshnum;
4434 if (loadmodel->nummeshes)
4436 loadmodel->meshlist = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *) * loadmodel->nummeshes);
4437 memcpy(loadmodel->meshlist, tempmeshlist, sizeof(surfmesh_t *) * loadmodel->nummeshes);
4440 // free the no longer needed vertex data
4441 loadmodel->brushq3.num_vertices = 0;
4442 Mem_Free(loadmodel->brushq3.data_vertex3f);
4443 loadmodel->brushq3.data_vertex3f = NULL;
4444 loadmodel->brushq3.data_texcoordtexture2f = NULL;
4445 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
4446 loadmodel->brushq3.data_color4f = NULL;
4447 // free the no longer needed triangle data
4448 loadmodel->brushq3.num_triangles = 0;
4449 Mem_Free(loadmodel->brushq3.data_element3i);
4450 loadmodel->brushq3.data_element3i = NULL;
4453 static void Mod_Q3BSP_LoadModels(lump_t *l)
4457 int i, j, n, c, count;
4459 in = (void *)(mod_base + l->fileofs);
4460 if (l->filelen % sizeof(*in))
4461 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
4462 count = l->filelen / sizeof(*in);
4463 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4465 loadmodel->brushq3.data_models = out;
4466 loadmodel->brushq3.num_models = count;
4468 for (i = 0;i < count;i++, in++, out++)
4470 for (j = 0;j < 3;j++)
4472 out->mins[j] = LittleFloat(in->mins[j]);
4473 out->maxs[j] = LittleFloat(in->maxs[j]);
4475 n = LittleLong(in->firstface);
4476 c = LittleLong(in->numfaces);
4477 if (n < 0 || n + c > loadmodel->brush.num_surfaces)
4478 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)\n", n, n + c, loadmodel->brush.num_surfaces);
4481 n = LittleLong(in->firstbrush);
4482 c = LittleLong(in->numbrushes);
4483 if (n < 0 || n + c > loadmodel->brush.num_brushes)
4484 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)\n", n, n + c, loadmodel->brush.num_brushes);
4485 out->firstbrush = n;
4486 out->numbrushes = c;
4490 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
4496 in = (void *)(mod_base + l->fileofs);
4497 if (l->filelen % sizeof(*in))
4498 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4499 count = l->filelen / sizeof(*in);
4500 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4502 loadmodel->brush.data_leafbrushes = out;
4503 loadmodel->brush.num_leafbrushes = count;
4505 for (i = 0;i < count;i++, in++, out++)
4507 n = LittleLong(*in);
4508 if (n < 0 || n >= loadmodel->brush.num_brushes)
4509 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)\n", n, loadmodel->brush.num_brushes);
4514 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
4520 in = (void *)(mod_base + l->fileofs);
4521 if (l->filelen % sizeof(*in))
4522 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4523 count = l->filelen / sizeof(*in);
4524 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4526 loadmodel->brush.data_leafsurfaces = out;
4527 loadmodel->brush.num_leafsurfaces = count;
4529 for (i = 0;i < count;i++, in++, out++)
4531 n = LittleLong(*in);
4532 if (n < 0 || n >= loadmodel->brush.num_surfaces)
4533 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)\n", n, loadmodel->brush.num_surfaces);
4538 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
4542 int i, j, n, c, count;
4544 in = (void *)(mod_base + l->fileofs);
4545 if (l->filelen % sizeof(*in))
4546 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4547 count = l->filelen / sizeof(*in);
4548 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4550 loadmodel->brush.data_leafs = out;
4551 loadmodel->brush.num_leafs = count;
4553 for (i = 0;i < count;i++, in++, out++)
4557 out->clusterindex = LittleLong(in->clusterindex);
4558 out->areaindex = LittleLong(in->areaindex);
4559 for (j = 0;j < 3;j++)
4561 // yes the mins/maxs are ints
4562 out->mins[j] = LittleLong(in->mins[j]) - 1;
4563 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
4565 n = LittleLong(in->firstleafface);
4566 c = LittleLong(in->numleaffaces);
4567 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
4568 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)\n", n, n + c, loadmodel->brush.num_leafsurfaces);
4569 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
4570 out->numleafsurfaces = c;
4571 n = LittleLong(in->firstleafbrush);
4572 c = LittleLong(in->numleafbrushes);
4573 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
4574 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)\n", n, n + c, loadmodel->brush.num_leafbrushes);
4575 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
4576 out->numleafbrushes = c;
4580 static void Mod_Q3BSP_LoadNodes(lump_t *l)
4586 in = (void *)(mod_base + l->fileofs);
4587 if (l->filelen % sizeof(*in))
4588 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4589 count = l->filelen / sizeof(*in);
4590 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4592 loadmodel->brush.data_nodes = out;
4593 loadmodel->brush.num_nodes = count;
4595 for (i = 0;i < count;i++, in++, out++)
4598 n = LittleLong(in->planeindex);
4599 if (n < 0 || n >= loadmodel->brush.num_planes)
4600 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)\n", n, loadmodel->brush.num_planes);
4601 out->plane = loadmodel->brush.data_planes + n;
4602 for (j = 0;j < 2;j++)
4604 n = LittleLong(in->childrenindex[j]);
4607 if (n >= loadmodel->brush.num_nodes)
4608 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)\n", n, loadmodel->brush.num_nodes);
4609 out->children[j] = loadmodel->brush.data_nodes + n;
4614 if (n >= loadmodel->brush.num_leafs)
4615 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)\n", n, loadmodel->brush.num_leafs);
4616 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
4619 for (j = 0;j < 3;j++)
4621 // yes the mins/maxs are ints
4622 out->mins[j] = LittleLong(in->mins[j]) - 1;
4623 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
4627 // set the parent pointers
4628 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
4631 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
4634 q3dlightgrid_t *out;
4637 in = (void *)(mod_base + l->fileofs);
4638 if (l->filelen % sizeof(*in))
4639 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
4640 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
4641 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
4642 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
4643 loadmodel->brushq3.num_lightgrid_imins[0] = ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
4644 loadmodel->brushq3.num_lightgrid_imins[1] = ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
4645 loadmodel->brushq3.num_lightgrid_imins[2] = ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
4646 loadmodel->brushq3.num_lightgrid_imaxs[0] = floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
4647 loadmodel->brushq3.num_lightgrid_imaxs[1] = floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
4648 loadmodel->brushq3.num_lightgrid_imaxs[2] = floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
4649 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
4650 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
4651 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
4652 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
4655 if (l->filelen < count * (int)sizeof(*in))
4656 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]);
4657 if (l->filelen != count * (int)sizeof(*in))
4658 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", count * sizeof(*in), l->filelen);
4661 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4662 loadmodel->brushq3.data_lightgrid = out;
4663 loadmodel->brushq3.num_lightgrid = count;
4665 // no swapping or validation necessary
4667 memcpy(out, in, count * (int)sizeof(*out));
4670 // no data, fill with white
4672 for (i = 0;i < count;i++)
4674 out[i].ambientrgb[0] = 128;
4675 out[i].ambientrgb[1] = 128;
4676 out[i].ambientrgb[2] = 128;
4677 out[i].diffusergb[0] = 0;
4678 out[i].diffusergb[1] = 0;
4679 out[i].diffusergb[2] = 0;
4680 out[i].diffusepitch = 0;
4681 out[i].diffuseyaw = 0;
4685 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]);
4686 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]);
4689 static void Mod_Q3BSP_LoadPVS(lump_t *l)
4694 if (l->filelen == 0)
4697 // unvised maps often have cluster indices even without pvs, so check
4698 // leafs to find real number of clusters
4699 loadmodel->brush.num_pvsclusters = 1;
4700 for (i = 0;i < loadmodel->brush.num_leafs;i++)
4701 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
4704 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
4705 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
4706 loadmodel->brush.data_pvsclusters = Mem_Alloc(loadmodel->mempool, totalchains);
4707 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
4711 in = (void *)(mod_base + l->fileofs);
4713 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
4715 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
4716 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
4717 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
4718 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8\n", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
4719 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
4720 if (l->filelen < totalchains + (int)sizeof(*in))
4721 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);
4723 loadmodel->brush.data_pvsclusters = Mem_Alloc(loadmodel->mempool, totalchains);
4724 memcpy(loadmodel->brush.data_pvsclusters, (qbyte *)(in + 1), totalchains);
4727 static void Mod_Q3BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
4729 int i, j, k, index[3];
4730 float transformed[3], blend1, blend2, blend, yaw, pitch, sinpitch;
4731 q3dlightgrid_t *a, *s;
4732 // FIXME: write this
4733 if (!model->brushq3.num_lightgrid)
4735 ambientcolor[0] = 1;
4736 ambientcolor[1] = 1;
4737 ambientcolor[2] = 1;
4740 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
4741 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
4742 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
4743 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
4744 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
4745 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
4746 index[0] = (int)floor(transformed[0]);
4747 index[1] = (int)floor(transformed[1]);
4748 index[2] = (int)floor(transformed[2]);
4749 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
4750 // now lerp the values
4751 VectorClear(diffusenormal);
4752 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
4753 for (k = 0;k < 2;k++)
4755 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
4756 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
4758 for (j = 0;j < 2;j++)
4760 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
4761 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
4763 for (i = 0;i < 2;i++)
4765 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0])));
4766 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
4768 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
4769 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
4770 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
4771 pitch = s->diffusepitch * M_PI / 128;
4772 yaw = s->diffuseyaw * M_PI / 128;
4773 sinpitch = sin(pitch);
4774 diffusenormal[0] += blend * (cos(yaw) * sinpitch);
4775 diffusenormal[1] += blend * (sin(yaw) * sinpitch);
4776 diffusenormal[2] += blend * (cos(pitch));
4777 //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)));
4781 VectorNormalize(diffusenormal);
4782 //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]);
4785 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, model_t *model, mnode_t *node, const vec3_t point, int markframe)
4790 // find which leaf the point is in
4792 node = node->children[DotProduct(point, node->plane->normal) < node->plane->dist];
4793 // point trace the brushes
4794 leaf = (mleaf_t *)node;
4795 for (i = 0;i < leaf->numleafbrushes;i++)
4797 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
4798 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
4800 brush->markframe = markframe;
4801 Collision_TracePointBrushFloat(trace, point, brush);
4804 // can't do point traces on curves (they have no thickness)
4807 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)
4809 int i, startside, endside;
4810 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
4812 msurface_t *surface;
4814 if (startfrac > trace->realfraction)
4816 // note: all line fragments past first impact fraction are ignored
4817 if (VectorCompare(start, end))
4819 // find which leaf the point is in
4821 node = node->children[DotProduct(start, node->plane->normal) < node->plane->dist];
4825 // find which nodes the line is in and recurse for them
4828 // recurse down node sides
4829 dist1 = PlaneDiff(start, node->plane);
4830 dist2 = PlaneDiff(end, node->plane);
4831 startside = dist1 < 0;
4832 endside = dist2 < 0;
4833 if (startside == endside)
4835 // most of the time the line fragment is on one side of the plane
4836 node = node->children[startside];
4840 // line crosses node plane, split the line
4841 midfrac = dist1 / (dist1 - dist2);
4842 VectorLerp(start, midfrac, end, mid);
4843 // take the near side first
4844 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
4845 if (midfrac <= trace->realfraction)
4846 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
4852 nodesegmentmins[0] = min(start[0], end[0]);
4853 nodesegmentmins[1] = min(start[1], end[1]);
4854 nodesegmentmins[2] = min(start[2], end[2]);
4855 nodesegmentmaxs[0] = max(start[0], end[0]);
4856 nodesegmentmaxs[1] = max(start[1], end[1]);
4857 nodesegmentmaxs[2] = max(start[2], end[2]);
4858 // line trace the brushes
4859 leaf = (mleaf_t *)node;
4860 for (i = 0;i < leaf->numleafbrushes;i++)
4862 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
4863 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
4865 brush->markframe = markframe;
4866 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
4867 if (startfrac > trace->realfraction)
4871 // can't do point traces on curves (they have no thickness)
4872 if (mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
4874 // line trace the curves
4875 for (i = 0;i < leaf->numleafsurfaces;i++)
4877 surface = model->brush.data_surfaces + leaf->firstleafsurface[i];
4878 if (surface->num_collisiontriangles && surface->collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
4880 surface->collisionmarkframe = markframe;
4881 Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
4882 if (startfrac > trace->realfraction)
4889 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)
4893 float nodesegmentmins[3], nodesegmentmaxs[3];
4896 msurface_t *surface;
4898 // find which nodes the line is in and recurse for them
4901 // recurse down node sides
4902 int startside, endside;
4903 float dist1near, dist1far, dist2near, dist2far;
4904 BoxPlaneCornerDistances(thisbrush_start->mins, thisbrush_start->maxs, node->plane, &dist1near, &dist1far);
4905 BoxPlaneCornerDistances(thisbrush_end->mins, thisbrush_end->maxs, node->plane, &dist2near, &dist2far);
4906 startside = dist1near < 0;
4907 startside = dist1near < 0 ? (dist1far < 0 ? 1 : 2) : (dist1far < 0 ? 2 : 0);
4908 endside = dist2near < 0 ? (dist2far < 0 ? 1 : 2) : (dist2far < 0 ? 2 : 0);
4909 if (startside == 2 || endside == 2)
4911 // brushes cross plane
4912 // do not clip anything, just take both sides
4913 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
4914 node = node->children[1];
4921 node = node->children[0];
4926 //midf0 = dist1near / (dist1near - dist2near);
4927 //midf1 = dist1far / (dist1far - dist2far);
4928 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
4929 node = node->children[1];
4937 //midf0 = dist1near / (dist1near - dist2near);
4938 //midf1 = dist1far / (dist1far - dist2far);
4939 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
4940 node = node->children[1];
4945 node = node->children[1];
4950 if (dist1near < 0 && dist2near < 0 && dist1far < 0 && dist2far < 0){node = node->children[1];continue;}
4951 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;}
4952 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;}
4953 if (dist1near < 0 && dist2near < 0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4954 if (dist1near < 0 && dist2near >= 0 && dist1far < 0 && dist2far < 0){node = node->children[1];continue;}
4955 if (dist1near < 0 && dist2near >= 0 && dist1far < 0 && dist2far >= 0){}
4956 if (dist1near < 0 && dist2near >= 0 && dist1far >= 0 && dist2far < 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4957 if (dist1near < 0 && dist2near >= 0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4958 if (dist1near >= 0 && dist2near < 0 && dist1far < 0 && dist2far < 0){node = node->children[1];continue;}
4959 if (dist1near >= 0 && dist2near < 0 && dist1far < 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
4960 if (dist1near >= 0 && dist2near < 0 && dist1far >= 0 && dist2far < 0){}
4961 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;}
4962 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;}
4963 if (dist1near >= 0 && dist2near >= 0 && dist1far < 0 && dist2far >= 0){node = node->children[0];continue;}
4964 if (dist1near >= 0 && dist2near >= 0 && dist1far >= 0 && dist2far < 0){node = node->children[0];continue;}
4965 if (dist1near >= 0 && dist2near >= 0 && dist1far >= 0 && dist2far >= 0){node = node->children[0];continue;}
4967 if (dist2near < 0) // d1n<0 && d2n<0
4969 if (dist2near < 0) // d1n<0 && d2n<0
4971 if (dist2near < 0) // d1n<0 && d2n<0
4974 else // d1n<0 && d2n>0
4978 else // d1n<0 && d2n>0
4980 if (dist2near < 0) // d1n<0 && d2n<0
4983 else // d1n<0 && d2n>0
4988 else // d1n<0 && d2n>0
4994 if (dist2near < 0) // d1n>0 && d2n<0
4997 else // d1n>0 && d2n>0
5001 if (dist1near < 0 == dist1far < 0 == dist2near < 0 == dist2far < 0)
5003 node = node->children[startside];
5006 if (dist1near < dist2near)
5011 node = node->children[0];
5016 node = node->children[1];
5019 // dist1near < 0 && dist2far >= 0
5025 startside = dist1near < 0 ? (dist1far < 0 ? 1 : 2) : (dist1far < 0 ? 2 : 0);
5026 endside = dist2near < 0 ? (dist2far < 0 ? 1 : 2) : (dist2far < 0 ? 2 : 0);
5027 if (startside == 2 || endside == 2)
5029 // brushes cross plane
5030 // do not clip anything, just take both sides
5031 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5032 node = node->children[1];
5034 else if (startside == endside)
5035 node = node->children[startside];
5036 else if (startside == 0) // endside = 1 (start infront, end behind)
5039 else // startside == 1 endside = 0 (start behind, end infront)
5045 node = node->children[startside];
5048 // start and end brush cross plane
5054 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5055 node = node->children[1];
5056 else if (dist1near < 0 && dist1far < 0 && dist2near >= 0 && dist2far >= 0)
5057 else if (dist1near >= 0 && dist1far >= 0 && dist2near < 0 && dist2far < 0)
5058 else if (dist1near >= 0 && dist1far >= 0 && dist2near >= 0 && dist2far >= 0)
5059 node = node->children[0];
5061 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5062 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5063 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5064 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5065 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5068 else if (dist1near >= 0 && dist1far >= 0)
5071 else // mixed (lying on plane)
5075 if (dist2near < 0 && dist2far < 0)
5079 node = node->children[1];
5081 if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5082 node = node->children[0];
5083 else if (dist1near >= 0 && dist1far >= 0 && dist2near >= 0 && dist2far >= 0)
5084 node = node->children[1];
5088 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5089 node = node->children[1];
5091 sides = dist1near || dist1near < 0 | dist1far < 0 | dist2near < 0 | dist
5092 startside = dist1 < 0;
5093 endside = dist2 < 0;
5094 if (startside == endside)
5096 // most of the time the line fragment is on one side of the plane
5097 node = node->children[startside];
5101 // line crosses node plane, split the line
5102 midfrac = dist1 / (dist1 - dist2);
5103 VectorLerp(start, midfrac, end, mid);
5104 // take the near side first
5105 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5106 if (midfrac <= trace->fraction)
5107 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5115 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5116 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5117 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5118 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5119 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5120 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5121 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5125 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5126 node = node->children[1];
5129 // FIXME: could be made faster by copying TraceLine code and making it use
5130 // box plane distances... (variant on the BoxOnPlaneSide code)
5133 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5134 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5135 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5136 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5137 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5138 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5139 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5143 if (mod_q3bsp_debugtracebrush.integer == 2)
5145 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5146 node = node->children[1];
5149 else if (mod_q3bsp_debugtracebrush.integer == 1)
5151 // recurse down node sides
5152 sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5155 // segment box crosses plane
5156 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5157 node = node->children[1];
5160 // take whichever side the segment box is on
5161 node = node->children[sides - 1];
5166 // recurse down node sides
5167 sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5170 // segment box crosses plane
5171 // now check start and end brush boxes to handle a lot of 'diagonal' cases more efficiently...
5172 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, node->plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, node->plane);
5175 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5176 node = node->children[1];
5180 // take whichever side the segment box is on
5181 node = node->children[sides - 1];
5187 // FIXME: could be made faster by copying TraceLine code and making it use
5188 // box plane distances... (variant on the BoxOnPlaneSide code)
5191 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5192 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5193 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5194 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5195 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5196 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5197 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5201 if (mod_q3bsp_debugtracebrush.integer == 2)
5203 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5204 node = node->children[1];
5206 else if (mod_q3bsp_debugtracebrush.integer == 1)
5208 // recurse down node sides
5209 sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5212 // segment box crosses plane
5213 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5214 node = node->children[1];
5218 // take whichever side the segment box is on
5219 node = node->children[sides - 1];
5224 // recurse down node sides
5225 sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5228 // segment box crosses plane
5229 // now check start and end brush boxes to handle a lot of 'diagonal' cases more efficiently...
5230 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, node->plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, node->plane);
5233 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5237 // take whichever side the segment box is on
5238 node = node->children[sides - 1];
5243 leaf = (mleaf_t *)node;
5244 for (i = 0;i < leaf->numleafbrushes;i++)
5246 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
5247 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
5249 brush->markframe = markframe;
5250 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
5253 if (mod_q3bsp_curves_collisions.integer)
5255 for (i = 0;i < leaf->numleafsurfaces;i++)
5257 surface = model->brush.data_surfaces + leaf->firstleafsurface[i];
5258 if (surface->num_collisiontriangles && surface->collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
5260 surface->collisionmarkframe = markframe;
5261 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5267 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)
5270 float segmentmins[3], segmentmaxs[3];
5271 colbrushf_t *thisbrush_start, *thisbrush_end;
5272 matrix4x4_t startmatrix, endmatrix;
5273 static int markframe = 0;
5274 msurface_t *surface;
5276 memset(trace, 0, sizeof(*trace));
5277 trace->fraction = 1;
5278 trace->realfraction = 1;
5279 trace->hitsupercontentsmask = hitsupercontentsmask;
5280 Matrix4x4_CreateIdentity(&startmatrix);
5281 Matrix4x4_CreateIdentity(&endmatrix);
5282 segmentmins[0] = min(boxstartmins[0], boxendmins[0]);
5283 segmentmins[1] = min(boxstartmins[1], boxendmins[1]);
5284 segmentmins[2] = min(boxstartmins[2], boxendmins[2]);
5285 segmentmaxs[0] = max(boxstartmaxs[0], boxendmaxs[0]);
5286 segmentmaxs[1] = max(boxstartmaxs[1], boxendmaxs[1]);
5287 segmentmaxs[2] = max(boxstartmaxs[2], boxendmaxs[2]);
5288 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxstartmins, boxstartmaxs) && VectorCompare(boxendmins, boxendmaxs))
5290 if (VectorCompare(boxstartmins, boxendmins))
5293 if (model->brush.submodel)
5295 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5296 if (brush->colbrushf)
5297 Collision_TracePointBrushFloat(trace, boxstartmins, brush->colbrushf);
5300 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, boxstartmins, ++markframe);
5305 if (model->brush.submodel)
5307 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5308 if (brush->colbrushf)
5309 Collision_TraceLineBrushFloat(trace, boxstartmins, boxendmins, brush->colbrushf, brush->colbrushf);
5310 if (mod_q3bsp_curves_collisions.integer)
5311 for (i = 0, surface = model->brush.data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
5312 if (surface->num_collisiontriangles)
5313 Collision_TraceLineTriangleMeshFloat(trace, boxstartmins, boxendmins, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5316 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, boxstartmins, boxendmins, 0, 1, boxstartmins, boxendmins, ++markframe, segmentmins, segmentmaxs);
5321 // box trace, performed as brush trace
5322 thisbrush_start = Collision_BrushForBox(&startmatrix, boxstartmins, boxstartmaxs);
5323 thisbrush_end = Collision_BrushForBox(&endmatrix, boxendmins, boxendmaxs);
5324 if (model->brush.submodel)
5326 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5327 if (brush->colbrushf)
5328 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush->colbrushf, brush->colbrushf);
5329 if (mod_q3bsp_curves_collisions.integer)
5330 for (i = 0, surface = model->brush.data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
5331 if (surface->num_collisiontriangles)
5332 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5335 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, thisbrush_start, thisbrush_end, ++markframe, segmentmins, segmentmaxs);
5339 static int Mod_Q3BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents)
5341 int supercontents = 0;
5342 if (nativecontents & CONTENTSQ3_SOLID)
5343 supercontents |= SUPERCONTENTS_SOLID;
5344 if (nativecontents & CONTENTSQ3_WATER)
5345 supercontents |= SUPERCONTENTS_WATER;
5346 if (nativecontents & CONTENTSQ3_SLIME)
5347 supercontents |= SUPERCONTENTS_SLIME;
5348 if (nativecontents & CONTENTSQ3_LAVA)
5349 supercontents |= SUPERCONTENTS_LAVA;
5350 if (nativecontents & CONTENTSQ3_BODY)
5351 supercontents |= SUPERCONTENTS_BODY;
5352 if (nativecontents & CONTENTSQ3_CORPSE)
5353 supercontents |= SUPERCONTENTS_CORPSE;
5354 if (nativecontents & CONTENTSQ3_NODROP)
5355 supercontents |= SUPERCONTENTS_NODROP;
5356 return supercontents;
5359 static int Mod_Q3BSP_NativeContentsFromSuperContents(model_t *model, int supercontents)
5361 int nativecontents = 0;
5362 if (supercontents & SUPERCONTENTS_SOLID)
5363 nativecontents |= CONTENTSQ3_SOLID;
5364 if (supercontents & SUPERCONTENTS_WATER)
5365 nativecontents |= CONTENTSQ3_WATER;
5366 if (supercontents & SUPERCONTENTS_SLIME)
5367 nativecontents |= CONTENTSQ3_SLIME;
5368 if (supercontents & SUPERCONTENTS_LAVA)
5369 nativecontents |= CONTENTSQ3_LAVA;
5370 if (supercontents & SUPERCONTENTS_BODY)
5371 nativecontents |= CONTENTSQ3_BODY;
5372 if (supercontents & SUPERCONTENTS_CORPSE)
5373 nativecontents |= CONTENTSQ3_CORPSE;
5374 if (supercontents & SUPERCONTENTS_NODROP)
5375 nativecontents |= CONTENTSQ3_NODROP;
5376 return nativecontents;
5379 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
5384 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
5385 node = node->children[1];
5387 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
5388 if (loadmodel->brush.num_leafs < numleafs)
5389 loadmodel->brush.num_leafs = numleafs;
5392 void Mod_Q3BSP_Load(model_t *mod, void *buffer)
5394 int i, j, numshadowmeshtriangles;
5395 q3dheader_t *header;
5396 float corner[3], yawradius, modelradius;
5397 msurface_t *surface;
5399 mod->type = mod_brushq3;
5400 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
5403 header = (q3dheader_t *)buffer;
5405 i = LittleLong(header->version);
5406 if (i != Q3BSPVERSION)
5407 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
5408 if (mod->isworldmodel)
5409 Cvar_SetValue("halflifebsp", false);
5411 mod->soundfromcenter = true;
5412 mod->TraceBox = Mod_Q3BSP_TraceBox;
5413 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
5414 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
5415 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
5416 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
5417 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
5418 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
5419 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
5420 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
5421 mod->Draw = R_Q1BSP_Draw;
5422 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
5423 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
5424 mod->DrawLight = R_Q1BSP_DrawLight;
5426 mod_base = (qbyte *)header;
5428 // swap all the lumps
5429 header->ident = LittleLong(header->ident);
5430 header->version = LittleLong(header->version);
5431 for (i = 0;i < Q3HEADER_LUMPS;i++)
5433 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
5434 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
5437 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
5438 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
5439 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
5440 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
5441 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
5442 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
5443 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
5444 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
5445 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS]);
5446 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
5447 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
5448 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
5449 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
5450 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
5451 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
5452 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
5453 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
5454 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
5456 // make a single combined shadow mesh to allow optimized shadow volume creation
5457 numshadowmeshtriangles = 0;
5458 for (j = 0, surface = loadmodel->brush.data_surfaces;j < loadmodel->brush.num_surfaces;j++, surface++)
5460 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
5461 numshadowmeshtriangles += surface->mesh.num_triangles;
5463 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
5464 for (j = 0, surface = loadmodel->brush.data_surfaces;j < loadmodel->brush.num_surfaces;j++, surface++)
5465 Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, surface->mesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->mesh.num_triangles, surface->mesh.data_element3i);
5466 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true);
5467 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
5469 loadmodel->brush.num_leafs = 0;
5470 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
5472 if (loadmodel->isworldmodel)
5474 // clear out any stale submodels or worldmodels lying around
5475 // if we did this clear before now, an error might abort loading and
5476 // leave things in a bad state
5477 Mod_RemoveStaleWorldModels(loadmodel);
5481 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
5486 // LordHavoc: only register submodels if it is the world
5487 // (prevents external bsp models from replacing world submodels with
5489 if (!loadmodel->isworldmodel)
5491 // duplicate the basic information
5492 sprintf(name, "*%i", i);
5493 mod = Mod_FindName(name);
5495 strcpy(mod->name, name);
5496 // textures and memory belong to the main model
5497 mod->texturepool = NULL;
5498 mod->mempool = NULL;
5499 mod->brush.GetPVS = NULL;
5500 mod->brush.FatPVS = NULL;
5501 mod->brush.BoxTouchingPVS = NULL;
5502 mod->brush.BoxTouchingVisibleLeafs = NULL;
5503 mod->brush.LightPoint = NULL;
5504 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
5506 mod->brush.submodel = i;
5508 // make the model surface list (used by shadowing/lighting)
5509 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
5510 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
5511 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
5512 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
5513 mod->surfacelist = Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->surfacelist));
5514 for (j = 0;j < mod->nummodelsurfaces;j++)
5515 mod->surfacelist[j] = mod->firstmodelsurface + j;
5517 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
5518 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
5519 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5520 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5521 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5522 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
5523 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
5524 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5525 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5526 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
5527 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
5528 mod->yawmins[2] = mod->normalmins[2];
5529 mod->yawmaxs[2] = mod->normalmaxs[2];
5530 mod->radius = modelradius;
5531 mod->radius2 = modelradius * modelradius;
5533 for (j = 0;j < mod->nummodelsurfaces;j++)
5534 if (mod->brush.data_surfaces[j + mod->firstmodelsurface].texture->surfaceflags & Q3SURFACEFLAG_SKY)
5536 if (j < mod->nummodelsurfaces)
5537 mod->DrawSky = R_Q1BSP_DrawSky;
5541 void Mod_IBSP_Load(model_t *mod, void *buffer)
5543 int i = LittleLong(((int *)buffer)[1]);
5544 if (i == Q3BSPVERSION)
5545 Mod_Q3BSP_Load(mod,buffer);
5546 else if (i == Q2BSPVERSION)
5547 Mod_Q2BSP_Load(mod,buffer);
5549 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i\n", i);
5552 void Mod_MAP_Load(model_t *mod, void *buffer)
5554 Host_Error("Mod_MAP_Load: not yet implemented\n");