2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
30 cvar_t mod_bsp_portalize = {0, "mod_bsp_portalize", "1", "enables portal generation from BSP tree (may take several seconds per map), used by r_drawportals, r_useportalculling, r_shadow_realtime_world_compileportalculling, sv_cullentities_portal"};
31 cvar_t r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
34 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
35 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
38 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
39 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
40 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t r_trippy = {0, "r_trippy", "0", "easter egg"};
42 cvar_t mod_noshader_default_offsetmapping = {CVAR_SAVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
43 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
44 cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
45 cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
46 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
47 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
48 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
49 cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
50 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
51 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
52 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
53 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
55 cvar_t mod_q1bsp_polygoncollisions = {0, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
56 cvar_t mod_collision_bih = {0, "mod_collision_bih", "1", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
57 cvar_t mod_recalculatenodeboxes = {0, "mod_recalculatenodeboxes", "1", "enables use of generated node bounding boxes based on BSP tree portal reconstruction, rather than the node boxes supplied by the map compiler"};
59 static texture_t mod_q1bsp_texture_solid;
60 static texture_t mod_q1bsp_texture_sky;
61 static texture_t mod_q1bsp_texture_lava;
62 static texture_t mod_q1bsp_texture_slime;
63 static texture_t mod_q1bsp_texture_water;
65 void Mod_BrushInit(void)
67 // Cvar_RegisterVariable(&r_subdivide_size);
68 Cvar_RegisterVariable(&mod_bsp_portalize);
69 Cvar_RegisterVariable(&r_novis);
70 Cvar_RegisterVariable(&r_nosurftextures);
71 Cvar_RegisterVariable(&r_subdivisions_tolerance);
72 Cvar_RegisterVariable(&r_subdivisions_mintess);
73 Cvar_RegisterVariable(&r_subdivisions_maxtess);
74 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
75 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
76 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
77 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
78 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
79 Cvar_RegisterVariable(&r_trippy);
80 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
81 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
82 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
83 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
84 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
85 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
86 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
87 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
88 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
89 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
90 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
91 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
92 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
93 Cvar_RegisterVariable(&mod_collision_bih);
94 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
96 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
97 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
98 mod_q1bsp_texture_solid.surfaceflags = 0;
99 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
101 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
102 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
103 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
104 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
106 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
107 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
108 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
109 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
111 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
112 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
113 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
114 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
116 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
117 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
118 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
119 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
122 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
129 // LordHavoc: modified to start at first clip node,
130 // in other words: first node of the (sub)model
131 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
133 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
135 return (mleaf_t *)node;
138 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
142 leaf = Mod_Q1BSP_PointInLeaf(model, p);
145 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
148 memcpy(out, leaf->ambient_sound_level, i);
154 memset(out, 0, outsize);
157 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
160 int nodestackindex = 0;
161 mnode_t *node, *nodestack[1024];
162 if (!model->brush.num_pvsclusters)
164 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
170 // node - recurse down the BSP tree
171 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
175 return -1; // ERROR: NAN bounding box!
176 // box is on one side of plane, take that path
177 node = node->children[sides-1];
181 // box crosses plane, take one path and remember the other
182 if (nodestackindex < 1024)
183 nodestack[nodestackindex++] = node->children[0];
184 node = node->children[1];
190 // leaf - add clusterindex to list
191 if (numclusters < maxclusters)
192 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
196 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
200 if (nodestackindex < 1024)
201 nodestack[nodestackindex++] = node->children[0];
202 node = node->children[1];
207 // leaf - add clusterindex to list
208 if (numclusters < maxclusters)
209 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
214 // try another path we didn't take earlier
215 if (nodestackindex == 0)
217 node = nodestack[--nodestackindex];
219 // return number of clusters found (even if more than the maxclusters)
223 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
225 int nodestackindex = 0;
226 mnode_t *node, *nodestack[1024];
227 if (!model->brush.num_pvsclusters)
229 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
235 // node - recurse down the BSP tree
236 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
240 return -1; // ERROR: NAN bounding box!
241 // box is on one side of plane, take that path
242 node = node->children[sides-1];
246 // box crosses plane, take one path and remember the other
247 if (nodestackindex < 1024)
248 nodestack[nodestackindex++] = node->children[0];
249 node = node->children[1];
255 // leaf - check cluster bit
256 int clusterindex = ((mleaf_t *)node)->clusterindex;
257 if (CHECKPVSBIT(pvs, clusterindex))
259 // it is visible, return immediately with the news
264 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
268 if (nodestackindex < 1024)
269 nodestack[nodestackindex++] = node->children[0];
270 node = node->children[1];
275 // leaf - check cluster bit
276 int clusterindex = ((mleaf_t *)node)->clusterindex;
277 if (CHECKPVSBIT(pvs, clusterindex))
279 // it is visible, return immediately with the news
285 // nothing to see here, try another path we didn't take earlier
286 if (nodestackindex == 0)
288 node = nodestack[--nodestackindex];
294 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
296 int nodestackindex = 0;
297 mnode_t *node, *nodestack[1024];
298 if (!model->brush.num_leafs)
300 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
306 // node - recurse down the BSP tree
307 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
311 return -1; // ERROR: NAN bounding box!
312 // box is on one side of plane, take that path
313 node = node->children[sides-1];
317 // box crosses plane, take one path and remember the other
318 if (nodestackindex < 1024)
319 nodestack[nodestackindex++] = node->children[0];
320 node = node->children[1];
326 // leaf - check cluster bit
327 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
328 if (CHECKPVSBIT(pvs, clusterindex))
330 // it is visible, return immediately with the news
335 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
339 if (nodestackindex < 1024)
340 nodestack[nodestackindex++] = node->children[0];
341 node = node->children[1];
346 // leaf - check cluster bit
347 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
348 if (CHECKPVSBIT(pvs, clusterindex))
350 // it is visible, return immediately with the news
356 // nothing to see here, try another path we didn't take earlier
357 if (nodestackindex == 0)
359 node = nodestack[--nodestackindex];
365 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
367 int nodestackindex = 0;
368 mnode_t *node, *nodestack[1024];
369 if (!model->brush.num_leafs)
371 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
377 // node - recurse down the BSP tree
378 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
382 return -1; // ERROR: NAN bounding box!
383 // box is on one side of plane, take that path
384 node = node->children[sides-1];
388 // box crosses plane, take one path and remember the other
389 if (nodestackindex < 1024)
390 nodestack[nodestackindex++] = node->children[0];
391 node = node->children[1];
397 // leaf - check if it is visible
398 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
400 // it is visible, return immediately with the news
405 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
409 if (nodestackindex < 1024)
410 nodestack[nodestackindex++] = node->children[0];
411 node = node->children[1];
416 // leaf - check if it is visible
417 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
419 // it is visible, return immediately with the news
425 // nothing to see here, try another path we didn't take earlier
426 if (nodestackindex == 0)
428 node = nodestack[--nodestackindex];
434 typedef struct findnonsolidlocationinfo_s
437 vec3_t absmin, absmax;
443 findnonsolidlocationinfo_t;
445 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
448 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
450 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
451 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
452 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
453 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
454 VectorSubtract(vert[1], vert[0], edge[0]);
455 VectorSubtract(vert[2], vert[1], edge[1]);
456 CrossProduct(edge[1], edge[0], facenormal);
457 if (facenormal[0] || facenormal[1] || facenormal[2])
459 VectorNormalize(facenormal);
460 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
461 if (f <= info->bestdist && f >= -info->bestdist)
463 VectorSubtract(vert[0], vert[2], edge[2]);
464 VectorNormalize(edge[0]);
465 VectorNormalize(edge[1]);
466 VectorNormalize(edge[2]);
467 CrossProduct(facenormal, edge[0], edgenormal[0]);
468 CrossProduct(facenormal, edge[1], edgenormal[1]);
469 CrossProduct(facenormal, edge[2], edgenormal[2]);
471 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
472 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
473 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
475 // we got lucky, the center is within the face
476 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
480 if (info->bestdist > dist)
482 info->bestdist = dist;
483 VectorScale(facenormal, (info->radius - -dist), info->nudge);
488 if (info->bestdist > dist)
490 info->bestdist = dist;
491 VectorScale(facenormal, (info->radius - dist), info->nudge);
497 // check which edge or vertex the center is nearest
498 for (i = 0;i < 3;i++)
500 f = DotProduct(info->center, edge[i]);
501 if (f >= DotProduct(vert[0], edge[i])
502 && f <= DotProduct(vert[1], edge[i]))
505 VectorMA(info->center, -f, edge[i], point);
506 dist = sqrt(DotProduct(point, point));
507 if (info->bestdist > dist)
509 info->bestdist = dist;
510 VectorScale(point, (info->radius / dist), info->nudge);
512 // skip both vertex checks
513 // (both are further away than this edge)
518 // not on edge, check first vertex of edge
519 VectorSubtract(info->center, vert[i], point);
520 dist = sqrt(DotProduct(point, point));
521 if (info->bestdist > dist)
523 info->bestdist = dist;
524 VectorScale(point, (info->radius / dist), info->nudge);
533 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
535 int surfacenum, k, *mark;
537 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
539 surface = info->model->data_surfaces + *mark;
540 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
542 if(surface->deprecatedq3num_bboxstride > 0)
545 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
546 for(i = 0; i < cnt; ++i)
548 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
550 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
552 tri = i * surface->deprecatedq3num_bboxstride + k;
553 if(tri >= surface->num_triangles)
555 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
562 for (k = 0;k < surface->num_triangles;k++)
564 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
571 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
575 float f = PlaneDiff(info->center, node->plane);
576 if (f >= -info->bestdist)
577 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
578 if (f <= info->bestdist)
579 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
583 if (((mleaf_t *)node)->numleafsurfaces)
584 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
588 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
591 findnonsolidlocationinfo_t info;
597 VectorCopy(in, info.center);
598 info.radius = radius;
603 VectorClear(info.nudge);
604 info.bestdist = radius;
605 VectorCopy(info.center, info.absmin);
606 VectorCopy(info.center, info.absmax);
607 info.absmin[0] -= info.radius + 1;
608 info.absmin[1] -= info.radius + 1;
609 info.absmin[2] -= info.radius + 1;
610 info.absmax[0] += info.radius + 1;
611 info.absmax[1] += info.radius + 1;
612 info.absmax[2] += info.radius + 1;
613 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
614 VectorAdd(info.center, info.nudge, info.center);
616 while (info.bestdist < radius && ++i < 10);
617 VectorCopy(info.center, out);
620 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
622 switch(nativecontents)
627 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
629 return SUPERCONTENTS_WATER;
631 return SUPERCONTENTS_SLIME;
633 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
635 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
640 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
642 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
643 return CONTENTS_SOLID;
644 if (supercontents & SUPERCONTENTS_SKY)
646 if (supercontents & SUPERCONTENTS_LAVA)
647 return CONTENTS_LAVA;
648 if (supercontents & SUPERCONTENTS_SLIME)
649 return CONTENTS_SLIME;
650 if (supercontents & SUPERCONTENTS_WATER)
651 return CONTENTS_WATER;
652 return CONTENTS_EMPTY;
655 typedef struct RecursiveHullCheckTraceInfo_s
657 // the hull we're tracing through
660 // the trace structure to fill in
663 // start, end, and end - start (in model space)
668 RecursiveHullCheckTraceInfo_t;
670 // 1/32 epsilon to keep floating point happy
671 #define DIST_EPSILON (0.03125)
673 #define HULLCHECKSTATE_EMPTY 0
674 #define HULLCHECKSTATE_SOLID 1
675 #define HULLCHECKSTATE_DONE 2
677 extern cvar_t collision_prefernudgedfraction;
678 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
680 // status variables, these don't need to be saved on the stack when
681 // recursing... but are because this should be thread-safe
682 // (note: tracing against a bbox is not thread-safe, yet)
687 // variables that need to be stored on the stack when recursing
692 // LordHavoc: a goto! everyone flee in terror... :)
697 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
698 if (!t->trace->startfound)
700 t->trace->startfound = true;
701 t->trace->startsupercontents |= num;
703 if (num & SUPERCONTENTS_LIQUIDSMASK)
704 t->trace->inwater = true;
706 t->trace->inopen = true;
707 if (num & SUPERCONTENTS_SOLID)
708 t->trace->hittexture = &mod_q1bsp_texture_solid;
709 else if (num & SUPERCONTENTS_SKY)
710 t->trace->hittexture = &mod_q1bsp_texture_sky;
711 else if (num & SUPERCONTENTS_LAVA)
712 t->trace->hittexture = &mod_q1bsp_texture_lava;
713 else if (num & SUPERCONTENTS_SLIME)
714 t->trace->hittexture = &mod_q1bsp_texture_slime;
716 t->trace->hittexture = &mod_q1bsp_texture_water;
717 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
718 t->trace->hitsupercontents = num;
719 if (num & t->trace->hitsupercontentsmask)
721 // if the first leaf is solid, set startsolid
722 if (t->trace->allsolid)
723 t->trace->startsolid = true;
724 #if COLLISIONPARANOID >= 3
727 return HULLCHECKSTATE_SOLID;
731 t->trace->allsolid = false;
732 #if COLLISIONPARANOID >= 3
735 return HULLCHECKSTATE_EMPTY;
739 // find the point distances
740 node = t->hull->clipnodes + num;
742 plane = t->hull->planes + node->planenum;
745 t1 = p1[plane->type] - plane->dist;
746 t2 = p2[plane->type] - plane->dist;
750 t1 = DotProduct (plane->normal, p1) - plane->dist;
751 t2 = DotProduct (plane->normal, p2) - plane->dist;
758 #if COLLISIONPARANOID >= 3
761 num = node->children[1];
770 #if COLLISIONPARANOID >= 3
773 num = node->children[0];
779 // the line intersects, find intersection point
780 // LordHavoc: this uses the original trace for maximum accuracy
781 #if COLLISIONPARANOID >= 3
786 t1 = t->start[plane->type] - plane->dist;
787 t2 = t->end[plane->type] - plane->dist;
791 t1 = DotProduct (plane->normal, t->start) - plane->dist;
792 t2 = DotProduct (plane->normal, t->end) - plane->dist;
795 midf = t1 / (t1 - t2);
796 midf = bound(p1f, midf, p2f);
797 VectorMA(t->start, midf, t->dist, mid);
799 // recurse both sides, front side first
800 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
801 // if this side is not empty, return what it is (solid or done)
802 if (ret != HULLCHECKSTATE_EMPTY)
805 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
806 // if other side is not solid, return what it is (empty or done)
807 if (ret != HULLCHECKSTATE_SOLID)
810 // front is air and back is solid, this is the impact point...
813 t->trace->plane.dist = -plane->dist;
814 VectorNegate (plane->normal, t->trace->plane.normal);
818 t->trace->plane.dist = plane->dist;
819 VectorCopy (plane->normal, t->trace->plane.normal);
822 // calculate the true fraction
823 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
824 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
825 midf = t1 / (t1 - t2);
826 t->trace->realfraction = bound(0, midf, 1);
828 // calculate the return fraction which is nudged off the surface a bit
829 midf = (t1 - DIST_EPSILON) / (t1 - t2);
830 t->trace->fraction = bound(0, midf, 1);
832 if (collision_prefernudgedfraction.integer)
833 t->trace->realfraction = t->trace->fraction;
835 #if COLLISIONPARANOID >= 3
838 return HULLCHECKSTATE_DONE;
841 //#if COLLISIONPARANOID < 2
842 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
845 mclipnode_t *nodes = t->hull->clipnodes;
846 mplane_t *planes = t->hull->planes;
848 VectorCopy(t->start, point);
851 plane = planes + nodes[num].planenum;
852 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
854 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
855 t->trace->startsupercontents |= num;
856 if (num & SUPERCONTENTS_LIQUIDSMASK)
857 t->trace->inwater = true;
859 t->trace->inopen = true;
860 if (num & t->trace->hitsupercontentsmask)
862 t->trace->allsolid = t->trace->startsolid = true;
863 return HULLCHECKSTATE_SOLID;
867 t->trace->allsolid = t->trace->startsolid = false;
868 return HULLCHECKSTATE_EMPTY;
873 static void Mod_Q1BSP_TracePoint(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
875 RecursiveHullCheckTraceInfo_t rhc;
877 memset(&rhc, 0, sizeof(rhc));
878 memset(trace, 0, sizeof(trace_t));
880 rhc.trace->fraction = 1;
881 rhc.trace->realfraction = 1;
882 rhc.trace->allsolid = true;
883 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
884 VectorCopy(start, rhc.start);
885 VectorCopy(start, rhc.end);
886 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
889 static void Mod_Q1BSP_TraceLine(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
891 RecursiveHullCheckTraceInfo_t rhc;
893 if (VectorCompare(start, end))
895 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
899 memset(&rhc, 0, sizeof(rhc));
900 memset(trace, 0, sizeof(trace_t));
902 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
903 rhc.trace->fraction = 1;
904 rhc.trace->realfraction = 1;
905 rhc.trace->allsolid = true;
906 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
907 VectorCopy(start, rhc.start);
908 VectorCopy(end, rhc.end);
909 VectorSubtract(rhc.end, rhc.start, rhc.dist);
910 #if COLLISIONPARANOID >= 2
911 Con_Printf("t(%f %f %f,%f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2]);
912 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
917 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
918 memset(&testtrace, 0, sizeof(trace_t));
919 rhc.trace = &testtrace;
920 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
921 rhc.trace->fraction = 1;
922 rhc.trace->realfraction = 1;
923 rhc.trace->allsolid = true;
924 VectorCopy(test, rhc.start);
925 VectorCopy(test, rhc.end);
926 VectorClear(rhc.dist);
927 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
928 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
929 if (!trace->startsolid && testtrace.startsolid)
930 Con_Printf(" - ended in solid!\n");
934 if (VectorLength2(rhc.dist))
935 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
937 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
941 static void Mod_Q1BSP_TraceBox(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
943 // this function currently only supports same size start and end
945 RecursiveHullCheckTraceInfo_t rhc;
947 if (VectorCompare(boxmins, boxmaxs))
949 if (VectorCompare(start, end))
950 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
952 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
956 memset(&rhc, 0, sizeof(rhc));
957 memset(trace, 0, sizeof(trace_t));
959 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
960 rhc.trace->fraction = 1;
961 rhc.trace->realfraction = 1;
962 rhc.trace->allsolid = true;
963 VectorSubtract(boxmaxs, boxmins, boxsize);
965 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
966 else if (model->brush.ishlbsp)
968 // LordHavoc: this has to have a minor tolerance (the .1) because of
969 // minor float precision errors from the box being transformed around
970 if (boxsize[0] < 32.1)
972 if (boxsize[2] < 54) // pick the nearest of 36 or 72
973 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
975 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
978 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
982 // LordHavoc: this has to have a minor tolerance (the .1) because of
983 // minor float precision errors from the box being transformed around
984 if (boxsize[0] < 32.1)
985 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
987 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
989 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
990 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
991 VectorSubtract(rhc.end, rhc.start, rhc.dist);
992 #if COLLISIONPARANOID >= 2
993 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]);
994 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
999 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1000 memset(&testtrace, 0, sizeof(trace_t));
1001 rhc.trace = &testtrace;
1002 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1003 rhc.trace->fraction = 1;
1004 rhc.trace->realfraction = 1;
1005 rhc.trace->allsolid = true;
1006 VectorCopy(test, rhc.start);
1007 VectorCopy(test, rhc.end);
1008 VectorClear(rhc.dist);
1009 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1010 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1011 if (!trace->startsolid && testtrace.startsolid)
1012 Con_Printf(" - ended in solid!\n");
1016 if (VectorLength2(rhc.dist))
1017 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1019 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1023 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1025 int num = model->brushq1.hulls[0].firstclipnode;
1027 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1028 mplane_t *planes = model->brushq1.hulls[0].planes;
1031 plane = planes + nodes[num].planenum;
1032 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1034 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1037 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, int boxq3surfaceflags, const texture_t *boxtexture)
1041 colplanef_t cbox_planes[6];
1043 cbox.hasaabbplanes = true;
1044 cbox.supercontents = boxsupercontents;
1047 cbox.numtriangles = 0;
1048 cbox.planes = cbox_planes;
1050 cbox.elements = NULL;
1058 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];
1059 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];
1060 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];
1061 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];
1062 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];
1063 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];
1064 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1065 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1066 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1067 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1068 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1069 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1070 memset(trace, 0, sizeof(trace_t));
1071 trace->hitsupercontentsmask = hitsupercontentsmask;
1072 trace->fraction = 1;
1073 trace->realfraction = 1;
1074 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1076 RecursiveHullCheckTraceInfo_t rhc;
1077 static hull_t box_hull;
1078 static mclipnode_t box_clipnodes[6];
1079 static mplane_t box_planes[6];
1080 // fill in a default trace
1081 memset(&rhc, 0, sizeof(rhc));
1082 memset(trace, 0, sizeof(trace_t));
1083 //To keep everything totally uniform, bounding boxes are turned into small
1084 //BSP trees instead of being compared directly.
1085 // create a temp hull from bounding box sizes
1086 box_planes[0].dist = cmaxs[0] - mins[0];
1087 box_planes[1].dist = cmins[0] - maxs[0];
1088 box_planes[2].dist = cmaxs[1] - mins[1];
1089 box_planes[3].dist = cmins[1] - maxs[1];
1090 box_planes[4].dist = cmaxs[2] - mins[2];
1091 box_planes[5].dist = cmins[2] - maxs[2];
1092 #if COLLISIONPARANOID >= 3
1093 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]);
1096 if (box_hull.clipnodes == NULL)
1100 //Set up the planes and clipnodes so that the six floats of a bounding box
1101 //can just be stored out and get a proper hull_t structure.
1103 box_hull.clipnodes = box_clipnodes;
1104 box_hull.planes = box_planes;
1105 box_hull.firstclipnode = 0;
1106 box_hull.lastclipnode = 5;
1108 for (i = 0;i < 6;i++)
1110 box_clipnodes[i].planenum = i;
1114 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1116 box_clipnodes[i].children[side^1] = i + 1;
1118 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1120 box_planes[i].type = i>>1;
1121 box_planes[i].normal[i>>1] = 1;
1125 // trace a line through the generated clipping hull
1126 //rhc.boxsupercontents = boxsupercontents;
1127 rhc.hull = &box_hull;
1129 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1130 rhc.trace->fraction = 1;
1131 rhc.trace->realfraction = 1;
1132 rhc.trace->allsolid = true;
1133 VectorCopy(start, rhc.start);
1134 VectorCopy(end, rhc.end);
1135 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1136 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1137 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1138 if (rhc.trace->startsupercontents)
1139 rhc.trace->startsupercontents = boxsupercontents;
1143 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1145 memset(trace, 0, sizeof(trace_t));
1146 trace->fraction = 1;
1147 trace->realfraction = 1;
1148 if (BoxesOverlap(start, start, cmins, cmaxs))
1150 trace->startsupercontents |= boxsupercontents;
1151 if (hitsupercontentsmask & boxsupercontents)
1153 trace->startsolid = true;
1154 trace->allsolid = true;
1159 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1162 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1163 return trace.fraction == 1;
1166 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(dp_model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
1170 float mid, distz = endz - startz;
1174 return false; // didn't hit anything
1176 switch (node->plane->type)
1179 node = node->children[x < node->plane->dist];
1182 node = node->children[y < node->plane->dist];
1185 side = startz < node->plane->dist;
1186 if ((endz < node->plane->dist) == side)
1188 node = node->children[side];
1191 // found an intersection
1192 mid = node->plane->dist;
1195 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1196 front += startz * node->plane->normal[2];
1197 back += endz * node->plane->normal[2];
1198 side = front < node->plane->dist;
1199 if ((back < node->plane->dist) == side)
1201 node = node->children[side];
1204 // found an intersection
1205 mid = startz + distz * (front - node->plane->dist) / (front - back);
1209 // go down front side
1210 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1211 return true; // hit something
1214 // check for impact on this node
1215 if (node->numsurfaces)
1217 int i, dsi, dti, lmwidth, lmheight;
1219 msurface_t *surface;
1220 unsigned char *lightmap;
1221 int maps, line3, size3;
1224 float scale, w, w00, w01, w10, w11;
1226 surface = model->data_surfaces + node->firstsurface;
1227 for (i = 0;i < node->numsurfaces;i++, surface++)
1229 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1230 continue; // no lightmaps
1232 // location we want to sample in the lightmap
1233 ds = ((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]) * 0.0625f;
1234 dt = ((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]) * 0.0625f;
1239 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1240 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1243 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1245 // calculate bilinear interpolation factors
1246 // and also multiply by fixedpoint conversion factors
1249 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1250 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1251 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1252 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1254 // values for pointer math
1255 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1256 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1258 // look up the pixel
1259 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1261 // bilinear filter each lightmap style, and sum them
1262 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1264 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1265 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1266 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1267 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1268 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1272 return true; // success
1277 // go down back side
1278 node = node->children[side ^ 1];
1280 distz = endz - startz;
1285 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1287 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1288 VectorSet(diffusenormal, 0, 0, 1);
1290 if (!model->brushq1.lightdata)
1292 VectorSet(ambientcolor, 1, 1, 1);
1293 VectorSet(diffusecolor, 0, 0, 0);
1297 Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2] + 0.125, p[2] - 65536);
1300 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1305 const msurface_t *surface;
1310 float edgenormal[3];
1317 surface = model->data_surfaces + node->firstsurface;
1318 for (i = 0;i < node->numsurfaces;i++, surface++)
1320 // skip surfaces whose bounding box does not include the point
1321 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1323 // skip faces with contents we don't care about
1324 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1326 // get the surface normal - since it is flat we know any vertex normal will suffice
1327 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1329 if (DotProduct(t->dist, normal) > 0)
1331 // iterate edges and see if the point is outside one of them
1332 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1334 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1335 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1336 VectorSubtract(v0, v1, edgedir);
1337 CrossProduct(edgedir, normal, edgenormal);
1338 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1341 // if the point is outside one of the edges, it is not within the surface
1342 if (j < surface->num_vertices)
1345 // we hit a surface, this is the impact point...
1346 VectorCopy(normal, t->trace->plane.normal);
1347 t->trace->plane.dist = DotProduct(normal, p);
1349 // calculate the true fraction
1350 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1351 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1352 midf = t1 / (t1 - t2);
1353 t->trace->realfraction = midf;
1355 // calculate the return fraction which is nudged off the surface a bit
1356 midf = (t1 - DIST_EPSILON) / (t1 - t2);
1357 t->trace->fraction = bound(0, midf, 1);
1359 if (collision_prefernudgedfraction.integer)
1360 t->trace->realfraction = t->trace->fraction;
1362 t->trace->hittexture = surface->texture->currentframe;
1363 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1364 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1365 return surface->texture->currentframe;
1370 static int Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, const double p1[3], const double p2[3])
1372 const mplane_t *plane;
1375 double midf, mid[3];
1376 const mleaf_t *leaf;
1380 plane = node->plane;
1381 if (plane->type < 3)
1383 t1 = p1[plane->type] - plane->dist;
1384 t2 = p2[plane->type] - plane->dist;
1388 t1 = DotProduct (plane->normal, p1) - plane->dist;
1389 t2 = DotProduct (plane->normal, p2) - plane->dist;
1395 node = node->children[1];
1404 node = node->children[0];
1410 // the line intersects, find intersection point
1411 // LordHavoc: this uses the original trace for maximum accuracy
1412 if (plane->type < 3)
1414 t1 = t->start[plane->type] - plane->dist;
1415 t2 = t->end[plane->type] - plane->dist;
1419 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1420 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1423 midf = t1 / (t1 - t2);
1424 VectorMA(t->start, midf, t->dist, mid);
1426 // recurse both sides, front side first, return if we hit a surface
1427 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1428 return HULLCHECKSTATE_DONE;
1430 // test each surface on the node
1431 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1432 if (t->trace->hittexture)
1433 return HULLCHECKSTATE_DONE;
1435 // recurse back side
1436 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1438 leaf = (const mleaf_t *)node;
1439 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1440 if (!t->trace->startfound)
1442 t->trace->startfound = true;
1443 t->trace->startsupercontents |= side;
1445 if (side & SUPERCONTENTS_LIQUIDSMASK)
1446 t->trace->inwater = true;
1448 t->trace->inopen = true;
1449 if (side & t->trace->hitsupercontentsmask)
1451 // if the first leaf is solid, set startsolid
1452 if (t->trace->allsolid)
1453 t->trace->startsolid = true;
1454 return HULLCHECKSTATE_SOLID;
1458 t->trace->allsolid = false;
1459 return HULLCHECKSTATE_EMPTY;
1463 static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
1465 RecursiveHullCheckTraceInfo_t rhc;
1467 memset(&rhc, 0, sizeof(rhc));
1468 memset(trace, 0, sizeof(trace_t));
1470 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1471 rhc.trace->fraction = 1;
1472 rhc.trace->realfraction = 1;
1473 rhc.trace->allsolid = true;
1474 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1475 VectorCopy(start, rhc.start);
1476 VectorCopy(end, rhc.end);
1477 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1478 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1479 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1482 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1485 unsigned char *outstart = out;
1486 while (out < outend)
1490 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1500 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun (during zero-run) on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1503 for (c = *in++;c > 0;c--)
1507 Con_Printf("Mod_Q1BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1518 R_Q1BSP_LoadSplitSky
1520 A sky texture is 256*128, with the right side being a masked overlay
1523 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1528 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1529 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1531 // allocate a texture pool if we need it
1532 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1533 loadmodel->texturepool = R_AllocTexturePool();
1535 if (bytesperpixel == 4)
1537 for (y = 0;y < h;y++)
1539 for (x = 0;x < w;x++)
1541 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1542 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1548 // make an average value for the back to avoid
1549 // a fringe on the top level
1558 for (y = 0;y < h;y++)
1560 for (x = 0;x < w;x++)
1562 p = src[x*width+y+w];
1563 r += palette_rgb[p][0];
1564 g += palette_rgb[p][1];
1565 b += palette_rgb[p][2];
1568 bgra.b[2] = r/(w*h);
1569 bgra.b[1] = g/(w*h);
1570 bgra.b[0] = b/(w*h);
1572 for (y = 0;y < h;y++)
1574 for (x = 0;x < w;x++)
1576 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1578 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1583 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1584 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1585 Mem_Free(solidpixels);
1586 Mem_Free(alphapixels);
1589 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1591 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1592 skinframe_t *skinframe;
1594 texture_t *tx, *tx2, *anims[10], *altanims[10];
1595 texture_t backuptex;
1597 unsigned char *data, *mtdata;
1599 char mapname[MAX_QPATH], name[MAX_QPATH];
1600 unsigned char zeroopaque[4], zerotrans[4];
1601 Vector4Set(zeroopaque, 0, 0, 0, 255);
1602 Vector4Set(zerotrans, 0, 0, 0, 128);
1604 loadmodel->data_textures = NULL;
1606 // add two slots for notexture walls and notexture liquids
1609 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1610 m->nummiptex = LittleLong (m->nummiptex);
1611 loadmodel->num_textures = m->nummiptex + 2;
1612 loadmodel->num_texturesperskin = loadmodel->num_textures;
1617 loadmodel->num_textures = 2;
1618 loadmodel->num_texturesperskin = loadmodel->num_textures;
1621 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1623 // fill out all slots with notexture
1624 if (cls.state != ca_dedicated)
1625 skinframe = R_SkinFrame_LoadMissing();
1628 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1630 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1633 if (cls.state != ca_dedicated)
1635 tx->numskinframes = 1;
1636 tx->skinframerate = 1;
1637 tx->skinframes[0] = skinframe;
1638 tx->currentskinframe = tx->skinframes[0];
1640 tx->basematerialflags = MATERIALFLAG_WALL;
1641 if (i == loadmodel->num_textures - 1)
1643 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1644 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1645 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1649 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1650 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1652 tx->currentframe = tx;
1654 // clear water settings
1657 tx->refractfactor = 1;
1658 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1659 tx->reflectfactor = 1;
1660 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1661 tx->r_water_wateralpha = 1;
1662 tx->offsetmapping = OFFSETMAPPING_OFF;
1663 tx->offsetscale = 1;
1664 tx->specularscalemod = 1;
1665 tx->specularpowermod = 1;
1670 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1674 s = loadmodel->name;
1675 if (!strncasecmp(s, "maps/", 5))
1677 FS_StripExtension(s, mapname, sizeof(mapname));
1679 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1681 // LordHavoc: mostly rewritten map texture loader
1682 for (i = 0;i < m->nummiptex;i++)
1684 dofs[i] = LittleLong(dofs[i]);
1685 if (r_nosurftextures.integer)
1689 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1692 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1694 // copy name, but only up to 16 characters
1695 // (the output buffer can hold more than this, but the input buffer is
1697 for (j = 0;j < 16 && dmiptex->name[j];j++)
1698 name[j] = dmiptex->name[j];
1703 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1704 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1707 mtwidth = LittleLong(dmiptex->width);
1708 mtheight = LittleLong(dmiptex->height);
1710 j = LittleLong(dmiptex->offsets[0]);
1714 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1716 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1719 mtdata = (unsigned char *)dmiptex + j;
1722 if ((mtwidth & 15) || (mtheight & 15))
1723 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1725 // LordHavoc: force all names to lowercase
1726 for (j = 0;name[j];j++)
1727 if (name[j] >= 'A' && name[j] <= 'Z')
1728 name[j] += 'a' - 'A';
1730 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1731 backuptex = loadmodel->data_textures[i];
1732 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1734 loadmodel->data_textures[i] = backuptex;
1736 tx = loadmodel->data_textures + i;
1737 strlcpy(tx->name, name, sizeof(tx->name));
1738 tx->width = mtwidth;
1739 tx->height = mtheight;
1741 if (tx->name[0] == '*')
1743 if (!strncmp(tx->name, "*lava", 5))
1745 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1746 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1748 else if (!strncmp(tx->name, "*slime", 6))
1750 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1751 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1755 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1756 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1759 else if (!strncmp(tx->name, "sky", 3))
1761 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1762 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1766 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1767 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1770 if (cls.state != ca_dedicated)
1772 // LordHavoc: HL sky textures are entirely different than quake
1773 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1775 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1777 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), false, false, false, NULL);
1778 if (data && image_width == image_height * 2)
1780 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1783 else if (mtdata != NULL)
1784 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1788 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1790 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1793 // did not find external texture, load it from the bsp or wad3
1794 if (loadmodel->brush.ishlbsp)
1796 // internal texture overrides wad
1797 unsigned char *pixels, *freepixels;
1798 pixels = freepixels = NULL;
1800 pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1802 pixels = freepixels = W_GetTextureBGRA(tx->name);
1805 tx->width = image_width;
1806 tx->height = image_height;
1807 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1810 Mem_Free(freepixels);
1812 else if (mtdata) // texture included
1813 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1815 // if skinframe is still NULL the "missing" texture will be used
1817 tx->skinframes[0] = skinframe;
1819 // LordHavoc: some Tenebrae textures get replaced by black
1820 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1821 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1822 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1823 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1826 tx->basematerialflags = MATERIALFLAG_WALL;
1827 if (tx->name[0] == '*')
1829 // LordHavoc: some turbulent textures should not be affected by wateralpha
1830 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1831 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1832 else if (!strncmp(tx->name,"*lava",5)
1833 || !strncmp(tx->name,"*teleport",9)
1834 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1835 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1837 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1838 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1839 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1841 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1843 // replace the texture with black
1844 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1846 else if (!strncmp(tx->name, "sky", 3))
1847 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1848 else if (!strcmp(tx->name, "caulk"))
1849 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1850 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1851 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1853 // start out with no animation
1854 tx->currentframe = tx;
1855 tx->currentskinframe = tx->skinframes[0];
1856 tx->currentmaterialflags = tx->basematerialflags;
1859 // sequence the animations
1860 for (i = 0;i < m->nummiptex;i++)
1862 tx = loadmodel->data_textures + i;
1863 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1865 if (tx->anim_total[0] || tx->anim_total[1])
1866 continue; // already sequenced
1868 // find the number of frames in the animation
1869 memset(anims, 0, sizeof(anims));
1870 memset(altanims, 0, sizeof(altanims));
1872 for (j = i;j < m->nummiptex;j++)
1874 tx2 = loadmodel->data_textures + j;
1875 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1879 if (num >= '0' && num <= '9')
1880 anims[num - '0'] = tx2;
1881 else if (num >= 'a' && num <= 'j')
1882 altanims[num - 'a'] = tx2;
1884 Con_Printf("Bad animating texture %s\n", tx->name);
1888 for (j = 0;j < 10;j++)
1895 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1898 for (j = 0;j < max;j++)
1902 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1906 for (j = 0;j < altmax;j++)
1910 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1919 // if there is no alternate animation, duplicate the primary
1920 // animation into the alternate
1922 for (k = 0;k < 10;k++)
1923 altanims[k] = anims[k];
1926 // link together the primary animation
1927 for (j = 0;j < max;j++)
1930 tx2->animated = true;
1931 tx2->anim_total[0] = max;
1932 tx2->anim_total[1] = altmax;
1933 for (k = 0;k < 10;k++)
1935 tx2->anim_frames[0][k] = anims[k];
1936 tx2->anim_frames[1][k] = altanims[k];
1940 // if there really is an alternate anim...
1941 if (anims[0] != altanims[0])
1943 // link together the alternate animation
1944 for (j = 0;j < altmax;j++)
1947 tx2->animated = true;
1948 // the primary/alternate are reversed here
1949 tx2->anim_total[0] = altmax;
1950 tx2->anim_total[1] = max;
1951 for (k = 0;k < 10;k++)
1953 tx2->anim_frames[0][k] = altanims[k];
1954 tx2->anim_frames[1][k] = anims[k];
1961 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1964 unsigned char *in, *out, *data, d;
1965 char litfilename[MAX_QPATH];
1966 char dlitfilename[MAX_QPATH];
1967 fs_offset_t filesize;
1968 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1970 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1971 for (i=0; i<l->filelen; i++)
1972 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1974 else // LordHavoc: bsp version 29 (normal white lighting)
1976 // LordHavoc: hope is not lost yet, check for a .lit file to load
1977 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1978 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1979 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1980 strlcat (litfilename, ".lit", sizeof (litfilename));
1981 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1982 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1985 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1987 i = LittleLong(((int *)data)[1]);
1990 if (developer_loading.integer)
1991 Con_Printf("loaded %s\n", litfilename);
1992 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1993 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1995 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1998 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2000 i = LittleLong(((int *)data)[1]);
2003 if (developer_loading.integer)
2004 Con_Printf("loaded %s\n", dlitfilename);
2005 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2006 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2007 loadmodel->brushq3.deluxemapping_modelspace = false;
2008 loadmodel->brushq3.deluxemapping = true;
2017 Con_Printf("Unknown .lit file version (%d)\n", i);
2019 else if (filesize == 8)
2020 Con_Print("Empty .lit file, ignoring\n");
2022 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
2029 // LordHavoc: oh well, expand the white lighting data
2032 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
2033 in = mod_base + l->fileofs;
2034 out = loadmodel->brushq1.lightdata;
2035 for (i = 0;i < l->filelen;i++)
2045 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
2047 loadmodel->brushq1.num_compressedpvs = 0;
2048 loadmodel->brushq1.data_compressedpvs = NULL;
2051 loadmodel->brushq1.num_compressedpvs = l->filelen;
2052 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
2053 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
2056 // used only for HalfLife maps
2057 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2059 char key[128], value[4096];
2063 if (!COM_ParseToken_Simple(&data, false, false))
2065 if (com_token[0] != '{')
2069 if (!COM_ParseToken_Simple(&data, false, false))
2071 if (com_token[0] == '}')
2072 break; // end of worldspawn
2073 if (com_token[0] == '_')
2074 strlcpy(key, com_token + 1, sizeof(key));
2076 strlcpy(key, com_token, sizeof(key));
2077 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2078 key[strlen(key)-1] = 0;
2079 if (!COM_ParseToken_Simple(&data, false, false))
2081 dpsnprintf(value, sizeof(value), "%s", com_token);
2082 if (!strcmp("wad", key)) // for HalfLife maps
2084 if (loadmodel->brush.ishlbsp)
2087 for (i = 0;i < (int)sizeof(value);i++)
2088 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2092 for (;i < (int)sizeof(value);i++)
2094 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2095 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2097 else if (value[i] == ';' || value[i] == 0)
2101 W_LoadTextureWadFile(&value[j], false);
2113 static void Mod_Q1BSP_LoadEntities(lump_t *l)
2115 loadmodel->brush.entities = NULL;
2118 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
2119 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
2120 loadmodel->brush.entities[l->filelen] = 0;
2121 if (loadmodel->brush.ishlbsp)
2122 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2126 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
2132 in = (dvertex_t *)(mod_base + l->fileofs);
2133 if (l->filelen % sizeof(*in))
2134 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2135 count = l->filelen / sizeof(*in);
2136 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2138 loadmodel->brushq1.vertexes = out;
2139 loadmodel->brushq1.numvertexes = count;
2141 for ( i=0 ; i<count ; i++, in++, out++)
2143 out->position[0] = LittleFloat(in->point[0]);
2144 out->position[1] = LittleFloat(in->point[1]);
2145 out->position[2] = LittleFloat(in->point[2]);
2149 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
2150 // can be used for this
2152 int SB_ReadInt (unsigned char **buffer)
2155 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
2161 float SB_ReadFloat (unsigned char **buffer)
2169 u.i = SB_ReadInt (buffer);
2173 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
2175 unsigned char *index;
2179 index = (unsigned char *)(mod_base + l->fileofs);
2180 if (l->filelen % (48+4*hullinfo->filehulls))
2181 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2183 count = l->filelen / (48+4*hullinfo->filehulls);
2184 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2186 loadmodel->brushq1.submodels = out;
2187 loadmodel->brush.numsubmodels = count;
2189 for (i = 0; i < count; i++, out++)
2191 // spread out the mins / maxs by a pixel
2192 out->mins[0] = SB_ReadFloat (&index) - 1;
2193 out->mins[1] = SB_ReadFloat (&index) - 1;
2194 out->mins[2] = SB_ReadFloat (&index) - 1;
2195 out->maxs[0] = SB_ReadFloat (&index) + 1;
2196 out->maxs[1] = SB_ReadFloat (&index) + 1;
2197 out->maxs[2] = SB_ReadFloat (&index) + 1;
2198 out->origin[0] = SB_ReadFloat (&index);
2199 out->origin[1] = SB_ReadFloat (&index);
2200 out->origin[2] = SB_ReadFloat (&index);
2201 for (j = 0; j < hullinfo->filehulls; j++)
2202 out->headnode[j] = SB_ReadInt (&index);
2203 out->visleafs = SB_ReadInt (&index);
2204 out->firstface = SB_ReadInt (&index);
2205 out->numfaces = SB_ReadInt (&index);
2209 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2215 in = (dedge_t *)(mod_base + l->fileofs);
2216 if (l->filelen % sizeof(*in))
2217 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2218 count = l->filelen / sizeof(*in);
2219 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2221 loadmodel->brushq1.edges = out;
2222 loadmodel->brushq1.numedges = count;
2224 for ( i=0 ; i<count ; i++, in++, out++)
2226 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2227 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2228 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2230 Con_Printf("Mod_Q1BSP_LoadEdges: %s has invalid vertex indices in edge %i (vertices %i %i >= numvertices %i)\n", loadmodel->name, i, out->v[0], out->v[1], loadmodel->brushq1.numvertexes);
2231 if(!loadmodel->brushq1.numvertexes)
2232 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2240 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2244 int i, j, k, count, miptex;
2246 in = (texinfo_t *)(mod_base + l->fileofs);
2247 if (l->filelen % sizeof(*in))
2248 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2249 count = l->filelen / sizeof(*in);
2250 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2252 loadmodel->brushq1.texinfo = out;
2253 loadmodel->brushq1.numtexinfo = count;
2255 for (i = 0;i < count;i++, in++, out++)
2257 for (k = 0;k < 2;k++)
2258 for (j = 0;j < 4;j++)
2259 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2261 miptex = LittleLong(in->miptex);
2262 out->flags = LittleLong(in->flags);
2264 out->texture = NULL;
2265 if (loadmodel->data_textures)
2267 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2268 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2270 out->texture = loadmodel->data_textures + miptex;
2272 if (out->flags & TEX_SPECIAL)
2274 // if texture chosen is NULL or the shader needs a lightmap,
2275 // force to notexture water shader
2276 if (out->texture == NULL)
2277 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2281 // if texture chosen is NULL, force to notexture
2282 if (out->texture == NULL)
2283 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2289 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2294 mins[0] = mins[1] = mins[2] = 9999;
2295 maxs[0] = maxs[1] = maxs[2] = -9999;
2297 for (i = 0;i < numverts;i++)
2299 for (j = 0;j < 3;j++, v++)
2309 #define MAX_SUBDIVPOLYTRIANGLES 4096
2310 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2312 static int subdivpolyverts, subdivpolytriangles;
2313 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2314 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2316 static int subdivpolylookupvert(vec3_t v)
2319 for (i = 0;i < subdivpolyverts;i++)
2320 if (subdivpolyvert[i][0] == v[0]
2321 && subdivpolyvert[i][1] == v[1]
2322 && subdivpolyvert[i][2] == v[2])
2324 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2325 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2326 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2327 return subdivpolyverts++;
2330 static void SubdividePolygon(int numverts, float *verts)
2332 int i, i1, i2, i3, f, b, c, p;
2333 vec3_t mins, maxs, front[256], back[256];
2334 float m, *pv, *cv, dist[256], frac;
2337 Host_Error("SubdividePolygon: ran out of verts in buffer");
2339 BoundPoly(numverts, verts, mins, maxs);
2341 for (i = 0;i < 3;i++)
2343 m = (mins[i] + maxs[i]) * 0.5;
2344 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2345 if (maxs[i] - m < 8)
2347 if (m - mins[i] < 8)
2351 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2352 dist[c] = cv[i] - m;
2355 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2359 VectorCopy(pv, front[f]);
2364 VectorCopy(pv, back[b]);
2367 if (dist[p] == 0 || dist[c] == 0)
2369 if ((dist[p] > 0) != (dist[c] > 0) )
2372 frac = dist[p] / (dist[p] - dist[c]);
2373 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2374 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2375 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2381 SubdividePolygon(f, front[0]);
2382 SubdividePolygon(b, back[0]);
2386 i1 = subdivpolylookupvert(verts);
2387 i2 = subdivpolylookupvert(verts + 3);
2388 for (i = 2;i < numverts;i++)
2390 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2392 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2396 i3 = subdivpolylookupvert(verts + i * 3);
2397 subdivpolyindex[subdivpolytriangles][0] = i1;
2398 subdivpolyindex[subdivpolytriangles][1] = i2;
2399 subdivpolyindex[subdivpolytriangles][2] = i3;
2401 subdivpolytriangles++;
2405 //Breaks a polygon up along axial 64 unit
2406 //boundaries so that turbulent and sky warps
2407 //can be done reasonably.
2408 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2414 subdivpolytriangles = 0;
2415 subdivpolyverts = 0;
2416 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2417 if (subdivpolytriangles < 1)
2418 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2420 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2421 mesh->num_vertices = subdivpolyverts;
2422 mesh->num_triangles = subdivpolytriangles;
2423 mesh->vertex = (surfvertex_t *)(mesh + 1);
2424 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2425 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2427 for (i = 0;i < mesh->num_triangles;i++)
2428 for (j = 0;j < 3;j++)
2429 mesh->index[i*3+j] = subdivpolyindex[i][j];
2431 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2433 VectorCopy(subdivpolyvert[i], v->v);
2434 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2435 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2440 extern cvar_t gl_max_lightmapsize;
2441 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2444 msurface_t *surface;
2445 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2446 float texmins[2], texmaxs[2], val;
2447 rtexture_t *lightmaptexture, *deluxemaptexture;
2449 in = (dface_t *)(mod_base + l->fileofs);
2450 if (l->filelen % sizeof(*in))
2451 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2452 count = l->filelen / sizeof(*in);
2453 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2454 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2456 loadmodel->num_surfaces = count;
2458 loadmodel->brushq1.firstrender = true;
2459 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2463 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2465 numedges = (unsigned short)LittleShort(in->numedges);
2466 totalverts += numedges;
2467 totaltris += numedges - 2;
2470 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2472 lightmaptexture = NULL;
2473 deluxemaptexture = r_texture_blanknormalmap;
2475 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2476 totallightmapsamples = 0;
2480 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2482 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2484 // FIXME: validate edges, texinfo, etc?
2485 firstedge = LittleLong(in->firstedge);
2486 numedges = (unsigned short)LittleShort(in->numedges);
2487 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)
2488 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2489 i = (unsigned short)LittleShort(in->texinfo);
2490 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2491 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2492 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2493 surface->texture = surface->lightmapinfo->texinfo->texture;
2495 planenum = (unsigned short)LittleShort(in->planenum);
2496 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2497 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2499 //surface->flags = surface->texture->flags;
2500 //if (LittleShort(in->side))
2501 // surface->flags |= SURF_PLANEBACK;
2502 //surface->plane = loadmodel->brush.data_planes + planenum;
2504 surface->num_firstvertex = totalverts;
2505 surface->num_vertices = numedges;
2506 surface->num_firsttriangle = totaltris;
2507 surface->num_triangles = numedges - 2;
2508 totalverts += numedges;
2509 totaltris += numedges - 2;
2511 // convert edges back to a normal polygon
2512 for (i = 0;i < surface->num_vertices;i++)
2514 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2516 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2518 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2520 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2521 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2522 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2523 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2524 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2525 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2526 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2527 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2530 for (i = 0;i < surface->num_triangles;i++)
2532 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2533 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2534 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2537 // compile additional data about the surface geometry
2538 Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
2539 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
2540 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2542 // generate surface extents information
2543 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2544 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2545 for (i = 1;i < surface->num_vertices;i++)
2547 for (j = 0;j < 2;j++)
2549 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2550 texmins[j] = min(texmins[j], val);
2551 texmaxs[j] = max(texmaxs[j], val);
2554 for (i = 0;i < 2;i++)
2556 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2557 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2560 smax = surface->lightmapinfo->extents[0] >> 4;
2561 tmax = surface->lightmapinfo->extents[1] >> 4;
2562 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2563 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2566 for (i = 0;i < MAXLIGHTMAPS;i++)
2567 surface->lightmapinfo->styles[i] = in->styles[i];
2568 surface->lightmaptexture = NULL;
2569 surface->deluxemaptexture = r_texture_blanknormalmap;
2570 i = LittleLong(in->lightofs);
2573 surface->lightmapinfo->samples = NULL;
2575 // give non-lightmapped water a 1x white lightmap
2576 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2578 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2579 surface->lightmapinfo->styles[0] = 0;
2580 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2584 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2585 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2586 else // LordHavoc: white lighting (bsp version 29)
2588 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2589 if (loadmodel->brushq1.nmaplightdata)
2590 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2593 // check if we should apply a lightmap to this
2594 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2596 if (ssize > 256 || tsize > 256)
2597 Host_Error("Bad surface extents");
2599 if (lightmapsize < ssize)
2600 lightmapsize = ssize;
2601 if (lightmapsize < tsize)
2602 lightmapsize = tsize;
2604 totallightmapsamples += ssize*tsize;
2606 // force lightmap upload on first time seeing the surface
2608 // additionally this is used by the later code to see if a
2609 // lightmap is needed on this surface (rather than duplicating the
2611 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2612 loadmodel->lit = true;
2616 // small maps (such as ammo boxes especially) don't need big lightmap
2617 // textures, so this code tries to guess a good size based on
2618 // totallightmapsamples (size of the lightmaps lump basically), as well as
2619 // trying to max out the size if there is a lot of lightmap data to store
2620 // additionally, never choose a lightmapsize that is smaller than the
2621 // largest surface encountered (as it would fail)
2623 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2626 // now that we've decided the lightmap texture size, we can do the rest
2627 if (cls.state != ca_dedicated)
2629 int stainmapsize = 0;
2630 mod_alloclightmap_state_t allocState;
2632 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2633 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2635 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2636 float u, v, ubase, vbase, uscale, vscale;
2638 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2641 smax = surface->lightmapinfo->extents[0] >> 4;
2642 tmax = surface->lightmapinfo->extents[1] >> 4;
2643 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2644 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2645 stainmapsize += ssize * tsize * 3;
2647 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2649 // allocate a texture pool if we need it
2650 if (loadmodel->texturepool == NULL)
2651 loadmodel->texturepool = R_AllocTexturePool();
2652 // could not find room, make a new lightmap
2653 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2654 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2655 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2656 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2657 if (loadmodel->brushq1.nmaplightdata)
2658 loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2660 Mod_AllocLightmap_Reset(&allocState);
2661 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2663 surface->lightmaptexture = lightmaptexture;
2664 surface->deluxemaptexture = deluxemaptexture;
2665 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2666 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2668 uscale = 1.0f / (float)lightmapsize;
2669 vscale = 1.0f / (float)lightmapsize;
2670 ubase = lightmapx * uscale;
2671 vbase = lightmapy * vscale;
2673 for (i = 0;i < surface->num_vertices;i++)
2675 u = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3]) + 8 - surface->lightmapinfo->texturemins[0]) * (1.0 / 16.0);
2676 v = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3]) + 8 - surface->lightmapinfo->texturemins[1]) * (1.0 / 16.0);
2677 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2678 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2679 // LordHavoc: calc lightmap data offset for vertex lighting to use
2682 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2686 if (cl_stainmaps.integer)
2688 // allocate stainmaps for permanent marks on walls and clear white
2689 unsigned char *stainsamples = NULL;
2690 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2691 memset(stainsamples, 255, stainmapsize);
2693 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2695 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2697 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2698 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2699 surface->lightmapinfo->stainsamples = stainsamples;
2700 stainsamples += ssize * tsize * 3;
2705 // generate ushort elements array if possible
2706 if (loadmodel->surfmesh.data_element3s)
2707 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2708 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2711 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2714 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2715 node->parent = parent;
2718 // this is a node, recurse to children
2719 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2720 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2721 // combine supercontents of children
2722 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2727 mleaf_t *leaf = (mleaf_t *)node;
2728 // if this is a leaf, calculate supercontents mask from all collidable
2729 // primitives in the leaf (brushes and collision surfaces)
2730 // also flag if the leaf contains any collision surfaces
2731 leaf->combinedsupercontents = 0;
2732 // combine the supercontents values of all brushes in this leaf
2733 for (j = 0;j < leaf->numleafbrushes;j++)
2734 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2735 // check if this leaf contains any collision surfaces (q3 patches)
2736 for (j = 0;j < leaf->numleafsurfaces;j++)
2738 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2739 if (surface->num_collisiontriangles)
2741 leaf->containscollisionsurfaces = true;
2742 leaf->combinedsupercontents |= surface->texture->supercontents;
2748 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2754 in = (dnode_t *)(mod_base + l->fileofs);
2755 if (l->filelen % sizeof(*in))
2756 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2757 count = l->filelen / sizeof(*in);
2759 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2760 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2762 loadmodel->brush.data_nodes = out;
2763 loadmodel->brush.num_nodes = count;
2765 for ( i=0 ; i<count ; i++, in++, out++)
2767 for (j=0 ; j<3 ; j++)
2769 out->mins[j] = LittleShort(in->mins[j]);
2770 out->maxs[j] = LittleShort(in->maxs[j]);
2773 p = LittleLong(in->planenum);
2774 out->plane = loadmodel->brush.data_planes + p;
2776 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2777 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2779 for (j=0 ; j<2 ; j++)
2781 // LordHavoc: this code supports broken bsp files produced by
2782 // arguire qbsp which can produce more than 32768 nodes, any value
2783 // below count is assumed to be a node number, any other value is
2784 // assumed to be a leaf number
2785 p = (unsigned short)LittleShort(in->children[j]);
2788 if (p < loadmodel->brush.num_nodes)
2789 out->children[j] = loadmodel->brush.data_nodes + p;
2792 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2793 // map it to the solid leaf
2794 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2799 // note this uses 65535 intentionally, -1 is leaf 0
2801 if (p < loadmodel->brush.num_leafs)
2802 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2805 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2806 // map it to the solid leaf
2807 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2813 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2816 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2822 in = (dleaf_t *)(mod_base + l->fileofs);
2823 if (l->filelen % sizeof(*in))
2824 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2825 count = l->filelen / sizeof(*in);
2826 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2828 loadmodel->brush.data_leafs = out;
2829 loadmodel->brush.num_leafs = count;
2830 // get visleafs from the submodel data
2831 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2832 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2833 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2834 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2836 for ( i=0 ; i<count ; i++, in++, out++)
2838 for (j=0 ; j<3 ; j++)
2840 out->mins[j] = LittleShort(in->mins[j]);
2841 out->maxs[j] = LittleShort(in->maxs[j]);
2844 // FIXME: this function could really benefit from some error checking
2846 out->contents = LittleLong(in->contents);
2848 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2849 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2850 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2852 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", (int)(out->firstleafsurface - loadmodel->brush.data_leafsurfaces), (int)(out->firstleafsurface + out->numleafsurfaces - loadmodel->brush.data_leafsurfaces), 0, loadmodel->brush.num_leafsurfaces);
2853 out->firstleafsurface = NULL;
2854 out->numleafsurfaces = 0;
2857 out->clusterindex = i - 1;
2858 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2859 out->clusterindex = -1;
2861 p = LittleLong(in->visofs);
2862 // ignore visofs errors on leaf 0 (solid)
2863 if (p >= 0 && out->clusterindex >= 0)
2865 if (p >= loadmodel->brushq1.num_compressedpvs)
2866 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2868 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);
2871 for (j = 0;j < 4;j++)
2872 out->ambient_sound_level[j] = in->ambient_level[j];
2874 // FIXME: Insert caustics here
2878 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2882 const unsigned char *pvs;
2883 // if there's no vis data, assume supported (because everything is visible all the time)
2884 if (!loadmodel->brush.data_pvsclusters)
2886 // check all liquid leafs to see if they can see into empty leafs, if any
2887 // can we can assume this map supports r_wateralpha
2888 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2890 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2892 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2893 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2894 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2901 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2908 in = (dclipnode_t *)(mod_base + l->fileofs);
2909 if (l->filelen % sizeof(*in))
2910 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2911 count = l->filelen / sizeof(*in);
2912 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2914 loadmodel->brushq1.clipnodes = out;
2915 loadmodel->brushq1.numclipnodes = count;
2917 for (i = 1; i < MAX_MAP_HULLS; i++)
2919 hull = &loadmodel->brushq1.hulls[i];
2920 hull->clipnodes = out;
2921 hull->firstclipnode = 0;
2922 hull->lastclipnode = count-1;
2923 hull->planes = loadmodel->brush.data_planes;
2924 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2925 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2926 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2927 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2928 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2929 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2930 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2933 for (i=0 ; i<count ; i++, out++, in++)
2935 out->planenum = LittleLong(in->planenum);
2936 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2937 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2938 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2939 if (out->children[0] >= count)
2940 out->children[0] -= 65536;
2941 if (out->children[1] >= count)
2942 out->children[1] -= 65536;
2943 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2944 Host_Error("Corrupt clipping hull(out of range planenum)");
2948 //Duplicate the drawing hull structure as a clipping hull
2949 static void Mod_Q1BSP_MakeHull0(void)
2956 hull = &loadmodel->brushq1.hulls[0];
2958 in = loadmodel->brush.data_nodes;
2959 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2961 hull->clipnodes = out;
2962 hull->firstclipnode = 0;
2963 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2964 hull->planes = loadmodel->brush.data_planes;
2966 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2968 out->planenum = in->plane - loadmodel->brush.data_planes;
2969 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2970 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2974 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2979 in = (short *)(mod_base + l->fileofs);
2980 if (l->filelen % sizeof(*in))
2981 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2982 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2983 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2985 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2987 j = (unsigned short) LittleShort(in[i]);
2988 if (j >= loadmodel->num_surfaces)
2989 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2990 loadmodel->brush.data_leafsurfaces[i] = j;
2994 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2999 in = (int *)(mod_base + l->fileofs);
3000 if (l->filelen % sizeof(*in))
3001 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3002 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
3003 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3005 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3006 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
3010 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
3016 in = (dplane_t *)(mod_base + l->fileofs);
3017 if (l->filelen % sizeof(*in))
3018 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3020 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
3021 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3023 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
3025 out->normal[0] = LittleFloat(in->normal[0]);
3026 out->normal[1] = LittleFloat(in->normal[1]);
3027 out->normal[2] = LittleFloat(in->normal[2]);
3028 out->dist = LittleFloat(in->dist);
3034 static void Mod_Q1BSP_LoadMapBrushes(void)
3038 int submodel, numbrushes;
3039 qboolean firstbrush;
3040 char *text, *maptext;
3041 char mapfilename[MAX_QPATH];
3042 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3043 strlcat (mapfilename, ".map", sizeof (mapfilename));
3044 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3048 if (!COM_ParseToken_Simple(&data, false, false))
3053 if (!COM_ParseToken_Simple(&data, false, false))
3055 if (com_token[0] != '{')
3061 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3064 if (!COM_ParseToken_Simple(&data, false, false))
3066 if (com_token[0] == '}')
3067 break; // end of entity
3068 if (com_token[0] == '{')
3075 if (submodel > loadmodel->brush.numsubmodels)
3077 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3081 model = loadmodel->brush.submodels[submodel];
3088 if (!COM_ParseToken_Simple(&data, false, false))
3090 if (com_token[0] == '}')
3091 break; // end of brush
3092 // each brush face should be this format:
3093 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3094 // FIXME: support hl .map format
3095 for (pointnum = 0;pointnum < 3;pointnum++)
3097 COM_ParseToken_Simple(&data, false, false);
3098 for (componentnum = 0;componentnum < 3;componentnum++)
3100 COM_ParseToken_Simple(&data, false, false);
3101 point[pointnum][componentnum] = atof(com_token);
3103 COM_ParseToken_Simple(&data, false, false);
3105 COM_ParseToken_Simple(&data, false, false);
3106 strlcpy(facetexture, com_token, sizeof(facetexture));
3107 COM_ParseToken_Simple(&data, false, false);
3108 //scroll_s = atof(com_token);
3109 COM_ParseToken_Simple(&data, false, false);
3110 //scroll_t = atof(com_token);
3111 COM_ParseToken_Simple(&data, false, false);
3112 //rotate = atof(com_token);
3113 COM_ParseToken_Simple(&data, false, false);
3114 //scale_s = atof(com_token);
3115 COM_ParseToken_Simple(&data, false, false);
3116 //scale_t = atof(com_token);
3117 TriangleNormal(point[0], point[1], point[2], planenormal);
3118 VectorNormalizeDouble(planenormal);
3119 planedist = DotProduct(point[0], planenormal);
3120 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3130 #define MAX_PORTALPOINTS 64
3132 typedef struct portal_s
3135 mnode_t *nodes[2]; // [0] = front side of plane
3136 struct portal_s *next[2];
3138 double points[3*MAX_PORTALPOINTS];
3139 struct portal_s *chain; // all portals are linked into a list
3143 static memexpandablearray_t portalarray;
3145 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3147 // process only nodes (leafs already had their box calculated)
3151 // calculate children first
3152 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3153 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3155 // make combined bounding box from children
3156 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3157 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3158 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3159 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3160 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3161 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3164 static void Mod_Q1BSP_FinalizePortals(void)
3166 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
3170 mleaf_t *leaf, *endleaf;
3172 // tally up portal and point counts and recalculate bounding boxes for all
3173 // leafs (because qbsp is very sloppy)
3174 leaf = loadmodel->brush.data_leafs;
3175 endleaf = leaf + loadmodel->brush.num_leafs;
3176 if (mod_recalculatenodeboxes.integer)
3178 for (;leaf < endleaf;leaf++)
3180 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3181 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3186 for (portalindex = 0;portalindex < portalrange;portalindex++)
3188 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3191 // note: this check must match the one below or it will usually corrupt memory
3192 // 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
3193 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3196 numpoints += p->numpoints * 2;
3199 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3200 loadmodel->brush.num_portals = numportals;
3201 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3202 loadmodel->brush.num_portalpoints = numpoints;
3203 // clear all leaf portal chains
3204 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3205 loadmodel->brush.data_leafs[i].portals = NULL;
3206 // process all portals in the global portal chain, while freeing them
3207 portal = loadmodel->brush.data_portals;
3208 point = loadmodel->brush.data_portalpoints;
3209 for (portalindex = 0;portalindex < portalrange;portalindex++)
3211 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3214 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3216 // note: this check must match the one above or it will usually corrupt memory
3217 // 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
3218 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3220 // first make the back to front portal(forward portal)
3221 portal->points = point;
3222 portal->numpoints = p->numpoints;
3223 portal->plane.dist = p->plane.dist;
3224 VectorCopy(p->plane.normal, portal->plane.normal);
3225 portal->here = (mleaf_t *)p->nodes[1];
3226 portal->past = (mleaf_t *)p->nodes[0];
3228 for (j = 0;j < portal->numpoints;j++)
3230 VectorCopy(p->points + j*3, point->position);
3233 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3234 PlaneClassify(&portal->plane);
3236 // link into leaf's portal chain
3237 portal->next = portal->here->portals;
3238 portal->here->portals = portal;
3240 // advance to next portal
3243 // then make the front to back portal(backward portal)
3244 portal->points = point;
3245 portal->numpoints = p->numpoints;
3246 portal->plane.dist = -p->plane.dist;
3247 VectorNegate(p->plane.normal, portal->plane.normal);
3248 portal->here = (mleaf_t *)p->nodes[0];
3249 portal->past = (mleaf_t *)p->nodes[1];
3251 for (j = portal->numpoints - 1;j >= 0;j--)
3253 VectorCopy(p->points + j*3, point->position);
3256 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3257 PlaneClassify(&portal->plane);
3259 // link into leaf's portal chain
3260 portal->next = portal->here->portals;
3261 portal->here->portals = portal;
3263 // advance to next portal
3266 // add the portal's polygon points to the leaf bounding boxes
3267 if (mod_recalculatenodeboxes.integer)
3269 for (i = 0;i < 2;i++)
3271 leaf = (mleaf_t *)p->nodes[i];
3272 for (j = 0;j < p->numpoints;j++)
3274 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3275 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3276 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3277 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3278 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3279 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3285 // now recalculate the node bounding boxes from the leafs
3286 if (mod_recalculatenodeboxes.integer)
3287 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3295 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3298 Host_Error("AddPortalToNodes: NULL front node");
3300 Host_Error("AddPortalToNodes: NULL back node");
3301 if (p->nodes[0] || p->nodes[1])
3302 Host_Error("AddPortalToNodes: already included");
3303 // 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
3305 p->nodes[0] = front;
3306 p->next[0] = (portal_t *)front->portals;
3307 front->portals = (mportal_t *)p;
3310 p->next[1] = (portal_t *)back->portals;
3311 back->portals = (mportal_t *)p;
3316 RemovePortalFromNode
3319 static void RemovePortalFromNodes(portal_t *portal)
3323 void **portalpointer;
3325 for (i = 0;i < 2;i++)
3327 node = portal->nodes[i];
3329 portalpointer = (void **) &node->portals;
3332 t = (portal_t *)*portalpointer;
3334 Host_Error("RemovePortalFromNodes: portal not in leaf");
3338 if (portal->nodes[0] == node)
3340 *portalpointer = portal->next[0];
3341 portal->nodes[0] = NULL;
3343 else if (portal->nodes[1] == node)
3345 *portalpointer = portal->next[1];
3346 portal->nodes[1] = NULL;
3349 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3353 if (t->nodes[0] == node)
3354 portalpointer = (void **) &t->next[0];
3355 else if (t->nodes[1] == node)
3356 portalpointer = (void **) &t->next[1];
3358 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3363 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3364 static double *portalpointsbuffer;
3365 static int portalpointsbufferoffset;
3366 static int portalpointsbuffersize;
3367 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3370 mnode_t *front, *back, *other_node;
3371 mplane_t clipplane, *plane;
3372 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3373 int numfrontpoints, numbackpoints;
3374 double *frontpoints, *backpoints;
3376 // if a leaf, we're done
3380 // get some space for our clipping operations to use
3381 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3383 portalpointsbuffersize = portalpointsbufferoffset * 2;
3384 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3386 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3387 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3388 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3389 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3391 plane = node->plane;
3393 front = node->children[0];
3394 back = node->children[1];
3396 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3398 // create the new portal by generating a polygon for the node plane,
3399 // and clipping it by all of the other portals(which came from nodes above this one)
3400 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3401 nodeportal->plane = *plane;
3403 // TODO: calculate node bounding boxes during recursion and calculate a maximum plane size accordingly to improve precision (as most maps do not need 1 billion unit plane polygons)
3404 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);
3405 nodeportal->numpoints = 4;
3406 side = 0; // shut up compiler warning
3407 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3409 clipplane = portal->plane;
3410 if (portal->nodes[0] == portal->nodes[1])
3411 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3412 if (portal->nodes[0] == node)
3414 else if (portal->nodes[1] == node)
3416 clipplane.dist = -clipplane.dist;
3417 VectorNegate(clipplane.normal, clipplane.normal);
3421 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3423 for (i = 0;i < nodeportal->numpoints*3;i++)
3424 frontpoints[i] = nodeportal->points[i];
3425 PolygonD_Divide(nodeportal->numpoints, frontpoints, clipplane.normal[0], clipplane.normal[1], clipplane.normal[2], clipplane.dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, nodeportal->points, &nodeportal->numpoints, 0, NULL, NULL, NULL);
3426 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3430 if (nodeportal->numpoints < 3)
3432 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3433 nodeportal->numpoints = 0;
3435 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3437 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3438 nodeportal->numpoints = 0;
3441 AddPortalToNodes(nodeportal, front, back);
3443 // split the portals of this node along this node's plane and assign them to the children of this node
3444 // (migrating the portals downward through the tree)
3445 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3447 if (portal->nodes[0] == portal->nodes[1])
3448 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3449 if (portal->nodes[0] == node)
3451 else if (portal->nodes[1] == node)
3454 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3455 nextportal = portal->next[side];
3456 if (!portal->numpoints)
3459 other_node = portal->nodes[!side];
3460 RemovePortalFromNodes(portal);
3462 // cut the portal into two portals, one on each side of the node plane
3463 PolygonD_Divide(portal->numpoints, portal->points, plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, frontpoints, &numfrontpoints, MAX_PORTALPOINTS, backpoints, &numbackpoints, NULL);
3465 if (!numfrontpoints)
3468 AddPortalToNodes(portal, back, other_node);
3470 AddPortalToNodes(portal, other_node, back);
3476 AddPortalToNodes(portal, front, other_node);
3478 AddPortalToNodes(portal, other_node, front);
3482 // the portal is split
3483 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3484 temp = splitportal->chain;
3485 *splitportal = *portal;
3486 splitportal->chain = temp;
3487 for (i = 0;i < numbackpoints*3;i++)
3488 splitportal->points[i] = backpoints[i];
3489 splitportal->numpoints = numbackpoints;
3490 for (i = 0;i < numfrontpoints*3;i++)
3491 portal->points[i] = frontpoints[i];
3492 portal->numpoints = numfrontpoints;
3496 AddPortalToNodes(portal, front, other_node);
3497 AddPortalToNodes(splitportal, back, other_node);
3501 AddPortalToNodes(portal, other_node, front);
3502 AddPortalToNodes(splitportal, other_node, back);
3506 Mod_Q1BSP_RecursiveNodePortals(front);
3507 Mod_Q1BSP_RecursiveNodePortals(back);
3509 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3512 static void Mod_Q1BSP_MakePortals(void)
3514 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3515 portalpointsbufferoffset = 0;
3516 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3517 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3518 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3519 Mem_Free(portalpointsbuffer);
3520 portalpointsbuffer = NULL;
3521 portalpointsbufferoffset = 0;
3522 portalpointsbuffersize = 0;
3523 Mod_Q1BSP_FinalizePortals();
3524 Mem_ExpandableArray_FreeArray(&portalarray);
3527 //Returns PVS data for a given point
3528 //(note: can return NULL)
3529 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3532 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3534 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3535 if (((mleaf_t *)node)->clusterindex >= 0)
3536 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3541 static void Mod_Q1BSP_FatPVS_RecursiveBSPNode(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbytes, mnode_t *node)
3545 float d = PlaneDiff(org, node->plane);
3547 node = node->children[0];
3548 else if (d < -radius)
3549 node = node->children[1];
3552 // go down both sides
3553 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3554 node = node->children[1];
3557 // if this leaf is in a cluster, accumulate the pvs bits
3558 if (((mleaf_t *)node)->clusterindex >= 0)
3561 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3562 for (i = 0;i < pvsbytes;i++)
3563 pvsbuffer[i] |= pvs[i];
3567 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3568 //of the given point.
3569 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3571 int bytes = model->brush.num_pvsclusterbytes;
3572 bytes = min(bytes, pvsbufferlength);
3573 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3575 memset(pvsbuffer, 0xFF, bytes);
3579 memset(pvsbuffer, 0, bytes);
3580 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3584 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3589 VectorSubtract(inmaxs, inmins, size);
3590 if (cmodel->brush.ishlbsp)
3593 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3594 else if (size[0] <= 32)
3596 if (size[2] < 54) // pick the nearest of 36 or 72
3597 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3599 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3602 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3607 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3608 else if (size[0] <= 32)
3609 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3611 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3613 VectorCopy(inmins, outmins);
3614 VectorAdd(inmins, hull->clip_size, outmaxs);
3617 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3620 int numshadowmeshtriangles = 0;
3621 msurface_t *surface;
3622 if (cls.state == ca_dedicated)
3624 // make a single combined shadow mesh to allow optimized shadow volume creation
3626 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3628 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3629 numshadowmeshtriangles += surface->num_triangles;
3631 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3632 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3633 if (surface->num_triangles > 0)
3634 Mod_ShadowMesh_AddMesh(mod->mempool, mod->brush.shadowmesh, NULL, NULL, NULL, mod->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
3635 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3636 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3637 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3639 return numshadowmeshtriangles;
3642 void Mod_CollisionBIH_TraceLineAgainstSurfaces(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask);
3644 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3649 float dist, modelyawradius, modelradius;
3650 msurface_t *surface;
3651 hullinfo_t hullinfo;
3652 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3653 model_brush_lightstyleinfo_t styleinfo[256];
3654 unsigned char *datapointer;
3656 mod->modeldatatypestring = "Q1BSP";
3658 mod->type = mod_brushq1;
3660 header = (dheader_t *)buffer;
3662 i = LittleLong(header->version);
3663 if (i != BSPVERSION && i != 30)
3664 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3665 mod->brush.ishlbsp = i == 30;
3667 // fill in hull info
3668 VectorClear (hullinfo.hullsizes[0][0]);
3669 VectorClear (hullinfo.hullsizes[0][1]);
3670 if (mod->brush.ishlbsp)
3672 mod->modeldatatypestring = "HLBSP";
3674 hullinfo.filehulls = 4;
3675 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3676 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3677 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3678 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3679 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3680 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3684 hullinfo.filehulls = 4;
3685 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3686 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3687 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3688 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3692 mod_base = (unsigned char*)buffer;
3693 for (i = 0; i < HEADER_LUMPS; i++)
3695 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3696 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3699 mod->soundfromcenter = true;
3700 mod->TraceBox = Mod_Q1BSP_TraceBox;
3701 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
3702 mod->TraceLine = Mod_Q1BSP_TraceLineAgainstSurfaces; // LordHavoc: use the surface-hitting version of TraceLine in all cases
3704 mod->TraceLine = Mod_Q1BSP_TraceLine;
3705 mod->TracePoint = Mod_Q1BSP_TracePoint;
3706 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3707 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3708 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3709 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3710 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3711 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3712 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3713 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3714 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3715 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3716 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3717 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3718 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3719 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3720 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3721 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3722 mod->Draw = R_Q1BSP_Draw;
3723 mod->DrawDepth = R_Q1BSP_DrawDepth;
3724 mod->DrawDebug = R_Q1BSP_DrawDebug;
3725 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3726 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3727 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3728 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3729 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3730 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3731 mod->DrawLight = R_Q1BSP_DrawLight;
3735 mod->brush.qw_md4sum = 0;
3736 mod->brush.qw_md4sum2 = 0;
3737 for (i = 0;i < HEADER_LUMPS;i++)
3740 if (i == LUMP_ENTITIES)
3742 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3743 mod->brush.qw_md4sum ^= LittleLong(temp);
3744 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3746 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3747 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3750 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3751 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3752 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3753 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3754 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3755 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3756 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3757 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3758 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3759 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3760 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3761 // load submodels before leafs because they contain the number of vis leafs
3762 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3763 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3764 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3765 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3767 // check if the map supports transparent water rendering
3768 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3770 if (mod->brushq1.data_compressedpvs)
3771 Mem_Free(mod->brushq1.data_compressedpvs);
3772 mod->brushq1.data_compressedpvs = NULL;
3773 mod->brushq1.num_compressedpvs = 0;
3775 Mod_Q1BSP_MakeHull0();
3776 if (mod_bsp_portalize.integer)
3777 Mod_Q1BSP_MakePortals();
3779 mod->numframes = 2; // regular and alternate animation
3782 // make a single combined shadow mesh to allow optimized shadow volume creation
3783 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3785 if (loadmodel->brush.numsubmodels)
3786 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3788 // LordHavoc: to clear the fog around the original quake submodel code, I
3790 // first of all, some background info on the submodels:
3791 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3792 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3793 // now the weird for loop itself:
3794 // the loop functions in an odd way, on each iteration it sets up the
3795 // current 'mod' model (which despite the confusing code IS the model of
3796 // the number i), at the end of the loop it duplicates the model to become
3797 // the next submodel, and loops back to set up the new submodel.
3799 // LordHavoc: now the explanation of my sane way (which works identically):
3800 // set up the world model, then on each submodel copy from the world model
3801 // and set up the submodel with the respective model info.
3802 totalstylesurfaces = 0;
3804 for (i = 0;i < mod->brush.numsubmodels;i++)
3806 memset(stylecounts, 0, sizeof(stylecounts));
3807 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3809 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3810 for (j = 0;j < MAXLIGHTMAPS;j++)
3811 stylecounts[surface->lightmapinfo->styles[j]]++;
3813 for (k = 0;k < 255;k++)
3817 totalstylesurfaces += stylecounts[k];
3820 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3821 for (i = 0;i < mod->brush.numsubmodels;i++)
3823 // LordHavoc: this code was originally at the end of this loop, but
3824 // has been transformed to something more readable at the start here.
3829 // duplicate the basic information
3830 dpsnprintf(name, sizeof(name), "*%i", i);
3831 mod = Mod_FindName(name, loadmodel->name);
3832 // copy the base model to this one
3834 // rename the clone back to its proper name
3835 strlcpy(mod->name, name, sizeof(mod->name));
3836 mod->brush.parentmodel = loadmodel;
3837 // textures and memory belong to the main model
3838 mod->texturepool = NULL;
3839 mod->mempool = NULL;
3840 mod->brush.GetPVS = NULL;
3841 mod->brush.FatPVS = NULL;
3842 mod->brush.BoxTouchingPVS = NULL;
3843 mod->brush.BoxTouchingLeafPVS = NULL;
3844 mod->brush.BoxTouchingVisibleLeafs = NULL;
3845 mod->brush.FindBoxClusters = NULL;
3846 mod->brush.LightPoint = NULL;
3847 mod->brush.AmbientSoundLevelsForPoint = NULL;
3850 mod->brush.submodel = i;
3852 if (loadmodel->brush.submodels)
3853 loadmodel->brush.submodels[i] = mod;
3855 bm = &mod->brushq1.submodels[i];
3857 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3858 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3860 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3861 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3864 mod->firstmodelsurface = bm->firstface;
3865 mod->nummodelsurfaces = bm->numfaces;
3867 // set node/leaf parents for this submodel
3868 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3870 // make the model surface list (used by shadowing/lighting)
3871 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3872 Mod_MakeSortedSurfaces(mod);
3874 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3875 // (previously this code measured the radius of the vertices of surfaces in the submodel, but that broke submodels that contain only CLIP brushes, which do not produce surfaces)
3876 VectorCopy(bm->mins, mod->normalmins);
3877 VectorCopy(bm->maxs, mod->normalmaxs);
3878 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3879 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3880 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3881 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3882 modelradius = modelyawradius + modelradius * modelradius;
3883 modelyawradius = sqrt(modelyawradius);
3884 modelradius = sqrt(modelradius);
3885 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3886 mod->yawmins[2] = mod->normalmins[2];
3887 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3888 mod->yawmaxs[2] = mod->normalmaxs[2];
3889 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3890 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3891 mod->radius = modelradius;
3892 mod->radius2 = modelradius * modelradius;
3894 // this gets altered below if sky or water is used
3895 mod->DrawSky = NULL;
3896 mod->DrawAddWaterPlanes = NULL;
3898 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3899 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3900 if (mod->nummodelsurfaces)
3902 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3903 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3905 if (j < mod->nummodelsurfaces)
3906 mod->DrawSky = R_Q1BSP_DrawSky;
3908 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3909 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
3911 if (j < mod->nummodelsurfaces)
3912 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3914 // build lightstyle update chains
3915 // (used to rapidly mark lightmapupdateflags on many surfaces
3916 // when d_lightstylevalue changes)
3917 memset(stylecounts, 0, sizeof(stylecounts));
3918 for (k = 0;k < mod->nummodelsurfaces;k++)
3920 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3921 for (j = 0;j < MAXLIGHTMAPS;j++)
3922 stylecounts[surface->lightmapinfo->styles[j]]++;
3924 mod->brushq1.num_lightstyles = 0;
3925 for (k = 0;k < 255;k++)
3929 styleinfo[mod->brushq1.num_lightstyles].style = k;
3930 styleinfo[mod->brushq1.num_lightstyles].value = 0;
3931 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3932 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3933 remapstyles[k] = mod->brushq1.num_lightstyles;
3934 mod->brushq1.num_lightstyles++;
3937 for (k = 0;k < mod->nummodelsurfaces;k++)
3939 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3940 for (j = 0;j < MAXLIGHTMAPS;j++)
3942 if (surface->lightmapinfo->styles[j] != 255)
3944 int r = remapstyles[surface->lightmapinfo->styles[j]];
3945 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3949 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3950 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3954 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3955 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3957 //mod->brushq1.num_visleafs = bm->visleafs;
3959 // build a Bounding Interval Hierarchy for culling triangles in light rendering
3960 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
3962 if (mod_q1bsp_polygoncollisions.integer)
3964 mod->collision_bih = mod->render_bih;
3965 // point traces and contents checks still use the bsp tree
3966 mod->TraceLine = Mod_CollisionBIH_TraceLine;
3967 mod->TraceBox = Mod_CollisionBIH_TraceBox;
3968 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
3969 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
3972 // generate VBOs and other shared data before cloning submodels
3976 Mod_Q1BSP_LoadMapBrushes();
3977 //Mod_Q1BSP_ProcessLightList();
3981 Con_DPrintf("Stats for q1bsp model \"%s\": %i faces, %i nodes, %i leafs, %i visleafs, %i visleafportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
3984 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3988 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3995 in = (void *)(mod_base + l->fileofs);
3996 if (l->filelen % sizeof(*in))
3997 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3998 count = l->filelen / sizeof(*in);
3999 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4002 loadmodel->num = count;
4004 for (i = 0;i < count;i++, in++, out++)
4010 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4017 in = (void *)(mod_base + l->fileofs);
4018 if (l->filelen % sizeof(*in))
4019 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4020 count = l->filelen / sizeof(*in);
4021 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4024 loadmodel->num = count;
4026 for (i = 0;i < count;i++, in++, out++)
4032 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4039 in = (void *)(mod_base + l->fileofs);
4040 if (l->filelen % sizeof(*in))
4041 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4042 count = l->filelen / sizeof(*in);
4043 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4046 loadmodel->num = count;
4048 for (i = 0;i < count;i++, in++, out++)
4054 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4061 in = (void *)(mod_base + l->fileofs);
4062 if (l->filelen % sizeof(*in))
4063 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4064 count = l->filelen / sizeof(*in);
4065 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4068 loadmodel->num = count;
4070 for (i = 0;i < count;i++, in++, out++)
4076 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
4083 in = (void *)(mod_base + l->fileofs);
4084 if (l->filelen % sizeof(*in))
4085 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
4086 count = l->filelen / sizeof(*in);
4087 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4090 loadmodel->num = count;
4092 for (i = 0;i < count;i++, in++, out++)
4098 static void Mod_Q2BSP_LoadFaces(lump_t *l)
4105 in = (void *)(mod_base + l->fileofs);
4106 if (l->filelen % sizeof(*in))
4107 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4108 count = l->filelen / sizeof(*in);
4109 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4112 loadmodel->num = count;
4114 for (i = 0;i < count;i++, in++, out++)
4120 static void Mod_Q2BSP_LoadLighting(lump_t *l)
4127 in = (void *)(mod_base + l->fileofs);
4128 if (l->filelen % sizeof(*in))
4129 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
4130 count = l->filelen / sizeof(*in);
4131 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4134 loadmodel->num = count;
4136 for (i = 0;i < count;i++, in++, out++)
4142 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
4149 in = (void *)(mod_base + l->fileofs);
4150 if (l->filelen % sizeof(*in))
4151 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4152 count = l->filelen / sizeof(*in);
4153 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4156 loadmodel->num = count;
4158 for (i = 0;i < count;i++, in++, out++)
4164 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
4171 in = (void *)(mod_base + l->fileofs);
4172 if (l->filelen % sizeof(*in))
4173 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4174 count = l->filelen / sizeof(*in);
4175 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4178 loadmodel->num = count;
4180 for (i = 0;i < count;i++, in++, out++)
4186 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
4193 in = (void *)(mod_base + l->fileofs);
4194 if (l->filelen % sizeof(*in))
4195 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4196 count = l->filelen / sizeof(*in);
4197 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4200 loadmodel->num = count;
4202 for (i = 0;i < count;i++, in++, out++)
4208 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4215 in = (void *)(mod_base + l->fileofs);
4216 if (l->filelen % sizeof(*in))
4217 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4218 count = l->filelen / sizeof(*in);
4219 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4222 loadmodel->num = count;
4224 for (i = 0;i < count;i++, in++, out++)
4230 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4237 in = (void *)(mod_base + l->fileofs);
4238 if (l->filelen % sizeof(*in))
4239 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4240 count = l->filelen / sizeof(*in);
4241 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4244 loadmodel->num = count;
4246 for (i = 0;i < count;i++, in++, out++)
4252 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4259 in = (void *)(mod_base + l->fileofs);
4260 if (l->filelen % sizeof(*in))
4261 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4262 count = l->filelen / sizeof(*in);
4263 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4266 loadmodel->num = count;
4268 for (i = 0;i < count;i++, in++, out++)
4274 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4281 in = (void *)(mod_base + l->fileofs);
4282 if (l->filelen % sizeof(*in))
4283 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4284 count = l->filelen / sizeof(*in);
4285 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4288 loadmodel->num = count;
4290 for (i = 0;i < count;i++, in++, out++)
4296 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4303 in = (void *)(mod_base + l->fileofs);
4304 if (l->filelen % sizeof(*in))
4305 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4306 count = l->filelen / sizeof(*in);
4307 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4310 loadmodel->num = count;
4312 for (i = 0;i < count;i++, in++, out++)
4318 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4325 in = (void *)(mod_base + l->fileofs);
4326 if (l->filelen % sizeof(*in))
4327 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4328 count = l->filelen / sizeof(*in);
4329 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4332 loadmodel->num = count;
4334 for (i = 0;i < count;i++, in++, out++)
4340 static void Mod_Q2BSP_LoadModels(lump_t *l)
4347 in = (void *)(mod_base + l->fileofs);
4348 if (l->filelen % sizeof(*in))
4349 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4350 count = l->filelen / sizeof(*in);
4351 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4354 loadmodel->num = count;
4356 for (i = 0;i < count;i++, in++, out++)
4362 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4365 q2dheader_t *header;
4367 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4369 mod->modeldatatypestring = "Q2BSP";
4371 mod->type = mod_brushq2;
4373 header = (q2dheader_t *)buffer;
4375 i = LittleLong(header->version);
4376 if (i != Q2BSPVERSION)
4377 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4379 mod_base = (unsigned char *)header;
4381 // swap all the lumps
4382 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4383 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4385 mod->brush.qw_md4sum = 0;
4386 mod->brush.qw_md4sum2 = 0;
4387 for (i = 0;i < Q2HEADER_LUMPS;i++)
4389 if (i == Q2LUMP_ENTITIES)
4391 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4392 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4394 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4397 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4398 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4399 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4400 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4401 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4402 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4403 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4404 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4405 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4406 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4407 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4408 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4409 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4410 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4411 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4412 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4413 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4414 // LordHavoc: must go last because this makes the submodels
4415 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4418 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4419 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4421 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4424 char key[128], value[MAX_INPUTLINE];
4426 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4427 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4428 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4431 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4432 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4433 loadmodel->brush.entities[l->filelen] = 0;
4434 data = loadmodel->brush.entities;
4435 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4436 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4437 loadmodel->brushq3.deluxemapping = false;
4438 if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4442 if (!COM_ParseToken_Simple(&data, false, false))
4444 if (com_token[0] == '}')
4445 break; // end of worldspawn
4446 if (com_token[0] == '_')
4447 strlcpy(key, com_token + 1, sizeof(key));
4449 strlcpy(key, com_token, sizeof(key));
4450 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4451 key[strlen(key)-1] = 0;
4452 if (!COM_ParseToken_Simple(&data, false, false))
4454 strlcpy(value, com_token, sizeof(value));
4455 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4457 #if _MSC_VER >= 1400
4458 #define sscanf sscanf_s
4461 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4462 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4464 VectorSet(v, 64, 64, 128);
4465 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4466 Con_Printf("Mod_Q3BSP_LoadEntities: funny gridsize \"%s\" in %s, interpreting as \"%f %f %f\" to match q3map2's parsing\n", value, loadmodel->name, v[0], v[1], v[2]);
4467 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4468 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4471 else if (!strcmp("deluxeMaps", key))
4473 if (!strcmp(com_token, "1"))
4475 loadmodel->brushq3.deluxemapping = true;
4476 loadmodel->brushq3.deluxemapping_modelspace = true;
4478 else if (!strcmp(com_token, "2"))
4480 loadmodel->brushq3.deluxemapping = true;
4481 loadmodel->brushq3.deluxemapping_modelspace = false;
4488 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4494 in = (q3dtexture_t *)(mod_base + l->fileofs);
4495 if (l->filelen % sizeof(*in))
4496 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4497 count = l->filelen / sizeof(*in);
4498 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4500 loadmodel->data_textures = out;
4501 loadmodel->num_textures = count;
4502 loadmodel->num_texturesperskin = loadmodel->num_textures;
4504 for (i = 0;i < count;i++)
4506 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4507 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4508 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4509 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4510 // restore the surfaceflags and supercontents
4511 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4512 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4516 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4522 in = (q3dplane_t *)(mod_base + l->fileofs);
4523 if (l->filelen % sizeof(*in))
4524 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4525 count = l->filelen / sizeof(*in);
4526 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4528 loadmodel->brush.data_planes = out;
4529 loadmodel->brush.num_planes = count;
4531 for (i = 0;i < count;i++, in++, out++)
4533 out->normal[0] = LittleFloat(in->normal[0]);
4534 out->normal[1] = LittleFloat(in->normal[1]);
4535 out->normal[2] = LittleFloat(in->normal[2]);
4536 out->dist = LittleFloat(in->dist);
4541 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4544 q3mbrushside_t *out;
4547 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4548 if (l->filelen % sizeof(*in))
4549 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4550 count = l->filelen / sizeof(*in);
4551 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4553 loadmodel->brush.data_brushsides = out;
4554 loadmodel->brush.num_brushsides = count;
4556 for (i = 0;i < count;i++, in++, out++)
4558 n = LittleLong(in->planeindex);
4559 if (n < 0 || n >= loadmodel->brush.num_planes)
4560 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4561 out->plane = loadmodel->brush.data_planes + n;
4562 n = LittleLong(in->textureindex);
4563 if (n < 0 || n >= loadmodel->num_textures)
4564 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4565 out->texture = loadmodel->data_textures + n;
4569 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4571 q3dbrushside_ig_t *in;
4572 q3mbrushside_t *out;
4575 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4576 if (l->filelen % sizeof(*in))
4577 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4578 count = l->filelen / sizeof(*in);
4579 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4581 loadmodel->brush.data_brushsides = out;
4582 loadmodel->brush.num_brushsides = count;
4584 for (i = 0;i < count;i++, in++, out++)
4586 n = LittleLong(in->planeindex);
4587 if (n < 0 || n >= loadmodel->brush.num_planes)
4588 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4589 out->plane = loadmodel->brush.data_planes + n;
4590 n = LittleLong(in->textureindex);
4591 if (n < 0 || n >= loadmodel->num_textures)
4592 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4593 out->texture = loadmodel->data_textures + n;
4597 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4601 int i, j, n, c, count, maxplanes, q3surfaceflags;
4602 colplanef_t *planes;
4604 in = (q3dbrush_t *)(mod_base + l->fileofs);
4605 if (l->filelen % sizeof(*in))
4606 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4607 count = l->filelen / sizeof(*in);
4608 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4610 loadmodel->brush.data_brushes = out;
4611 loadmodel->brush.num_brushes = count;
4616 for (i = 0;i < count;i++, in++, out++)
4618 n = LittleLong(in->firstbrushside);
4619 c = LittleLong(in->numbrushsides);
4620 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4621 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4622 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4623 out->numbrushsides = c;
4624 n = LittleLong(in->textureindex);
4625 if (n < 0 || n >= loadmodel->num_textures)
4626 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4627 out->texture = loadmodel->data_textures + n;
4629 // make a list of mplane_t structs to construct a colbrush from
4630 if (maxplanes < out->numbrushsides)
4632 maxplanes = out->numbrushsides;
4635 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4638 for (j = 0;j < out->numbrushsides;j++)
4640 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4641 planes[j].dist = out->firstbrushside[j].plane->dist;
4642 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4643 planes[j].texture = out->firstbrushside[j].texture;
4644 q3surfaceflags |= planes[j].q3surfaceflags;
4646 // make the colbrush from the planes
4647 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4649 // this whole loop can take a while (e.g. on redstarrepublic4)
4650 CL_KeepaliveMessage(false);
4656 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4662 in = (q3deffect_t *)(mod_base + l->fileofs);
4663 if (l->filelen % sizeof(*in))
4664 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4665 count = l->filelen / sizeof(*in);
4666 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4668 loadmodel->brushq3.data_effects = out;
4669 loadmodel->brushq3.num_effects = count;
4671 for (i = 0;i < count;i++, in++, out++)
4673 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4674 n = LittleLong(in->brushindex);
4675 if (n >= loadmodel->brush.num_brushes)
4677 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4680 out->brushindex = n;
4681 out->unknown = LittleLong(in->unknown);
4685 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4690 in = (q3dvertex_t *)(mod_base + l->fileofs);
4691 if (l->filelen % sizeof(*in))
4692 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4693 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4694 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4695 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4696 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4697 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4698 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4700 for (i = 0;i < count;i++, in++)
4702 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4703 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4704 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4705 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4706 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4707 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4708 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4709 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4710 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4711 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4712 // svector/tvector are calculated later in face loading
4713 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4714 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4715 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4716 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4717 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4718 loadmodel->lit = true;
4722 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4728 in = (int *)(mod_base + l->fileofs);
4729 if (l->filelen % sizeof(int[3]))
4730 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4731 count = l->filelen / sizeof(*in);
4733 if(!loadmodel->brushq3.num_vertices)
4736 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4737 loadmodel->brushq3.num_triangles = 0;
4741 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4742 loadmodel->brushq3.num_triangles = count / 3;
4743 loadmodel->brushq3.data_element3i = out;
4745 for (i = 0;i < count;i++, in++, out++)
4747 *out = LittleLong(*in);
4748 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4750 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4756 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4758 q3dlightmap_t *input_pointer;
4776 int mergedrowsxcolumns;
4781 unsigned char *mergedpixels;
4782 unsigned char *mergeddeluxepixels;
4783 unsigned char *mergebuf;
4784 char mapname[MAX_QPATH];
4786 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4788 // defaults for q3bsp
4795 loadmodel->brushq3.lightmapsize = 128;
4797 if (cls.state == ca_dedicated)
4800 if(mod_q3bsp_nolightmaps.integer)
4806 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4807 if (developer_loading.integer)
4808 Con_Printf("Using internal lightmaps\n");
4809 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4810 if (l->filelen % sizeof(*input_pointer))
4811 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4812 count = l->filelen / sizeof(*input_pointer);
4813 for(i = 0; i < count; ++i)
4814 inpixels[i] = input_pointer[i].rgb;
4818 // no internal lightmaps
4819 // try external lightmaps
4820 if (developer_loading.integer)
4821 Con_Printf("Using external lightmaps\n");
4822 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4823 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false, NULL);
4827 // using EXTERNAL lightmaps instead
4828 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4830 Mem_Free(inpixels[0]);
4831 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4841 for(count = 1; ; ++count)
4843 inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false, NULL);
4844 if(!inpixels[count])
4845 break; // we got all of them
4846 if(image_width != size || image_height != size)
4848 Mem_Free(inpixels[count]);
4849 inpixels[count] = NULL;
4850 Con_Printf("Mod_Q3BSP_LoadLightmaps: mismatched lightmap size in %s - external lightmap %s/lm_%04d does not match earlier ones\n", loadmodel->name, mapname, count);
4856 loadmodel->brushq3.lightmapsize = size;
4857 loadmodel->brushq3.num_originallightmaps = count;
4859 // now check the surfaces to see if any of them index an odd numbered
4860 // lightmap, if so this is not a deluxemapped bsp file
4862 // also check what lightmaps are actually used, because q3map2 sometimes
4863 // (always?) makes an unused one at the end, which
4864 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4865 // reason when only one lightmap is used, which can throw off the
4866 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4867 // to see if the second lightmap is blank, if so it is not deluxemapped.
4868 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4869 // in Mod_Q3BSP_LoadEntities was failed
4870 if (!loadmodel->brushq3.deluxemapping)
4872 loadmodel->brushq3.deluxemapping = !(count & 1);
4873 loadmodel->brushq3.deluxemapping_modelspace = true;
4875 if (loadmodel->brushq3.deluxemapping)
4877 int facecount = faceslump->filelen / sizeof(q3dface_t);
4878 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4879 for (i = 0;i < facecount;i++)
4881 j = LittleLong(faces[i].lightmapindex);
4884 endlightmap = max(endlightmap, j + 1);
4885 if ((j & 1) || j + 1 >= count)
4887 loadmodel->brushq3.deluxemapping = false;
4894 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4895 // reason when only one lightmap is used, which can throw off the
4896 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4897 // to see if the second lightmap is blank, if so it is not deluxemapped.
4899 // further research has shown q3map2 sometimes creates a deluxemap and two
4900 // blank lightmaps, which must be handled properly as well
4901 if (endlightmap == 1 && count > 1)
4904 for (i = 0;i < size*size;i++)
4906 if (c[bytesperpixel*i + rgbmap[0]])
4908 if (c[bytesperpixel*i + rgbmap[1]])
4910 if (c[bytesperpixel*i + rgbmap[2]])
4915 // all pixels in the unused lightmap were black...
4916 loadmodel->brushq3.deluxemapping = false;
4921 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4923 // figure out what the most reasonable merge power is within limits
4925 // find the appropriate NxN dimensions to merge to, to avoid wasted space
4926 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
4928 // figure out how big the merged texture has to be
4929 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
4930 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
4931 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
4933 mergedwidth = mergegoal;
4934 mergedheight = mergegoal;
4935 // choose non-square size (2x1 aspect) if only half the space is used;
4936 // this really only happens when the entire set fits in one texture, if
4937 // there are multiple textures, we don't worry about shrinking the last
4938 // one to fit, because the driver prefers the same texture size on
4939 // consecutive draw calls...
4940 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
4943 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
4944 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
4945 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
4946 loadmodel->brushq3.num_lightmapmergedwidthpower++;
4947 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
4948 loadmodel->brushq3.num_lightmapmergedheightpower++;
4949 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
4951 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
4952 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
4953 powerxy = powerx+powery;
4954 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
4956 mergedcolumns = 1 << powerx;
4957 mergedrows = 1 << powery;
4958 mergedrowsxcolumns = 1 << powerxy;
4960 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
4961 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4962 if (loadmodel->brushq3.deluxemapping)
4963 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4965 // allocate a texture pool if we need it
4966 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4967 loadmodel->texturepool = R_AllocTexturePool();
4969 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
4970 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
4971 for (i = 0;i < count;i++)
4973 // figure out which merged lightmap texture this fits into
4974 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
4975 lightmapindex = i >> powerdxy;
4977 // choose the destination address
4978 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
4979 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
4980 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
4981 Con_Printf("copying original lightmap %i (%ix%i) to %i (at %i,%i)\n", i, size, size, lightmapindex, (realindex & (mergedcolumns-1))*size, ((realindex >> powerx) & (mergedrows-1))*size);
4983 // convert pixels from RGB or BGRA while copying them into the destination rectangle
4984 for (j = 0;j < size;j++)
4985 for (k = 0;k < size;k++)
4987 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
4988 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
4989 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
4990 mergebuf[(j*mergedwidth+k)*4+3] = 255;
4993 // upload texture if this was the last tile being written to the texture
4994 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
4996 if (loadmodel->brushq3.deluxemapping && (i & 1))
4997 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%04i", lightmapindex), mergedwidth, mergedheight, mergeddeluxepixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
4999 loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5003 if (mergeddeluxepixels)
5004 Mem_Free(mergeddeluxepixels);
5005 Mem_Free(mergedpixels);
5008 for(i = 0; i < count; ++i)
5009 Mem_Free(inpixels[i]);
5013 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5018 *collisionstride = stride;
5021 cnt = (num_triangles + stride - 1) / stride;
5022 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5023 for(j = 0; j < cnt; ++j)
5025 mins = &((*collisionbbox6f)[6 * j + 0]);
5026 maxs = &((*collisionbbox6f)[6 * j + 3]);
5027 for(k = 0; k < stride; ++k)
5029 tri = j * stride + k;
5030 if(tri >= num_triangles)
5032 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5033 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5034 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5035 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5036 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5037 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5038 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5039 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5040 if(vert[0] < mins[0]) mins[0] = vert[0];
5041 if(vert[1] < mins[1]) mins[1] = vert[1];
5042 if(vert[2] < mins[2]) mins[2] = vert[2];
5043 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5044 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5045 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5046 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5047 if(vert[0] < mins[0]) mins[0] = vert[0];
5048 if(vert[1] < mins[1]) mins[1] = vert[1];
5049 if(vert[2] < mins[2]) mins[2] = vert[2];
5050 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5051 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5052 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5057 *collisionbbox6f = NULL;
5060 typedef struct patchtess_s
5064 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5067 float *originalvertex3f;
5070 #define PATCHTESS_SAME_LODGROUP(a,b) \
5072 (a).lodgroup[0] == (b).lodgroup[0] && \
5073 (a).lodgroup[1] == (b).lodgroup[1] && \
5074 (a).lodgroup[2] == (b).lodgroup[2] && \
5075 (a).lodgroup[3] == (b).lodgroup[3] && \
5076 (a).lodgroup[4] == (b).lodgroup[4] && \
5077 (a).lodgroup[5] == (b).lodgroup[5] \
5080 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5082 q3dface_t *in, *oldin;
5083 msurface_t *out, *oldout;
5084 int i, oldi, j, n, count, invalidelements, patchsize[2], finalwidth, finalheight, xtess, ytess, finalvertices, finaltriangles, firstvertex, firstelement, type, oldnumtriangles, oldnumtriangles2, meshvertices, meshtriangles, collisionvertices, collisiontriangles, numvertices, numtriangles, cxtess, cytess;
5085 float lightmaptcbase[2], lightmaptcscale[2];
5086 //int *originalelement3i;
5087 //int *originalneighbor3i;
5088 float *originalvertex3f;
5089 //float *originalsvector3f;
5090 //float *originaltvector3f;
5091 float *originalnormal3f;
5092 float *originalcolor4f;
5093 float *originaltexcoordtexture2f;
5094 float *originaltexcoordlightmap2f;
5095 float *surfacecollisionvertex3f;
5096 int *surfacecollisionelement3i;
5098 patchtess_t *patchtess = NULL;
5099 int patchtesscount = 0;
5102 in = (q3dface_t *)(mod_base + l->fileofs);
5103 if (l->filelen % sizeof(*in))
5104 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5105 count = l->filelen / sizeof(*in);
5106 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5108 loadmodel->data_surfaces = out;
5109 loadmodel->num_surfaces = count;
5112 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5120 for (;i < count;i++, in++, out++)
5122 // check face type first
5123 type = LittleLong(in->type);
5124 if (type != Q3FACETYPE_FLAT
5125 && type != Q3FACETYPE_PATCH
5126 && type != Q3FACETYPE_MESH
5127 && type != Q3FACETYPE_FLARE)
5129 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5133 n = LittleLong(in->textureindex);
5134 if (n < 0 || n >= loadmodel->num_textures)
5136 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5139 out->texture = loadmodel->data_textures + n;
5140 n = LittleLong(in->effectindex);
5141 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5143 if (developer_extra.integer)
5144 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5150 out->effect = loadmodel->brushq3.data_effects + n;
5152 if (cls.state != ca_dedicated)
5154 out->lightmaptexture = NULL;
5155 out->deluxemaptexture = r_texture_blanknormalmap;
5156 n = LittleLong(in->lightmapindex);
5159 else if (n >= loadmodel->brushq3.num_originallightmaps)
5161 if(loadmodel->brushq3.num_originallightmaps != 0)
5162 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5167 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5168 if (loadmodel->brushq3.deluxemapping)
5169 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5170 loadmodel->lit = true;
5174 firstvertex = LittleLong(in->firstvertex);
5175 numvertices = LittleLong(in->numvertices);
5176 firstelement = LittleLong(in->firstelement);
5177 numtriangles = LittleLong(in->numelements) / 3;
5178 if (numtriangles * 3 != LittleLong(in->numelements))
5180 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));
5183 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5185 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);
5188 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5190 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);
5195 case Q3FACETYPE_FLAT:
5196 case Q3FACETYPE_MESH:
5197 // no processing necessary
5199 case Q3FACETYPE_PATCH:
5200 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5201 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5202 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))
5204 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5207 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5209 // convert patch to Q3FACETYPE_MESH
5210 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5211 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5212 // bound to user settings
5213 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5214 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5215 // bound to sanity settings
5216 xtess = bound(0, xtess, 1024);
5217 ytess = bound(0, ytess, 1024);
5219 // lower quality collision patches! Same procedure as before, but different cvars
5220 // convert patch to Q3FACETYPE_MESH
5221 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5222 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5223 // bound to user settings
5224 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5225 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5226 // bound to sanity settings
5227 cxtess = bound(0, cxtess, 1024);
5228 cytess = bound(0, cytess, 1024);
5230 // store it for the LOD grouping step
5231 patchtess[patchtesscount].info.xsize = patchsize[0];
5232 patchtess[patchtesscount].info.ysize = patchsize[1];
5233 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5234 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5235 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5236 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5238 patchtess[patchtesscount].surface_id = i;
5239 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5240 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5241 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5242 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5243 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5244 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5245 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5248 case Q3FACETYPE_FLARE:
5249 if (developer_extra.integer)
5250 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5254 out->num_vertices = numvertices;
5255 out->num_triangles = numtriangles;
5256 meshvertices += out->num_vertices;
5257 meshtriangles += out->num_triangles;
5260 // Fix patches tesselations so that they make no seams
5264 for(i = 0; i < patchtesscount; ++i)
5266 for(j = i+1; j < patchtesscount; ++j)
5268 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5271 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5278 // Calculate resulting number of triangles
5279 collisionvertices = 0;
5280 collisiontriangles = 0;
5281 for(i = 0; i < patchtesscount; ++i)
5283 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5284 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5285 numvertices = finalwidth * finalheight;
5286 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5288 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5289 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5290 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5291 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5293 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5294 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5295 numvertices = finalwidth * finalheight;
5296 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5298 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5299 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5300 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5301 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5307 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5308 if (collisiontriangles)
5310 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5311 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5315 collisionvertices = 0;
5316 collisiontriangles = 0;
5317 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5319 if (out->num_vertices < 3 || out->num_triangles < 1)
5322 type = LittleLong(in->type);
5323 firstvertex = LittleLong(in->firstvertex);
5324 firstelement = LittleLong(in->firstelement);
5325 out->num_firstvertex = meshvertices;
5326 out->num_firsttriangle = meshtriangles;
5327 out->num_firstcollisiontriangle = collisiontriangles;
5330 case Q3FACETYPE_FLAT:
5331 case Q3FACETYPE_MESH:
5332 // no processing necessary, except for lightmap merging
5333 for (j = 0;j < out->num_vertices;j++)
5335 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5336 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5337 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5338 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5339 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5340 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5341 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5342 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5343 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5344 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5345 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5346 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5347 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5348 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5350 for (j = 0;j < out->num_triangles*3;j++)
5351 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5353 case Q3FACETYPE_PATCH:
5354 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5355 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5356 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5357 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5358 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5359 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5360 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5362 xtess = ytess = cxtess = cytess = -1;
5363 for(j = 0; j < patchtesscount; ++j)
5364 if(patchtess[j].surface_id == i)
5366 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5367 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5368 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5369 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5374 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5375 xtess = ytess = cxtess = cytess = 0;
5378 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5379 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5380 finalvertices = finalwidth * finalheight;
5381 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5382 type = Q3FACETYPE_MESH;
5383 // generate geometry
5384 // (note: normals are skipped because they get recalculated)
5385 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5386 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5387 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5388 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5389 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5390 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5392 out->num_triangles = Mod_RemoveDegenerateTriangles(out->num_triangles, (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), loadmodel->surfmesh.data_vertex3f);
5394 if (developer_extra.integer)
5396 if (out->num_triangles < finaltriangles)
5397 Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles, %i degenerate triangles removed (leaving %i)\n", patchsize[0], patchsize[1], out->num_vertices, finaltriangles, finaltriangles - out->num_triangles, out->num_triangles);
5399 Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles\n", patchsize[0], patchsize[1], out->num_vertices, out->num_triangles);
5401 // q3map does not put in collision brushes for curves... ugh
5402 // build the lower quality collision geometry
5403 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5404 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5405 finalvertices = finalwidth * finalheight;
5406 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5408 // legacy collision geometry implementation
5409 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5410 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5411 out->num_collisionvertices = finalvertices;
5412 out->num_collisiontriangles = finaltriangles;
5413 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5414 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5416 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5417 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5419 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5421 // now optimize the collision mesh by finding triangle bboxes...
5422 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5423 Mod_Q3BSP_BuildBBoxes(loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle, out->num_triangles, loadmodel->surfmesh.data_vertex3f, &out->deprecatedq3data_bbox6f, &out->deprecatedq3num_bboxstride, mod_q3bsp_curves_stride.integer);
5425 // store collision geometry for BIH collision tree
5426 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5427 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5428 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5429 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5430 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5432 // remove this once the legacy code is removed
5434 int nc = out->num_collisiontriangles;
5436 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5438 if(nc != out->num_collisiontriangles)
5440 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5445 if (developer_extra.integer)
5446 Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve became %i:%i vertices / %i:%i triangles (%i:%i degenerate)\n", patchsize[0], patchsize[1], out->num_vertices, out->num_collisionvertices, oldnumtriangles, oldnumtriangles2, oldnumtriangles - out->num_triangles, oldnumtriangles2 - out->num_collisiontriangles);
5448 collisionvertices += finalvertices;
5449 collisiontriangles += out->num_collisiontriangles;
5454 meshvertices += out->num_vertices;
5455 meshtriangles += out->num_triangles;
5456 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5457 if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
5459 if (invalidelements)
5461 Con_Printf("Mod_Q3BSP_LoadFaces: Warning: face #%i has %i invalid elements, type = %i, texture->name = \"%s\", texture->surfaceflags = %i, firstvertex = %i, numvertices = %i, firstelement = %i, numelements = %i, elements list:\n", i, invalidelements, type, out->texture->name, out->texture->surfaceflags, firstvertex, out->num_vertices, firstelement, out->num_triangles * 3);
5462 for (j = 0;j < out->num_triangles * 3;j++)
5464 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5465 if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
5466 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5470 // calculate a bounding box
5471 VectorClear(out->mins);
5472 VectorClear(out->maxs);
5473 if (out->num_vertices)
5475 if (cls.state != ca_dedicated && out->lightmaptexture)
5477 // figure out which part of the merged lightmap this fits into
5478 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5479 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5480 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5481 lightmapindex &= mergewidth * mergeheight - 1;
5482 lightmaptcscale[0] = 1.0f / mergewidth;
5483 lightmaptcscale[1] = 1.0f / mergeheight;
5484 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5485 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5486 // modify the lightmap texcoords to match this region of the merged lightmap
5487 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5489 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5490 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5493 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5494 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5495 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5497 out->mins[0] = min(out->mins[0], v[0]);
5498 out->maxs[0] = max(out->maxs[0], v[0]);
5499 out->mins[1] = min(out->mins[1], v[1]);
5500 out->maxs[1] = max(out->maxs[1], v[1]);
5501 out->mins[2] = min(out->mins[2], v[2]);
5502 out->maxs[2] = max(out->maxs[2], v[2]);
5504 out->mins[0] -= 1.0f;
5505 out->mins[1] -= 1.0f;
5506 out->mins[2] -= 1.0f;
5507 out->maxs[0] += 1.0f;
5508 out->maxs[1] += 1.0f;
5509 out->maxs[2] += 1.0f;
5511 // set lightmap styles for consistency with q1bsp
5512 //out->lightmapinfo->styles[0] = 0;
5513 //out->lightmapinfo->styles[1] = 255;
5514 //out->lightmapinfo->styles[2] = 255;
5515 //out->lightmapinfo->styles[3] = 255;
5520 for (;i < count;i++, out++)
5522 if(out->num_vertices && out->num_triangles)
5524 if(out->num_vertices == 0)
5526 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5527 if(out->num_triangles == 0)
5528 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5530 else if(out->num_triangles == 0)
5531 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s, near %f %f %f) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)",
5532 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5533 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5534 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5537 // for per pixel lighting
5538 Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
5540 // generate ushort elements array if possible
5541 if (loadmodel->surfmesh.data_element3s)
5542 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5543 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5545 // free the no longer needed vertex data
5546 loadmodel->brushq3.num_vertices = 0;
5547 if (loadmodel->brushq3.data_vertex3f)
5548 Mem_Free(loadmodel->brushq3.data_vertex3f);
5549 loadmodel->brushq3.data_vertex3f = NULL;
5550 loadmodel->brushq3.data_normal3f = NULL;
5551 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5552 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5553 loadmodel->brushq3.data_color4f = NULL;
5554 // free the no longer needed triangle data
5555 loadmodel->brushq3.num_triangles = 0;
5556 if (loadmodel->brushq3.data_element3i)
5557 Mem_Free(loadmodel->brushq3.data_element3i);
5558 loadmodel->brushq3.data_element3i = NULL;
5561 Mem_Free(patchtess);
5564 static void Mod_Q3BSP_LoadModels(lump_t *l)
5568 int i, j, n, c, count;
5570 in = (q3dmodel_t *)(mod_base + l->fileofs);
5571 if (l->filelen % sizeof(*in))
5572 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5573 count = l->filelen / sizeof(*in);
5574 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5576 loadmodel->brushq3.data_models = out;
5577 loadmodel->brushq3.num_models = count;
5579 for (i = 0;i < count;i++, in++, out++)
5581 for (j = 0;j < 3;j++)
5583 out->mins[j] = LittleFloat(in->mins[j]);
5584 out->maxs[j] = LittleFloat(in->maxs[j]);
5586 n = LittleLong(in->firstface);
5587 c = LittleLong(in->numfaces);
5588 if (n < 0 || n + c > loadmodel->num_surfaces)
5589 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5592 n = LittleLong(in->firstbrush);
5593 c = LittleLong(in->numbrushes);
5594 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5595 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5596 out->firstbrush = n;
5597 out->numbrushes = c;
5601 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5607 in = (int *)(mod_base + l->fileofs);
5608 if (l->filelen % sizeof(*in))
5609 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5610 count = l->filelen / sizeof(*in);
5611 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5613 loadmodel->brush.data_leafbrushes = out;
5614 loadmodel->brush.num_leafbrushes = count;
5616 for (i = 0;i < count;i++, in++, out++)
5618 n = LittleLong(*in);
5619 if (n < 0 || n >= loadmodel->brush.num_brushes)
5620 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5625 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5631 in = (int *)(mod_base + l->fileofs);
5632 if (l->filelen % sizeof(*in))
5633 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5634 count = l->filelen / sizeof(*in);
5635 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5637 loadmodel->brush.data_leafsurfaces = out;
5638 loadmodel->brush.num_leafsurfaces = count;
5640 for (i = 0;i < count;i++, in++, out++)
5642 n = LittleLong(*in);
5643 if (n < 0 || n >= loadmodel->num_surfaces)
5644 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5649 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5653 int i, j, n, c, count;
5655 in = (q3dleaf_t *)(mod_base + l->fileofs);
5656 if (l->filelen % sizeof(*in))
5657 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5658 count = l->filelen / sizeof(*in);
5659 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5661 loadmodel->brush.data_leafs = out;
5662 loadmodel->brush.num_leafs = count;
5664 for (i = 0;i < count;i++, in++, out++)
5668 out->clusterindex = LittleLong(in->clusterindex);
5669 out->areaindex = LittleLong(in->areaindex);
5670 for (j = 0;j < 3;j++)
5672 // yes the mins/maxs are ints
5673 out->mins[j] = LittleLong(in->mins[j]) - 1;
5674 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5676 n = LittleLong(in->firstleafface);
5677 c = LittleLong(in->numleaffaces);
5678 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5679 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5680 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5681 out->numleafsurfaces = c;
5682 n = LittleLong(in->firstleafbrush);
5683 c = LittleLong(in->numleafbrushes);
5684 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5685 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5686 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5687 out->numleafbrushes = c;
5691 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5697 in = (q3dnode_t *)(mod_base + l->fileofs);
5698 if (l->filelen % sizeof(*in))
5699 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5700 count = l->filelen / sizeof(*in);
5702 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5703 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5705 loadmodel->brush.data_nodes = out;
5706 loadmodel->brush.num_nodes = count;
5708 for (i = 0;i < count;i++, in++, out++)
5711 n = LittleLong(in->planeindex);
5712 if (n < 0 || n >= loadmodel->brush.num_planes)
5713 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5714 out->plane = loadmodel->brush.data_planes + n;
5715 for (j = 0;j < 2;j++)
5717 n = LittleLong(in->childrenindex[j]);
5720 if (n >= loadmodel->brush.num_nodes)
5721 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5722 out->children[j] = loadmodel->brush.data_nodes + n;
5727 if (n >= loadmodel->brush.num_leafs)
5728 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5729 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5732 for (j = 0;j < 3;j++)
5734 // yes the mins/maxs are ints
5735 out->mins[j] = LittleLong(in->mins[j]) - 1;
5736 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5740 // set the parent pointers
5741 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5744 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5747 q3dlightgrid_t *out;
5750 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5751 if (l->filelen % sizeof(*in))
5752 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5753 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5754 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5755 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5756 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5757 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5758 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5759 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5760 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5761 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5762 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5763 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5764 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5765 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5766 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]);
5767 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]);
5769 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5772 if (l->filelen < count * (int)sizeof(*in))
5774 Con_Printf("Mod_Q3BSP_LoadLightGrid: invalid lightgrid lump size %i bytes, should be %i bytes (%ix%ix%i)", l->filelen, (int)(count * sizeof(*in)), loadmodel->brushq3.num_lightgrid_isize[0], loadmodel->brushq3.num_lightgrid_isize[1], loadmodel->brushq3.num_lightgrid_isize[2]);
5775 return; // ignore the grid if we cannot understand it
5777 if (l->filelen != count * (int)sizeof(*in))
5778 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5779 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5780 loadmodel->brushq3.data_lightgrid = out;
5781 loadmodel->brushq3.num_lightgrid = count;
5782 // no swapping or validation necessary
5783 memcpy(out, in, count * (int)sizeof(*out));
5787 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5792 if (l->filelen == 0)
5795 // unvised maps often have cluster indices even without pvs, so check
5796 // leafs to find real number of clusters
5797 loadmodel->brush.num_pvsclusters = 1;
5798 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5799 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5802 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5803 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5804 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5805 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5809 in = (q3dpvs_t *)(mod_base + l->fileofs);
5811 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5813 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5814 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5815 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5816 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5817 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5818 if (l->filelen < totalchains + (int)sizeof(*in))
5819 Host_Error("Mod_Q3BSP_LoadPVS: lump too small ((numclusters = %i) * (chainlength = %i) + sizeof(q3dpvs_t) == %i bytes, lump is %i bytes)", loadmodel->brush.num_pvsclusters, loadmodel->brush.num_pvsclusterbytes, (int)(totalchains + sizeof(*in)), l->filelen);
5821 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5822 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5825 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5827 int i, j, k, index[3];
5828 float transformed[3], blend1, blend2, blend, stylescale = 1;
5829 q3dlightgrid_t *a, *s;
5831 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5832 switch(vid.renderpath)
5834 case RENDERPATH_GL20:
5835 case RENDERPATH_D3D9:
5836 case RENDERPATH_D3D10:
5837 case RENDERPATH_D3D11:
5838 case RENDERPATH_SOFT:
5839 case RENDERPATH_GLES2:
5840 // LordHavoc: FIXME: is this true?
5841 stylescale = 1; // added while render
5843 case RENDERPATH_GL11:
5844 case RENDERPATH_GL13:
5845 case RENDERPATH_GLES1:
5846 stylescale = r_refdef.scene.rtlightstylevalue[0];
5850 if (!model->brushq3.num_lightgrid)
5852 ambientcolor[0] = stylescale;
5853 ambientcolor[1] = stylescale;
5854 ambientcolor[2] = stylescale;
5858 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5859 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5860 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5861 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5862 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5863 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5864 index[0] = (int)floor(transformed[0]);
5865 index[1] = (int)floor(transformed[1]);
5866 index[2] = (int)floor(transformed[2]);
5867 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5869 // now lerp the values
5870 VectorClear(diffusenormal);
5871 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5872 for (k = 0;k < 2;k++)
5874 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5875 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5877 for (j = 0;j < 2;j++)
5879 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5880 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5882 for (i = 0;i < 2;i++)
5884 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5885 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5887 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5888 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5889 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5890 // this uses the mod_md3_sin table because the values are
5891 // already in the 0-255 range, the 64+ bias fetches a cosine
5892 // instead of a sine value
5893 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5894 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5895 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5896 //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)));
5901 // normalize the light direction before turning
5902 VectorNormalize(diffusenormal);
5903 //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]);
5906 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5909 double midf, mid[3];
5915 // find the point distances
5916 mplane_t *plane = node->plane;
5917 if (plane->type < 3)
5919 t1 = p1[plane->type] - plane->dist;
5920 t2 = p2[plane->type] - plane->dist;
5924 t1 = DotProduct (plane->normal, p1) - plane->dist;
5925 t2 = DotProduct (plane->normal, p2) - plane->dist;
5932 node = node->children[1];
5941 node = node->children[0];
5947 midf = t1 / (t1 - t2);
5948 VectorLerp(p1, midf, p2, mid);
5950 // recurse both sides, front side first
5951 // return 2 if empty is followed by solid (hit something)
5952 // do not return 2 if both are solid or both empty,
5953 // or if start is solid and end is empty
5954 // as these degenerate cases usually indicate the eye is in solid and
5955 // should see the target point anyway
5956 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
5959 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5964 return ((mleaf_t *)node)->clusterindex < 0;
5967 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5969 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
5972 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
5973 return trace.fraction == 1;
5977 double tracestart[3], traceend[3];
5978 VectorCopy(start, tracestart);
5979 VectorCopy(end, traceend);
5980 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
5984 void Mod_CollisionBIH_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
5987 const bih_leaf_t *leaf;
5988 const bih_node_t *node;
5989 const colbrushf_t *brush;
5992 int nodestackpos = 0;
5993 int nodestack[1024];
5995 memset(trace, 0, sizeof(*trace));
5996 trace->fraction = 1;
5997 trace->realfraction = 1;
5998 trace->hitsupercontentsmask = hitsupercontentsmask;
6000 bih = &model->collision_bih;
6004 nodenum = bih->rootnode;
6005 nodestack[nodestackpos++] = nodenum;
6006 while (nodestackpos)
6008 nodenum = nodestack[--nodestackpos];
6009 node = bih->nodes + nodenum;
6011 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6014 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6016 axis = node->type - BIH_SPLITX;
6017 if (start[axis] >= node->frontmin)
6018 nodestack[nodestackpos++] = node->front;
6019 if (start[axis] <= node->backmax)
6020 nodestack[nodestackpos++] = node->back;
6022 else if (node->type == BIH_UNORDERED)
6024 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6026 leaf = bih->leafs + node->children[axis];
6028 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6034 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6035 Collision_TracePointBrushFloat(trace, start, brush);
6037 case BIH_COLLISIONTRIANGLE:
6038 // collision triangle - skipped because they have no volume
6040 case BIH_RENDERTRIANGLE:
6041 // render triangle - skipped because they have no volume
6049 void Mod_CollisionBIH_TraceLineShared(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, const bih_t *bih)
6051 const bih_leaf_t *leaf;
6052 const bih_node_t *node;
6053 const colbrushf_t *brush;
6055 const texture_t *texture;
6056 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6057 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6058 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6063 if (VectorCompare(start, end))
6065 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6069 nodenum = bih->rootnode;
6071 memset(trace, 0, sizeof(*trace));
6072 trace->fraction = 1;
6073 trace->realfraction = 1;
6074 trace->hitsupercontentsmask = hitsupercontentsmask;
6077 nodestackline[nodestackpos][0] = start[0];
6078 nodestackline[nodestackpos][1] = start[1];
6079 nodestackline[nodestackpos][2] = start[2];
6080 nodestackline[nodestackpos][3] = end[0];
6081 nodestackline[nodestackpos][4] = end[1];
6082 nodestackline[nodestackpos][5] = end[2];
6083 nodestack[nodestackpos++] = nodenum;
6084 while (nodestackpos)
6086 nodenum = nodestack[--nodestackpos];
6087 node = bih->nodes + nodenum;
6088 VectorCopy(nodestackline[nodestackpos], nodestart);
6089 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6090 sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6091 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6093 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6095 // recurse children of the split
6096 axis = node->type - BIH_SPLITX;
6097 d1 = node->backmax - nodestart[axis];
6098 d2 = node->backmax - nodeend[axis];
6099 d3 = nodestart[axis] - node->frontmin;
6100 d4 = nodeend[axis] - node->frontmin;
6101 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6103 case 0: /* >>>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6104 case 1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6105 case 2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6106 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6107 case 4: /* >><> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6108 case 5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6109 case 6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6110 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6111 case 8: /* >>>< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6112 case 9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6113 case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6114 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6115 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6116 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6117 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6118 case 15: /* <<<< */ break;
6121 else if (node->type == BIH_UNORDERED)
6123 // calculate sweep bounds for this node
6124 // copy node bounds into local variables
6125 VectorCopy(node->mins, nodebigmins);
6126 VectorCopy(node->maxs, nodebigmaxs);
6127 // clip line to this node bounds
6128 axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6129 axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6130 axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6131 // some of the line intersected the enlarged node box
6132 // calculate sweep bounds for this node
6133 sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6134 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6136 leaf = bih->leafs + node->children[axis];
6137 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6142 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6143 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6145 case BIH_COLLISIONTRIANGLE:
6146 if (!mod_q3bsp_curves_collisions.integer)
6148 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6149 texture = model->data_textures + leaf->textureindex;
6150 Collision_TraceLineTriangleFloat(trace, start, end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6152 case BIH_RENDERTRIANGLE:
6153 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6154 texture = model->data_textures + leaf->textureindex;
6155 Collision_TraceLineTriangleFloat(trace, start, end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6163 void Mod_CollisionBIH_TraceLine(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
6165 if (VectorCompare(start, end))
6167 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6170 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6173 void Mod_CollisionBIH_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *thisbrush_start, colbrushf_t *thisbrush_end, int hitsupercontentsmask)
6176 const bih_leaf_t *leaf;
6177 const bih_node_t *node;
6178 const colbrushf_t *brush;
6180 const texture_t *texture;
6181 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6182 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6183 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6184 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6186 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6188 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6189 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6191 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6195 bih = &model->collision_bih;
6198 nodenum = bih->rootnode;
6200 // box trace, performed as brush trace
6201 memset(trace, 0, sizeof(*trace));
6202 trace->fraction = 1;
6203 trace->realfraction = 1;
6204 trace->hitsupercontentsmask = hitsupercontentsmask;
6206 // calculate tracebox-like parameters for efficient culling
6207 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6208 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6209 VectorSubtract(thisbrush_start->mins, start, startmins);
6210 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6211 VectorSubtract(thisbrush_end->mins, end, endmins);
6212 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6213 mins[0] = min(startmins[0], endmins[0]);
6214 mins[1] = min(startmins[1], endmins[1]);
6215 mins[2] = min(startmins[2], endmins[2]);
6216 maxs[0] = max(startmaxs[0], endmaxs[0]);
6217 maxs[1] = max(startmaxs[1], endmaxs[1]);
6218 maxs[2] = max(startmaxs[2], endmaxs[2]);
6221 nodestackline[nodestackpos][0] = start[0];
6222 nodestackline[nodestackpos][1] = start[1];
6223 nodestackline[nodestackpos][2] = start[2];
6224 nodestackline[nodestackpos][3] = end[0];
6225 nodestackline[nodestackpos][4] = end[1];
6226 nodestackline[nodestackpos][5] = end[2];
6227 nodestack[nodestackpos++] = nodenum;
6228 while (nodestackpos)
6230 nodenum = nodestack[--nodestackpos];
6231 node = bih->nodes + nodenum;
6232 VectorCopy(nodestackline[nodestackpos], nodestart);
6233 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6234 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6235 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6237 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6239 // recurse children of the split
6240 axis = node->type - BIH_SPLITX;
6241 d1 = node->backmax - nodestart[axis] - mins[axis];
6242 d2 = node->backmax - nodeend[axis] - mins[axis];
6243 d3 = nodestart[axis] - node->frontmin + maxs[axis];
6244 d4 = nodeend[axis] - node->frontmin + maxs[axis];
6245 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6247 case 0: /* >>>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6248 case 1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6249 case 2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6250 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6251 case 4: /* >><> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6252 case 5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6253 case 6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6254 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6255 case 8: /* >>>< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6256 case 9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6257 case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6258 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6259 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6260 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6261 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6262 case 15: /* <<<< */ break;
6265 else if (node->type == BIH_UNORDERED)
6267 // calculate sweep bounds for this node
6268 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6269 VectorSubtract(node->mins, maxs, nodebigmins);
6270 VectorSubtract(node->maxs, mins, nodebigmaxs);
6271 // clip line to this node bounds
6272 axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6273 axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6274 axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6275 // some of the line intersected the enlarged node box
6276 // calculate sweep bounds for this node
6277 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6278 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6280 leaf = bih->leafs + node->children[axis];
6281 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6286 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6287 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6289 case BIH_COLLISIONTRIANGLE:
6290 if (!mod_q3bsp_curves_collisions.integer)
6292 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6293 texture = model->data_textures + leaf->textureindex;
6294 Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6296 case BIH_RENDERTRIANGLE:
6297 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6298 texture = model->data_textures + leaf->textureindex;
6299 Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6307 void Mod_CollisionBIH_TraceBox(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
6309 colboxbrushf_t thisbrush_start, thisbrush_end;
6310 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6312 // box trace, performed as brush trace
6313 VectorAdd(start, boxmins, boxstartmins);
6314 VectorAdd(start, boxmaxs, boxstartmaxs);
6315 VectorAdd(end, boxmins, boxendmins);
6316 VectorAdd(end, boxmaxs, boxendmaxs);
6317 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6318 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6319 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6323 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6326 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6327 return trace.startsupercontents;
6330 void Mod_CollisionBIH_TracePoint_Mesh(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
6333 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6335 int hitsupercontents;
6336 VectorSet(end, start[0], start[1], model->normalmins[2]);
6338 memset(trace, 0, sizeof(*trace));
6339 trace->fraction = 1;
6340 trace->realfraction = 1;
6341 trace->hitsupercontentsmask = hitsupercontentsmask;
6343 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6344 hitsupercontents = trace->hitsupercontents;
6345 memset(trace, 0, sizeof(*trace));
6346 trace->fraction = 1;
6347 trace->realfraction = 1;
6348 trace->hitsupercontentsmask = hitsupercontentsmask;
6349 trace->startsupercontents = hitsupercontents;
6353 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6356 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6359 VectorSet(end, start[0], start[1], model->normalmins[2]);
6360 memset(&trace, 0, sizeof(trace));
6362 trace.realfraction = 1;
6363 trace.hitsupercontentsmask = 0;
6364 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6365 return trace.hitsupercontents;
6371 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6376 // find which leaf the point is in
6378 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6379 // point trace the brushes
6380 leaf = (mleaf_t *)node;
6381 for (i = 0;i < leaf->numleafbrushes;i++)
6383 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6384 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6386 brush->markframe = markframe;
6387 Collision_TracePointBrushFloat(trace, point, brush);
6390 // can't do point traces on curves (they have no thickness)
6393 static void Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace_t *trace, dp_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)
6395 int i, startside, endside;
6396 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6398 msurface_t *surface;
6401 // walk the tree until we hit a leaf, recursing for any split cases
6405 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6407 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6408 node = node->children[1];
6410 // abort if this part of the bsp tree can not be hit by this trace
6411 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6413 plane = node->plane;
6414 // axial planes are much more common than non-axial, so an optimized
6415 // axial case pays off here
6416 if (plane->type < 3)
6418 dist1 = start[plane->type] - plane->dist;
6419 dist2 = end[plane->type] - plane->dist;
6423 dist1 = DotProduct(start, plane->normal) - plane->dist;
6424 dist2 = DotProduct(end, plane->normal) - plane->dist;
6426 startside = dist1 < 0;
6427 endside = dist2 < 0;
6428 if (startside == endside)
6430 // most of the time the line fragment is on one side of the plane
6431 node = node->children[startside];
6435 // line crosses node plane, split the line
6436 dist1 = PlaneDiff(linestart, plane);
6437 dist2 = PlaneDiff(lineend, plane);
6438 midfrac = dist1 / (dist1 - dist2);
6439 VectorLerp(linestart, midfrac, lineend, mid);
6440 // take the near side first
6441 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6442 // if we found an impact on the front side, don't waste time
6443 // exploring the far side
6444 if (midfrac <= trace->realfraction)
6445 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6450 // abort if this part of the bsp tree can not be hit by this trace
6451 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6454 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6455 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6456 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6457 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6458 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6459 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6460 // line trace the brushes
6461 leaf = (mleaf_t *)node;
6463 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6466 for (i = 0;i < leaf->numleafbrushes;i++)
6468 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6469 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6471 brush->markframe = markframe;
6472 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6475 // can't do point traces on curves (they have no thickness)
6476 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6478 // line trace the curves
6479 for (i = 0;i < leaf->numleafsurfaces;i++)
6481 surface = model->data_surfaces + leaf->firstleafsurface[i];
6482 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6484 surface->deprecatedq3collisionmarkframe = markframe;
6485 Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6491 static void Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace_t *trace, dp_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)
6497 msurface_t *surface;
6499 float nodesegmentmins[3], nodesegmentmaxs[3];
6500 // walk the tree until we hit a leaf, recursing for any split cases
6504 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6506 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6507 node = node->children[1];
6509 // abort if this part of the bsp tree can not be hit by this trace
6510 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6512 plane = node->plane;
6513 // axial planes are much more common than non-axial, so an optimized
6514 // axial case pays off here
6515 if (plane->type < 3)
6517 // this is an axial plane, compare bounding box directly to it and
6518 // recurse sides accordingly
6519 // recurse down node sides
6520 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6521 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6522 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6523 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6527 // this is a non-axial plane, so check if the start and end boxes
6528 // are both on one side of the plane to handle 'diagonal' cases
6529 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6533 // segment crosses plane
6534 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6537 // if sides == 0 then the trace itself is bogus (Not A Number values),
6538 // in this case we simply pretend the trace hit nothing
6540 return; // ERROR: NAN bounding box!
6541 // take whichever side the segment box is on
6542 node = node->children[sides - 1];
6545 // abort if this part of the bsp tree can not be hit by this trace
6546 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6548 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6549 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6550 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6551 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6552 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6553 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6555 leaf = (mleaf_t *)node;
6557 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6560 for (i = 0;i < leaf->numleafbrushes;i++)
6562 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6563 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6565 brush->markframe = markframe;
6566 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6569 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6571 for (i = 0;i < leaf->numleafsurfaces;i++)
6573 surface = model->data_surfaces + leaf->firstleafsurface[i];
6574 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6576 surface->deprecatedq3collisionmarkframe = markframe;
6577 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6584 static int markframe = 0;
6586 static void Mod_Q3BSP_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
6590 memset(trace, 0, sizeof(*trace));
6591 trace->fraction = 1;
6592 trace->realfraction = 1;
6593 trace->hitsupercontentsmask = hitsupercontentsmask;
6594 if (mod_collision_bih.integer)
6595 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6596 else if (model->brush.submodel)
6598 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6599 if (brush->colbrushf)
6600 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6603 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6606 static void Mod_Q3BSP_TraceLine(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
6609 float segmentmins[3], segmentmaxs[3];
6610 msurface_t *surface;
6613 if (VectorCompare(start, end))
6615 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6619 memset(trace, 0, sizeof(*trace));
6620 trace->fraction = 1;
6621 trace->realfraction = 1;
6622 trace->hitsupercontentsmask = hitsupercontentsmask;
6623 segmentmins[0] = min(start[0], end[0]) - 1;
6624 segmentmins[1] = min(start[1], end[1]) - 1;
6625 segmentmins[2] = min(start[2], end[2]) - 1;
6626 segmentmaxs[0] = max(start[0], end[0]) + 1;
6627 segmentmaxs[1] = max(start[1], end[1]) + 1;
6628 segmentmaxs[2] = max(start[2], end[2]) + 1;
6629 if (mod_collision_bih.integer)
6630 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6631 else if (model->brush.submodel)
6633 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6634 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6635 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6636 if (mod_q3bsp_curves_collisions.integer)
6637 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6638 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6639 Collision_TraceLineTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6642 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6645 void Mod_Q3BSP_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *start, colbrushf_t *end, int hitsupercontentsmask)
6647 float segmentmins[3], segmentmaxs[3];
6649 msurface_t *surface;
6652 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6654 if (VectorCompare(start->mins, end->mins))
6655 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6657 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6661 // box trace, performed as brush trace
6662 memset(trace, 0, sizeof(*trace));
6663 trace->fraction = 1;
6664 trace->realfraction = 1;
6665 trace->hitsupercontentsmask = hitsupercontentsmask;
6666 segmentmins[0] = min(start->mins[0], end->mins[0]);
6667 segmentmins[1] = min(start->mins[1], end->mins[1]);
6668 segmentmins[2] = min(start->mins[2], end->mins[2]);
6669 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6670 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6671 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6672 if (mod_collision_bih.integer)
6673 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6674 else if (model->brush.submodel)
6676 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6677 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6678 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6679 if (mod_q3bsp_curves_collisions.integer)
6680 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6681 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6682 Collision_TraceBrushTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6685 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6688 static void Mod_Q3BSP_TraceBox(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
6690 colboxbrushf_t thisbrush_start, thisbrush_end;
6691 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6693 // box trace, performed as brush trace
6694 VectorAdd(start, boxmins, boxstartmins);
6695 VectorAdd(start, boxmaxs, boxstartmaxs);
6696 VectorAdd(end, boxmins, boxendmins);
6697 VectorAdd(end, boxmaxs, boxendmaxs);
6698 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6699 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6700 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6703 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6706 int supercontents = 0;
6708 if (mod_collision_bih.integer)
6711 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6712 supercontents = trace.startsupercontents;
6714 // test if the point is inside each brush
6715 else if (model->brush.submodel)
6717 // submodels are effectively one leaf
6718 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6719 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6720 supercontents |= brush->colbrushf->supercontents;
6724 mnode_t *node = model->brush.data_nodes;
6726 // find which leaf the point is in
6728 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6729 leaf = (mleaf_t *)node;
6730 // now check the brushes in the leaf
6731 for (i = 0;i < leaf->numleafbrushes;i++)
6733 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6734 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6735 supercontents |= brush->colbrushf->supercontents;
6738 return supercontents;
6741 void Mod_CollisionBIH_TraceLineAgainstSurfaces(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
6743 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
6747 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6755 int nummodelbrushes = model->nummodelbrushes;
6756 int nummodelsurfaces = model->nummodelsurfaces;
6758 const int *collisionelement3i;
6759 const float *collisionvertex3f;
6760 const int *renderelement3i;
6761 const float *rendervertex3f;
6762 bih_leaf_t *bihleafs;
6763 bih_node_t *bihnodes;
6765 int *temp_leafsortscratch;
6766 const msurface_t *surface;
6767 const q3mbrush_t *brush;
6769 // find out how many BIH leaf nodes we need
6771 if (userendersurfaces)
6773 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6774 bihnumleafs += surface->num_triangles;
6778 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6779 if (brush->colbrushf)
6781 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6783 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6784 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
6786 bihnumleafs += surface->num_collisiontriangles;
6793 // allocate the memory for the BIH leaf nodes
6794 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6796 // now populate the BIH leaf nodes
6799 // add render surfaces
6800 renderelement3i = model->surfmesh.data_element3i;
6801 rendervertex3f = model->surfmesh.data_vertex3f;
6802 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6804 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6806 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6808 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6809 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6810 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6811 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6812 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6813 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6814 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6815 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6816 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6817 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6822 if (!userendersurfaces)
6824 // add collision brushes
6825 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6827 if (!brush->colbrushf)
6829 bihleafs[bihleafindex].type = BIH_BRUSH;
6830 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6831 bihleafs[bihleafindex].surfaceindex = -1;
6832 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6833 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6834 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6838 // add collision surfaces
6839 collisionelement3i = model->brush.data_collisionelement3i;
6840 collisionvertex3f = model->brush.data_collisionvertex3f;
6841 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6843 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6845 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
6846 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6847 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6848 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6849 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6850 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6851 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6852 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6853 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6854 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6860 // allocate buffers for the produced and temporary data
6861 bihmaxnodes = bihnumleafs + 1;
6862 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6863 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6864 temp_leafsortscratch = temp_leafsort + bihnumleafs;
6867 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6869 // we're done with the temporary data
6870 Mem_Free(temp_leafsort);
6872 // resize the BIH nodes array if it over-allocated
6873 if (out->maxnodes > out->numnodes)
6875 out->maxnodes = out->numnodes;
6876 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
6882 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6884 int supercontents = 0;
6885 if (nativecontents & CONTENTSQ3_SOLID)
6886 supercontents |= SUPERCONTENTS_SOLID;
6887 if (nativecontents & CONTENTSQ3_WATER)
6888 supercontents |= SUPERCONTENTS_WATER;
6889 if (nativecontents & CONTENTSQ3_SLIME)
6890 supercontents |= SUPERCONTENTS_SLIME;
6891 if (nativecontents & CONTENTSQ3_LAVA)
6892 supercontents |= SUPERCONTENTS_LAVA;
6893 if (nativecontents & CONTENTSQ3_BODY)
6894 supercontents |= SUPERCONTENTS_BODY;
6895 if (nativecontents & CONTENTSQ3_CORPSE)
6896 supercontents |= SUPERCONTENTS_CORPSE;
6897 if (nativecontents & CONTENTSQ3_NODROP)
6898 supercontents |= SUPERCONTENTS_NODROP;
6899 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6900 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6901 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6902 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6903 if (nativecontents & CONTENTSQ3_DONOTENTER)
6904 supercontents |= SUPERCONTENTS_DONOTENTER;
6905 if (nativecontents & CONTENTSQ3_BOTCLIP)
6906 supercontents |= SUPERCONTENTS_BOTCLIP;
6907 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6908 supercontents |= SUPERCONTENTS_OPAQUE;
6909 return supercontents;
6912 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6914 int nativecontents = 0;
6915 if (supercontents & SUPERCONTENTS_SOLID)
6916 nativecontents |= CONTENTSQ3_SOLID;
6917 if (supercontents & SUPERCONTENTS_WATER)
6918 nativecontents |= CONTENTSQ3_WATER;
6919 if (supercontents & SUPERCONTENTS_SLIME)
6920 nativecontents |= CONTENTSQ3_SLIME;
6921 if (supercontents & SUPERCONTENTS_LAVA)
6922 nativecontents |= CONTENTSQ3_LAVA;
6923 if (supercontents & SUPERCONTENTS_BODY)
6924 nativecontents |= CONTENTSQ3_BODY;
6925 if (supercontents & SUPERCONTENTS_CORPSE)
6926 nativecontents |= CONTENTSQ3_CORPSE;
6927 if (supercontents & SUPERCONTENTS_NODROP)
6928 nativecontents |= CONTENTSQ3_NODROP;
6929 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6930 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6931 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6932 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6933 if (supercontents & SUPERCONTENTS_DONOTENTER)
6934 nativecontents |= CONTENTSQ3_DONOTENTER;
6935 if (supercontents & SUPERCONTENTS_BOTCLIP)
6936 nativecontents |= CONTENTSQ3_BOTCLIP;
6937 if (!(supercontents & SUPERCONTENTS_OPAQUE))
6938 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6939 return nativecontents;
6942 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6947 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6948 node = node->children[1];
6950 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6951 if (loadmodel->brush.num_leafs < numleafs)
6952 loadmodel->brush.num_leafs = numleafs;
6955 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6958 q3dheader_t *header;
6959 float corner[3], yawradius, modelradius;
6961 mod->modeldatatypestring = "Q3BSP";
6963 mod->type = mod_brushq3;
6964 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6967 header = (q3dheader_t *)buffer;
6968 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6969 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6971 i = LittleLong(header->version);
6972 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
6973 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
6975 mod->soundfromcenter = true;
6976 mod->TraceBox = Mod_Q3BSP_TraceBox;
6977 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
6978 mod->TraceLine = Mod_Q3BSP_TraceLine;
6979 mod->TracePoint = Mod_Q3BSP_TracePoint;
6980 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
6981 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
6982 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
6983 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
6984 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
6985 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
6986 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
6987 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
6988 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
6989 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
6990 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
6991 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
6992 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
6993 mod->brush.AmbientSoundLevelsForPoint = NULL;
6994 mod->brush.RoundUpToHullSize = NULL;
6995 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
6996 mod->Draw = R_Q1BSP_Draw;
6997 mod->DrawDepth = R_Q1BSP_DrawDepth;
6998 mod->DrawDebug = R_Q1BSP_DrawDebug;
6999 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7000 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7001 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7002 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7003 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7004 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7005 mod->DrawLight = R_Q1BSP_DrawLight;
7007 mod_base = (unsigned char *)header;
7009 // swap all the lumps
7010 header->ident = LittleLong(header->ident);
7011 header->version = LittleLong(header->version);
7012 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7013 for (i = 0;i < lumps;i++)
7015 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7016 if((char *) bufferend < (char *) buffer + j)
7017 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7018 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7019 if((char *) bufferend < (char *) buffer + j)
7020 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7023 * NO, do NOT clear them!
7024 * they contain actual data referenced by other stuff.
7025 * Instead, before using the advertisements lump, check header->versio
7027 * Sorry, but otherwise it breaks memory of the first lump.
7028 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7030 header->lumps[i].fileofs = 0;
7031 header->lumps[i].filelen = 0;
7035 mod->brush.qw_md4sum = 0;
7036 mod->brush.qw_md4sum2 = 0;
7037 for (i = 0;i < lumps;i++)
7039 if (i == Q3LUMP_ENTITIES)
7041 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7042 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7044 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7046 // all this checksumming can take a while, so let's send keepalives here too
7047 CL_KeepaliveMessage(false);
7050 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7051 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7052 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7053 if (header->version == Q3BSPVERSION_IG)
7054 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7056 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7057 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7058 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7059 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7060 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7061 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7062 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7063 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7064 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7065 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7066 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7067 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7068 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7069 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7070 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7072 // the MakePortals code works fine on the q3bsp data as well
7073 if (mod_bsp_portalize.integer)
7074 Mod_Q1BSP_MakePortals();
7076 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7077 loadmodel->brush.supportwateralpha = true;
7079 // make a single combined shadow mesh to allow optimized shadow volume creation
7080 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7082 loadmodel->brush.num_leafs = 0;
7083 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7085 if (loadmodel->brush.numsubmodels)
7086 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7089 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7094 // duplicate the basic information
7095 dpsnprintf(name, sizeof(name), "*%i", i);
7096 mod = Mod_FindName(name, loadmodel->name);
7097 // copy the base model to this one
7099 // rename the clone back to its proper name
7100 strlcpy(mod->name, name, sizeof(mod->name));
7101 mod->brush.parentmodel = loadmodel;
7102 // textures and memory belong to the main model
7103 mod->texturepool = NULL;
7104 mod->mempool = NULL;
7105 mod->brush.GetPVS = NULL;
7106 mod->brush.FatPVS = NULL;
7107 mod->brush.BoxTouchingPVS = NULL;
7108 mod->brush.BoxTouchingLeafPVS = NULL;
7109 mod->brush.BoxTouchingVisibleLeafs = NULL;
7110 mod->brush.FindBoxClusters = NULL;
7111 mod->brush.LightPoint = NULL;
7112 mod->brush.AmbientSoundLevelsForPoint = NULL;
7114 mod->brush.submodel = i;
7115 if (loadmodel->brush.submodels)
7116 loadmodel->brush.submodels[i] = mod;
7118 // make the model surface list (used by shadowing/lighting)
7119 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7120 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7121 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7122 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7123 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7124 Mod_MakeSortedSurfaces(mod);
7126 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7127 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7128 // enlarge the bounding box to enclose all geometry of this model,
7129 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7130 // which can in turn mess up the farclip (as well as culling when
7131 // outside the level - an unimportant concern)
7133 //printf("Editing model %d... BEFORE re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
7134 for (j = 0;j < mod->nummodelsurfaces;j++)
7136 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7137 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7139 if (!surface->num_vertices)
7141 for (k = 0;k < surface->num_vertices;k++, v += 3)
7143 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7144 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7145 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7146 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7147 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7148 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7151 //printf("Editing model %d... AFTER re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
7152 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7153 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7154 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7155 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7156 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7157 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7158 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7159 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7160 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7161 mod->yawmins[2] = mod->normalmins[2];
7162 mod->yawmaxs[2] = mod->normalmaxs[2];
7163 mod->radius = modelradius;
7164 mod->radius2 = modelradius * modelradius;
7166 // this gets altered below if sky or water is used
7167 mod->DrawSky = NULL;
7168 mod->DrawAddWaterPlanes = NULL;
7170 for (j = 0;j < mod->nummodelsurfaces;j++)
7171 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7173 if (j < mod->nummodelsurfaces)
7174 mod->DrawSky = R_Q1BSP_DrawSky;
7176 for (j = 0;j < mod->nummodelsurfaces;j++)
7177 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7179 if (j < mod->nummodelsurfaces)
7180 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7182 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7183 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7185 // generate VBOs and other shared data before cloning submodels
7190 Con_DPrintf("Stats for q3bsp model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
7193 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7195 int i = LittleLong(((int *)buffer)[1]);
7196 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7197 Mod_Q3BSP_Load(mod,buffer, bufferend);
7198 else if (i == Q2BSPVERSION)
7199 Mod_Q2BSP_Load(mod,buffer, bufferend);
7201 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7204 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7206 Host_Error("Mod_MAP_Load: not yet implemented");
7209 typedef struct objvertex_s
7220 static unsigned char nobsp_pvs[1] = {1};
7222 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7224 const char *textbase = (char *)buffer, *text = textbase;
7228 char materialname[MAX_QPATH];
7229 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7230 int index1, index2, index3;
7231 objvertex_t vfirst, vprev, vcurrent;
7234 int numtriangles = 0;
7235 int maxtriangles = 0;
7236 objvertex_t *vertices = NULL;
7238 int maxtextures = 0, numtextures = 0, textureindex = 0;
7239 int maxv = 0, numv = 1;
7240 int maxvt = 0, numvt = 1;
7241 int maxvn = 0, numvn = 1;
7242 char *texturenames = NULL;
7243 float dist, modelradius, modelyawradius, yawradius;
7250 objvertex_t *thisvertex = NULL;
7251 int vertexhashindex;
7252 int *vertexhashtable = NULL;
7253 objvertex_t *vertexhashdata = NULL;
7254 objvertex_t *vdata = NULL;
7255 int vertexhashsize = 0;
7256 int vertexhashcount = 0;
7257 skinfile_t *skinfiles = NULL;
7258 unsigned char *data = NULL;
7259 int *submodelfirstsurface;
7260 msurface_t *surface;
7261 msurface_t *tempsurfaces;
7263 memset(&vfirst, 0, sizeof(vfirst));
7264 memset(&vprev, 0, sizeof(vprev));
7265 memset(&vcurrent, 0, sizeof(vcurrent));
7267 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7269 loadmodel->modeldatatypestring = "OBJ";
7271 loadmodel->type = mod_obj;
7272 loadmodel->soundfromcenter = true;
7273 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7274 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7275 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7276 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7277 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7278 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7279 loadmodel->brush.TraceLineOfSight = NULL;
7280 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7281 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7282 loadmodel->brush.GetPVS = NULL;
7283 loadmodel->brush.FatPVS = NULL;
7284 loadmodel->brush.BoxTouchingPVS = NULL;
7285 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7286 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7287 loadmodel->brush.FindBoxClusters = NULL;
7288 loadmodel->brush.LightPoint = NULL;
7289 loadmodel->brush.FindNonSolidLocation = NULL;
7290 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7291 loadmodel->brush.RoundUpToHullSize = NULL;
7292 loadmodel->brush.PointInLeaf = NULL;
7293 loadmodel->Draw = R_Q1BSP_Draw;
7294 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7295 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7296 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7297 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7298 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7299 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7300 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7301 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7302 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7304 skinfiles = Mod_LoadSkinFiles();
7305 if (loadmodel->numskins < 1)
7306 loadmodel->numskins = 1;
7308 // make skinscenes for the skins (no groups)
7309 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7310 for (i = 0;i < loadmodel->numskins;i++)
7312 loadmodel->skinscenes[i].firstframe = i;
7313 loadmodel->skinscenes[i].framecount = 1;
7314 loadmodel->skinscenes[i].loop = true;
7315 loadmodel->skinscenes[i].framerate = 10;
7321 // we always have model 0, i.e. the first "submodel"
7322 loadmodel->brush.numsubmodels = 1;
7324 // parse the OBJ text now
7327 static char emptyarg[1] = "";
7332 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7333 line[linelen] = text[linelen];
7335 for (argc = 0;argc < 4;argc++)
7336 argv[argc] = emptyarg;
7339 while (*s == ' ' || *s == '\t')
7349 while (*s == ' ' || *s == '\t')
7359 if (argv[0][0] == '#')
7361 if (!strcmp(argv[0], "v"))
7365 maxv = max(maxv * 2, 1024);
7366 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7368 v[numv*3+0] = atof(argv[1]);
7369 v[numv*3+2] = atof(argv[2]);
7370 v[numv*3+1] = atof(argv[3]);
7373 else if (!strcmp(argv[0], "vt"))
7377 maxvt = max(maxvt * 2, 1024);
7378 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7380 vt[numvt*2+0] = atof(argv[1]);
7381 vt[numvt*2+1] = 1-atof(argv[2]);
7384 else if (!strcmp(argv[0], "vn"))
7388 maxvn = max(maxvn * 2, 1024);
7389 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7391 vn[numvn*3+0] = atof(argv[1]);
7392 vn[numvn*3+2] = atof(argv[2]);
7393 vn[numvn*3+1] = atof(argv[3]);
7396 else if (!strcmp(argv[0], "f"))
7400 if (maxtextures <= numtextures)
7402 maxtextures = max(maxtextures * 2, 256);
7403 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7405 textureindex = numtextures++;
7406 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7408 for (j = 1;j < argc;j++)
7410 index1 = atoi(argv[j]);
7411 while(argv[j][0] && argv[j][0] != '/')
7415 index2 = atoi(argv[j]);
7416 while(argv[j][0] && argv[j][0] != '/')
7420 index3 = atoi(argv[j]);
7421 // negative refers to a recent vertex
7422 // zero means not specified
7423 // positive means an absolute vertex index
7425 index1 = numv - index1;
7427 index2 = numvt - index2;
7429 index3 = numvn - index3;
7430 vcurrent.nextindex = -1;
7431 vcurrent.textureindex = textureindex;
7432 vcurrent.submodelindex = submodelindex;
7433 if (v && index1 >= 0 && index1 < numv)
7434 VectorCopy(v + 3*index1, vcurrent.v);
7435 if (vt && index2 >= 0 && index2 < numvt)
7436 Vector2Copy(vt + 2*index2, vcurrent.vt);
7437 if (vn && index3 >= 0 && index3 < numvn)
7438 VectorCopy(vn + 3*index3, vcurrent.vn);
7439 if (numtriangles == 0)
7441 VectorCopy(vcurrent.v, mins);
7442 VectorCopy(vcurrent.v, maxs);
7446 mins[0] = min(mins[0], vcurrent.v[0]);
7447 mins[1] = min(mins[1], vcurrent.v[1]);
7448 mins[2] = min(mins[2], vcurrent.v[2]);
7449 maxs[0] = max(maxs[0], vcurrent.v[0]);
7450 maxs[1] = max(maxs[1], vcurrent.v[1]);
7451 maxs[2] = max(maxs[2], vcurrent.v[2]);
7457 if (maxtriangles <= numtriangles)
7459 maxtriangles = max(maxtriangles * 2, 32768);
7460 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7462 vertices[numtriangles*3+0] = vfirst;
7463 vertices[numtriangles*3+1] = vprev;
7464 vertices[numtriangles*3+2] = vcurrent;
7470 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7472 submodelindex = atof(argv[1]);
7473 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7475 else if (!strcmp(argv[0], "usemtl"))
7477 for (i = 0;i < numtextures;i++)
7478 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7480 if (i < numtextures)
7484 if (maxtextures <= numtextures)
7486 maxtextures = max(maxtextures * 2, 256);
7487 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7489 textureindex = numtextures++;
7490 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7495 // now that we have the OBJ data loaded as-is, we can convert it
7497 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7498 VectorCopy(mins, loadmodel->normalmins);
7499 VectorCopy(maxs, loadmodel->normalmaxs);
7500 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7501 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7502 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7503 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7504 modelradius = modelyawradius + modelradius * modelradius;
7505 modelyawradius = sqrt(modelyawradius);
7506 modelradius = sqrt(modelradius);
7507 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7508 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7509 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7510 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7511 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7512 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7513 loadmodel->radius = modelradius;
7514 loadmodel->radius2 = modelradius * modelradius;
7516 // allocate storage for triangles
7517 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7518 // allocate vertex hash structures to build an optimal vertex subset
7519 vertexhashsize = numtriangles*2;
7520 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7521 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7522 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7523 vertexhashcount = 0;
7525 // gather surface stats for assigning vertex/triangle ranges
7529 loadmodel->num_surfaces = 0;
7530 // allocate storage for the worst case number of surfaces, later we resize
7531 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7532 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7533 surface = tempsurfaces;
7534 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7536 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7537 for (textureindex = 0;textureindex < numtextures;textureindex++)
7539 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7541 thisvertex = vertices + vertexindex;
7542 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7545 // skip the surface creation if there are no triangles for it
7546 if (vertexindex == numtriangles*3)
7548 // create a surface for these vertices
7549 surfacevertices = 0;
7550 surfaceelements = 0;
7551 // we hack in a texture index in the surface to be fixed up later...
7552 surface->texture = (texture_t *)((size_t)textureindex);
7553 // calculate bounds as we go
7554 VectorCopy(thisvertex->v, surface->mins);
7555 VectorCopy(thisvertex->v, surface->maxs);
7556 for (;vertexindex < numtriangles*3;vertexindex++)
7558 thisvertex = vertices + vertexindex;
7559 if (thisvertex->submodelindex != submodelindex)
7561 if (thisvertex->textureindex != textureindex)
7563 // add vertex to surface bounds
7564 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7565 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7566 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7567 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7568 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7569 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7570 // add the vertex if it is not found in the merged set, and
7571 // get its index (triangle element) for the surface
7572 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7573 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7575 vdata = vertexhashdata + i;
7576 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7581 i = vertexhashcount++;
7582 vdata = vertexhashdata + i;
7583 *vdata = *thisvertex;
7584 vdata->nextindex = vertexhashtable[vertexhashindex];
7585 vertexhashtable[vertexhashindex] = i;
7588 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7591 surfacetriangles = surfaceelements / 3;
7592 surface->num_vertices = surfacevertices;
7593 surface->num_triangles = surfacetriangles;
7594 surface->num_firstvertex = firstvertex;
7595 surface->num_firsttriangle = firsttriangle;
7596 firstvertex += surface->num_vertices;
7597 firsttriangle += surface->num_triangles;
7599 loadmodel->num_surfaces++;
7602 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7603 numvertices = firstvertex;
7604 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7605 tempsurfaces = NULL;
7607 // allocate storage for final mesh data
7608 loadmodel->num_textures = numtextures * loadmodel->numskins;
7609 loadmodel->num_texturesperskin = numtextures;
7610 data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0) + (r_enableshadowvolumes.integer ? numtriangles * sizeof(int[3]) : 0) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7611 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7612 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7613 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7614 loadmodel->surfmesh.num_vertices = numvertices;
7615 loadmodel->surfmesh.num_triangles = numtriangles;
7616 if (r_enableshadowvolumes.integer)
7617 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7618 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7619 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7620 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7621 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7622 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7623 if (loadmodel->surfmesh.num_vertices <= 65536)
7624 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7626 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7628 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7629 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7630 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7633 // load the textures
7634 for (textureindex = 0;textureindex < numtextures;textureindex++)
7635 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7636 Mod_FreeSkinFiles(skinfiles);
7638 // set the surface textures to their real values now that we loaded them...
7639 for (i = 0;i < loadmodel->num_surfaces;i++)
7640 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7644 Mem_Free(texturenames);
7648 Mem_Free(vertexhashtable);
7649 Mem_Free(vertexhashdata);
7651 // make a single combined shadow mesh to allow optimized shadow volume creation
7652 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7654 // compute all the mesh information that was not loaded from the file
7655 if (loadmodel->surfmesh.data_element3s)
7656 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7657 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7658 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7659 // generate normals if the file did not have them
7660 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7661 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
7662 Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
7663 if (loadmodel->surfmesh.data_neighbor3i)
7664 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7666 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7667 loadmodel->brush.num_visleafs = 1;
7668 loadmodel->brush.num_leafs = 1;
7669 loadmodel->brush.num_nodes = 0;
7670 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7671 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7672 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7673 loadmodel->brush.num_pvsclusters = 1;
7674 loadmodel->brush.num_pvsclusterbytes = 1;
7675 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7676 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7677 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7678 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7679 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7680 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7681 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7682 loadmodel->brush.data_leafs->clusterindex = 0;
7683 loadmodel->brush.data_leafs->areaindex = 0;
7684 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7685 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7686 loadmodel->brush.data_leafs->numleafbrushes = 0;
7687 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7688 loadmodel->brush.supportwateralpha = true;
7690 if (loadmodel->brush.numsubmodels)
7691 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7694 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7699 // duplicate the basic information
7700 dpsnprintf(name, sizeof(name), "*%i", i);
7701 mod = Mod_FindName(name, loadmodel->name);
7702 // copy the base model to this one
7704 // rename the clone back to its proper name
7705 strlcpy(mod->name, name, sizeof(mod->name));
7706 mod->brush.parentmodel = loadmodel;
7707 // textures and memory belong to the main model
7708 mod->texturepool = NULL;
7709 mod->mempool = NULL;
7710 mod->brush.GetPVS = NULL;
7711 mod->brush.FatPVS = NULL;
7712 mod->brush.BoxTouchingPVS = NULL;
7713 mod->brush.BoxTouchingLeafPVS = NULL;
7714 mod->brush.BoxTouchingVisibleLeafs = NULL;
7715 mod->brush.FindBoxClusters = NULL;
7716 mod->brush.LightPoint = NULL;
7717 mod->brush.AmbientSoundLevelsForPoint = NULL;
7719 mod->brush.submodel = i;
7720 if (loadmodel->brush.submodels)
7721 loadmodel->brush.submodels[i] = mod;
7723 // make the model surface list (used by shadowing/lighting)
7724 mod->firstmodelsurface = submodelfirstsurface[i];
7725 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7726 mod->firstmodelbrush = 0;
7727 mod->nummodelbrushes = 0;
7728 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
7729 Mod_MakeSortedSurfaces(mod);
7731 VectorClear(mod->normalmins);
7732 VectorClear(mod->normalmaxs);
7734 for (j = 0;j < mod->nummodelsurfaces;j++)
7736 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7737 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7739 if (!surface->num_vertices)
7744 VectorCopy(v, mod->normalmins);
7745 VectorCopy(v, mod->normalmaxs);
7747 for (k = 0;k < surface->num_vertices;k++, v += 3)
7749 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7750 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7751 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7752 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7753 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7754 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7757 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7758 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7759 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7760 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7761 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7762 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7763 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7764 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7765 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7766 mod->yawmins[2] = mod->normalmins[2];
7767 mod->yawmaxs[2] = mod->normalmaxs[2];
7768 mod->radius = modelradius;
7769 mod->radius2 = modelradius * modelradius;
7771 // this gets altered below if sky or water is used
7772 mod->DrawSky = NULL;
7773 mod->DrawAddWaterPlanes = NULL;
7775 for (j = 0;j < mod->nummodelsurfaces;j++)
7776 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7778 if (j < mod->nummodelsurfaces)
7779 mod->DrawSky = R_Q1BSP_DrawSky;
7781 for (j = 0;j < mod->nummodelsurfaces;j++)
7782 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7784 if (j < mod->nummodelsurfaces)
7785 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7787 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
7788 mod->render_bih = mod->collision_bih;
7790 // generate VBOs and other shared data before cloning submodels
7795 Mem_Free(submodelfirstsurface);
7797 Con_DPrintf("Stats for obj model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
7800 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
7802 // we already have done PVS culling at this point...
7803 // so we don't need to do it again.
7806 vec3_t testorigin, mins, maxs;
7808 testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
7809 testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
7810 testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
7812 if(model->brush.TraceLineOfSight(model, eye, testorigin))
7815 // expand the box a little
7816 mins[0] = (t+1) * minsX[0] - t * maxsX[0];
7817 maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
7818 mins[1] = (t+1) * minsX[1] - t * maxsX[1];
7819 maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
7820 mins[2] = (t+1) * minsX[2] - t * maxsX[2];
7821 maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
7823 for(i = 0; i != numsamples; ++i)
7825 testorigin[0] = lhrandom(mins[0], maxs[0]);
7826 testorigin[1] = lhrandom(mins[1], maxs[1]);
7827 testorigin[2] = lhrandom(mins[2], maxs[2]);
7829 if(model->brush.TraceLineOfSight(model, eye, testorigin))