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_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
53 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
54 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
55 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
56 cvar_t mod_q3shader_force_addalpha = {0, "mod_q3shader_force_addalpha", "0", "treat GL_ONE GL_ONE (or add) blendfunc as GL_SRC_ALPHA GL_ONE for compatibility with older DarkPlaces releases"};
57 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)"};
58 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"};
59 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"};
60 extern cvar_t vid_sRGB;
61 extern cvar_t vid_sRGB_fallback;
63 static texture_t mod_q1bsp_texture_solid;
64 static texture_t mod_q1bsp_texture_sky;
65 static texture_t mod_q1bsp_texture_lava;
66 static texture_t mod_q1bsp_texture_slime;
67 static texture_t mod_q1bsp_texture_water;
69 void Mod_BrushInit(void)
71 // Cvar_RegisterVariable(&r_subdivide_size);
72 Cvar_RegisterVariable(&mod_bsp_portalize);
73 Cvar_RegisterVariable(&r_novis);
74 Cvar_RegisterVariable(&r_nosurftextures);
75 Cvar_RegisterVariable(&r_subdivisions_tolerance);
76 Cvar_RegisterVariable(&r_subdivisions_mintess);
77 Cvar_RegisterVariable(&r_subdivisions_maxtess);
78 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
79 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
80 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
81 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
82 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
83 Cvar_RegisterVariable(&r_trippy);
84 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
85 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
86 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
87 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
88 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
89 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
90 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
91 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
92 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
93 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
94 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
95 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
96 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
97 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
98 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
99 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
100 Cvar_RegisterVariable(&mod_collision_bih);
101 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
103 // these games were made for older DP engines and are no longer
104 // maintained; use this hack to show their textures properly
105 if(gamemode == GAME_NEXUIZ)
106 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
108 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
109 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
110 mod_q1bsp_texture_solid.surfaceflags = 0;
111 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
113 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
114 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
115 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
116 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
118 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
119 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
120 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
121 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
123 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
124 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
125 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
126 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
128 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
129 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
130 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
131 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
134 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
141 // LordHavoc: modified to start at first clip node,
142 // in other words: first node of the (sub)model
143 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
145 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
147 return (mleaf_t *)node;
150 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
154 leaf = Mod_Q1BSP_PointInLeaf(model, p);
157 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
160 memcpy(out, leaf->ambient_sound_level, i);
166 memset(out, 0, outsize);
169 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
172 int nodestackindex = 0;
173 mnode_t *node, *nodestack[1024];
174 if (!model->brush.num_pvsclusters)
176 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
182 // node - recurse down the BSP tree
183 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
187 return -1; // ERROR: NAN bounding box!
188 // box is on one side of plane, take that path
189 node = node->children[sides-1];
193 // box crosses plane, take one path and remember the other
194 if (nodestackindex < 1024)
195 nodestack[nodestackindex++] = node->children[0];
196 node = node->children[1];
202 // leaf - add clusterindex to list
203 if (numclusters < maxclusters)
204 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
208 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
212 if (nodestackindex < 1024)
213 nodestack[nodestackindex++] = node->children[0];
214 node = node->children[1];
219 // leaf - add clusterindex to list
220 if (numclusters < maxclusters)
221 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
226 // try another path we didn't take earlier
227 if (nodestackindex == 0)
229 node = nodestack[--nodestackindex];
231 // return number of clusters found (even if more than the maxclusters)
235 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
237 int nodestackindex = 0;
238 mnode_t *node, *nodestack[1024];
239 if (!model->brush.num_pvsclusters)
241 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
247 // node - recurse down the BSP tree
248 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
252 return -1; // ERROR: NAN bounding box!
253 // box is on one side of plane, take that path
254 node = node->children[sides-1];
258 // box crosses plane, take one path and remember the other
259 if (nodestackindex < 1024)
260 nodestack[nodestackindex++] = node->children[0];
261 node = node->children[1];
267 // leaf - check cluster bit
268 int clusterindex = ((mleaf_t *)node)->clusterindex;
269 if (CHECKPVSBIT(pvs, clusterindex))
271 // it is visible, return immediately with the news
276 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
280 if (nodestackindex < 1024)
281 nodestack[nodestackindex++] = node->children[0];
282 node = node->children[1];
287 // leaf - check cluster bit
288 int clusterindex = ((mleaf_t *)node)->clusterindex;
289 if (CHECKPVSBIT(pvs, clusterindex))
291 // it is visible, return immediately with the news
297 // nothing to see here, try another path we didn't take earlier
298 if (nodestackindex == 0)
300 node = nodestack[--nodestackindex];
306 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
308 int nodestackindex = 0;
309 mnode_t *node, *nodestack[1024];
310 if (!model->brush.num_leafs)
312 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
318 // node - recurse down the BSP tree
319 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
323 return -1; // ERROR: NAN bounding box!
324 // box is on one side of plane, take that path
325 node = node->children[sides-1];
329 // box crosses plane, take one path and remember the other
330 if (nodestackindex < 1024)
331 nodestack[nodestackindex++] = node->children[0];
332 node = node->children[1];
338 // leaf - check cluster bit
339 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
340 if (CHECKPVSBIT(pvs, clusterindex))
342 // it is visible, return immediately with the news
347 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
351 if (nodestackindex < 1024)
352 nodestack[nodestackindex++] = node->children[0];
353 node = node->children[1];
358 // leaf - check cluster bit
359 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
360 if (CHECKPVSBIT(pvs, clusterindex))
362 // it is visible, return immediately with the news
368 // nothing to see here, try another path we didn't take earlier
369 if (nodestackindex == 0)
371 node = nodestack[--nodestackindex];
377 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
379 int nodestackindex = 0;
380 mnode_t *node, *nodestack[1024];
381 if (!model->brush.num_leafs)
383 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
389 // node - recurse down the BSP tree
390 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
394 return -1; // ERROR: NAN bounding box!
395 // box is on one side of plane, take that path
396 node = node->children[sides-1];
400 // box crosses plane, take one path and remember the other
401 if (nodestackindex < 1024)
402 nodestack[nodestackindex++] = node->children[0];
403 node = node->children[1];
409 // leaf - check if it is visible
410 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
412 // it is visible, return immediately with the news
417 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
421 if (nodestackindex < 1024)
422 nodestack[nodestackindex++] = node->children[0];
423 node = node->children[1];
428 // leaf - check if it is visible
429 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
431 // it is visible, return immediately with the news
437 // nothing to see here, try another path we didn't take earlier
438 if (nodestackindex == 0)
440 node = nodestack[--nodestackindex];
446 typedef struct findnonsolidlocationinfo_s
449 vec3_t absmin, absmax;
455 findnonsolidlocationinfo_t;
457 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
460 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
462 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
463 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
464 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
465 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
466 VectorSubtract(vert[1], vert[0], edge[0]);
467 VectorSubtract(vert[2], vert[1], edge[1]);
468 CrossProduct(edge[1], edge[0], facenormal);
469 if (facenormal[0] || facenormal[1] || facenormal[2])
471 VectorNormalize(facenormal);
472 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
473 if (f <= info->bestdist && f >= -info->bestdist)
475 VectorSubtract(vert[0], vert[2], edge[2]);
476 VectorNormalize(edge[0]);
477 VectorNormalize(edge[1]);
478 VectorNormalize(edge[2]);
479 CrossProduct(facenormal, edge[0], edgenormal[0]);
480 CrossProduct(facenormal, edge[1], edgenormal[1]);
481 CrossProduct(facenormal, edge[2], edgenormal[2]);
483 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
484 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
485 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
487 // we got lucky, the center is within the face
488 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
492 if (info->bestdist > dist)
494 info->bestdist = dist;
495 VectorScale(facenormal, (info->radius - -dist), info->nudge);
500 if (info->bestdist > dist)
502 info->bestdist = dist;
503 VectorScale(facenormal, (info->radius - dist), info->nudge);
509 // check which edge or vertex the center is nearest
510 for (i = 0;i < 3;i++)
512 f = DotProduct(info->center, edge[i]);
513 if (f >= DotProduct(vert[0], edge[i])
514 && f <= DotProduct(vert[1], edge[i]))
517 VectorMA(info->center, -f, edge[i], point);
518 dist = sqrt(DotProduct(point, point));
519 if (info->bestdist > dist)
521 info->bestdist = dist;
522 VectorScale(point, (info->radius / dist), info->nudge);
524 // skip both vertex checks
525 // (both are further away than this edge)
530 // not on edge, check first vertex of edge
531 VectorSubtract(info->center, vert[i], point);
532 dist = sqrt(DotProduct(point, point));
533 if (info->bestdist > dist)
535 info->bestdist = dist;
536 VectorScale(point, (info->radius / dist), info->nudge);
545 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
547 int surfacenum, k, *mark;
549 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
551 surface = info->model->data_surfaces + *mark;
552 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
554 if(surface->deprecatedq3num_bboxstride > 0)
557 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
558 for(i = 0; i < cnt; ++i)
560 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
562 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
564 tri = i * surface->deprecatedq3num_bboxstride + k;
565 if(tri >= surface->num_triangles)
567 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
574 for (k = 0;k < surface->num_triangles;k++)
576 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
583 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
587 float f = PlaneDiff(info->center, node->plane);
588 if (f >= -info->bestdist)
589 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
590 if (f <= info->bestdist)
591 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
595 if (((mleaf_t *)node)->numleafsurfaces)
596 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
600 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
603 findnonsolidlocationinfo_t info;
609 VectorCopy(in, info.center);
610 info.radius = radius;
615 VectorClear(info.nudge);
616 info.bestdist = radius;
617 VectorCopy(info.center, info.absmin);
618 VectorCopy(info.center, info.absmax);
619 info.absmin[0] -= info.radius + 1;
620 info.absmin[1] -= info.radius + 1;
621 info.absmin[2] -= info.radius + 1;
622 info.absmax[0] += info.radius + 1;
623 info.absmax[1] += info.radius + 1;
624 info.absmax[2] += info.radius + 1;
625 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
626 VectorAdd(info.center, info.nudge, info.center);
628 while (info.bestdist < radius && ++i < 10);
629 VectorCopy(info.center, out);
632 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
634 switch(nativecontents)
639 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
641 return SUPERCONTENTS_WATER;
643 return SUPERCONTENTS_SLIME;
645 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
647 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
652 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
654 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
655 return CONTENTS_SOLID;
656 if (supercontents & SUPERCONTENTS_SKY)
658 if (supercontents & SUPERCONTENTS_LAVA)
659 return CONTENTS_LAVA;
660 if (supercontents & SUPERCONTENTS_SLIME)
661 return CONTENTS_SLIME;
662 if (supercontents & SUPERCONTENTS_WATER)
663 return CONTENTS_WATER;
664 return CONTENTS_EMPTY;
667 typedef struct RecursiveHullCheckTraceInfo_s
669 // the hull we're tracing through
672 // the trace structure to fill in
675 // start, end, and end - start (in model space)
680 RecursiveHullCheckTraceInfo_t;
682 // 1/32 epsilon to keep floating point happy
683 #define DIST_EPSILON (0.03125)
685 #define HULLCHECKSTATE_EMPTY 0
686 #define HULLCHECKSTATE_SOLID 1
687 #define HULLCHECKSTATE_DONE 2
689 extern cvar_t collision_prefernudgedfraction;
690 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
692 // status variables, these don't need to be saved on the stack when
693 // recursing... but are because this should be thread-safe
694 // (note: tracing against a bbox is not thread-safe, yet)
699 // variables that need to be stored on the stack when recursing
704 // LordHavoc: a goto! everyone flee in terror... :)
709 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
710 if (!t->trace->startfound)
712 t->trace->startfound = true;
713 t->trace->startsupercontents |= num;
715 if (num & SUPERCONTENTS_LIQUIDSMASK)
716 t->trace->inwater = true;
718 t->trace->inopen = true;
719 if (num & SUPERCONTENTS_SOLID)
720 t->trace->hittexture = &mod_q1bsp_texture_solid;
721 else if (num & SUPERCONTENTS_SKY)
722 t->trace->hittexture = &mod_q1bsp_texture_sky;
723 else if (num & SUPERCONTENTS_LAVA)
724 t->trace->hittexture = &mod_q1bsp_texture_lava;
725 else if (num & SUPERCONTENTS_SLIME)
726 t->trace->hittexture = &mod_q1bsp_texture_slime;
728 t->trace->hittexture = &mod_q1bsp_texture_water;
729 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
730 t->trace->hitsupercontents = num;
731 if (num & t->trace->hitsupercontentsmask)
733 // if the first leaf is solid, set startsolid
734 if (t->trace->allsolid)
735 t->trace->startsolid = true;
736 #if COLLISIONPARANOID >= 3
739 return HULLCHECKSTATE_SOLID;
743 t->trace->allsolid = false;
744 #if COLLISIONPARANOID >= 3
747 return HULLCHECKSTATE_EMPTY;
751 // find the point distances
752 node = t->hull->clipnodes + num;
754 plane = t->hull->planes + node->planenum;
757 t1 = p1[plane->type] - plane->dist;
758 t2 = p2[plane->type] - plane->dist;
762 t1 = DotProduct (plane->normal, p1) - plane->dist;
763 t2 = DotProduct (plane->normal, p2) - plane->dist;
770 #if COLLISIONPARANOID >= 3
773 num = node->children[1];
782 #if COLLISIONPARANOID >= 3
785 num = node->children[0];
791 // the line intersects, find intersection point
792 // LordHavoc: this uses the original trace for maximum accuracy
793 #if COLLISIONPARANOID >= 3
798 t1 = t->start[plane->type] - plane->dist;
799 t2 = t->end[plane->type] - plane->dist;
803 t1 = DotProduct (plane->normal, t->start) - plane->dist;
804 t2 = DotProduct (plane->normal, t->end) - plane->dist;
807 midf = t1 / (t1 - t2);
808 midf = bound(p1f, midf, p2f);
809 VectorMA(t->start, midf, t->dist, mid);
811 // recurse both sides, front side first
812 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
813 // if this side is not empty, return what it is (solid or done)
814 if (ret != HULLCHECKSTATE_EMPTY)
817 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
818 // if other side is not solid, return what it is (empty or done)
819 if (ret != HULLCHECKSTATE_SOLID)
822 // front is air and back is solid, this is the impact point...
825 t->trace->plane.dist = -plane->dist;
826 VectorNegate (plane->normal, t->trace->plane.normal);
830 t->trace->plane.dist = plane->dist;
831 VectorCopy (plane->normal, t->trace->plane.normal);
834 // calculate the true fraction
835 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
836 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
837 midf = t1 / (t1 - t2);
838 t->trace->realfraction = bound(0, midf, 1);
840 // calculate the return fraction which is nudged off the surface a bit
841 midf = (t1 - DIST_EPSILON) / (t1 - t2);
842 t->trace->fraction = bound(0, midf, 1);
844 if (collision_prefernudgedfraction.integer)
845 t->trace->realfraction = t->trace->fraction;
847 #if COLLISIONPARANOID >= 3
850 return HULLCHECKSTATE_DONE;
853 //#if COLLISIONPARANOID < 2
854 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
857 mclipnode_t *nodes = t->hull->clipnodes;
858 mplane_t *planes = t->hull->planes;
860 VectorCopy(t->start, point);
863 plane = planes + nodes[num].planenum;
864 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
866 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
867 t->trace->startsupercontents |= num;
868 if (num & SUPERCONTENTS_LIQUIDSMASK)
869 t->trace->inwater = true;
871 t->trace->inopen = true;
872 if (num & t->trace->hitsupercontentsmask)
874 t->trace->allsolid = t->trace->startsolid = true;
875 return HULLCHECKSTATE_SOLID;
879 t->trace->allsolid = t->trace->startsolid = false;
880 return HULLCHECKSTATE_EMPTY;
885 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)
887 RecursiveHullCheckTraceInfo_t rhc;
889 memset(&rhc, 0, sizeof(rhc));
890 memset(trace, 0, sizeof(trace_t));
892 rhc.trace->fraction = 1;
893 rhc.trace->realfraction = 1;
894 rhc.trace->allsolid = true;
895 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
896 VectorCopy(start, rhc.start);
897 VectorCopy(start, rhc.end);
898 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
901 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)
903 RecursiveHullCheckTraceInfo_t rhc;
905 if (VectorCompare(start, end))
907 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
911 memset(&rhc, 0, sizeof(rhc));
912 memset(trace, 0, sizeof(trace_t));
914 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
915 rhc.trace->fraction = 1;
916 rhc.trace->realfraction = 1;
917 rhc.trace->allsolid = true;
918 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
919 VectorCopy(start, rhc.start);
920 VectorCopy(end, rhc.end);
921 VectorSubtract(rhc.end, rhc.start, rhc.dist);
922 #if COLLISIONPARANOID >= 2
923 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]);
924 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
929 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
930 memset(&testtrace, 0, sizeof(trace_t));
931 rhc.trace = &testtrace;
932 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
933 rhc.trace->fraction = 1;
934 rhc.trace->realfraction = 1;
935 rhc.trace->allsolid = true;
936 VectorCopy(test, rhc.start);
937 VectorCopy(test, rhc.end);
938 VectorClear(rhc.dist);
939 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
940 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
941 if (!trace->startsolid && testtrace.startsolid)
942 Con_Printf(" - ended in solid!\n");
946 if (VectorLength2(rhc.dist))
947 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
949 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
953 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)
955 // this function currently only supports same size start and end
957 RecursiveHullCheckTraceInfo_t rhc;
959 if (VectorCompare(boxmins, boxmaxs))
961 if (VectorCompare(start, end))
962 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
964 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
968 memset(&rhc, 0, sizeof(rhc));
969 memset(trace, 0, sizeof(trace_t));
971 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
972 rhc.trace->fraction = 1;
973 rhc.trace->realfraction = 1;
974 rhc.trace->allsolid = true;
975 VectorSubtract(boxmaxs, boxmins, boxsize);
977 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
978 else if (model->brush.ishlbsp)
980 // LordHavoc: this has to have a minor tolerance (the .1) because of
981 // minor float precision errors from the box being transformed around
982 if (boxsize[0] < 32.1)
984 if (boxsize[2] < 54) // pick the nearest of 36 or 72
985 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
987 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
990 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
994 // LordHavoc: this has to have a minor tolerance (the .1) because of
995 // minor float precision errors from the box being transformed around
996 if (boxsize[0] < 32.1)
997 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
999 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1001 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1002 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1003 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1004 #if COLLISIONPARANOID >= 2
1005 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]);
1006 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1011 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1012 memset(&testtrace, 0, sizeof(trace_t));
1013 rhc.trace = &testtrace;
1014 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1015 rhc.trace->fraction = 1;
1016 rhc.trace->realfraction = 1;
1017 rhc.trace->allsolid = true;
1018 VectorCopy(test, rhc.start);
1019 VectorCopy(test, rhc.end);
1020 VectorClear(rhc.dist);
1021 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1022 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1023 if (!trace->startsolid && testtrace.startsolid)
1024 Con_Printf(" - ended in solid!\n");
1028 if (VectorLength2(rhc.dist))
1029 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1031 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1035 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1037 int num = model->brushq1.hulls[0].firstclipnode;
1039 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1040 mplane_t *planes = model->brushq1.hulls[0].planes;
1043 plane = planes + nodes[num].planenum;
1044 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1046 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1049 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)
1053 colplanef_t cbox_planes[6];
1055 cbox.hasaabbplanes = true;
1056 cbox.supercontents = boxsupercontents;
1059 cbox.numtriangles = 0;
1060 cbox.planes = cbox_planes;
1062 cbox.elements = NULL;
1070 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];
1071 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];
1072 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];
1073 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];
1074 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];
1075 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];
1076 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1077 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1078 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1079 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1080 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1081 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1082 memset(trace, 0, sizeof(trace_t));
1083 trace->hitsupercontentsmask = hitsupercontentsmask;
1084 trace->fraction = 1;
1085 trace->realfraction = 1;
1086 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1088 RecursiveHullCheckTraceInfo_t rhc;
1089 static hull_t box_hull;
1090 static mclipnode_t box_clipnodes[6];
1091 static mplane_t box_planes[6];
1092 // fill in a default trace
1093 memset(&rhc, 0, sizeof(rhc));
1094 memset(trace, 0, sizeof(trace_t));
1095 //To keep everything totally uniform, bounding boxes are turned into small
1096 //BSP trees instead of being compared directly.
1097 // create a temp hull from bounding box sizes
1098 box_planes[0].dist = cmaxs[0] - mins[0];
1099 box_planes[1].dist = cmins[0] - maxs[0];
1100 box_planes[2].dist = cmaxs[1] - mins[1];
1101 box_planes[3].dist = cmins[1] - maxs[1];
1102 box_planes[4].dist = cmaxs[2] - mins[2];
1103 box_planes[5].dist = cmins[2] - maxs[2];
1104 #if COLLISIONPARANOID >= 3
1105 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]);
1108 if (box_hull.clipnodes == NULL)
1112 //Set up the planes and clipnodes so that the six floats of a bounding box
1113 //can just be stored out and get a proper hull_t structure.
1115 box_hull.clipnodes = box_clipnodes;
1116 box_hull.planes = box_planes;
1117 box_hull.firstclipnode = 0;
1118 box_hull.lastclipnode = 5;
1120 for (i = 0;i < 6;i++)
1122 box_clipnodes[i].planenum = i;
1126 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1128 box_clipnodes[i].children[side^1] = i + 1;
1130 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1132 box_planes[i].type = i>>1;
1133 box_planes[i].normal[i>>1] = 1;
1137 // trace a line through the generated clipping hull
1138 //rhc.boxsupercontents = boxsupercontents;
1139 rhc.hull = &box_hull;
1141 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1142 rhc.trace->fraction = 1;
1143 rhc.trace->realfraction = 1;
1144 rhc.trace->allsolid = true;
1145 VectorCopy(start, rhc.start);
1146 VectorCopy(end, rhc.end);
1147 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1148 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1149 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1150 if (rhc.trace->startsupercontents)
1151 rhc.trace->startsupercontents = boxsupercontents;
1155 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)
1157 memset(trace, 0, sizeof(trace_t));
1158 trace->fraction = 1;
1159 trace->realfraction = 1;
1160 if (BoxesOverlap(start, start, cmins, cmaxs))
1162 trace->startsupercontents |= boxsupercontents;
1163 if (hitsupercontentsmask & boxsupercontents)
1165 trace->startsolid = true;
1166 trace->allsolid = true;
1171 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1174 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1175 return trace.fraction == 1;
1178 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)
1182 float mid, distz = endz - startz;
1186 return false; // didn't hit anything
1188 switch (node->plane->type)
1191 node = node->children[x < node->plane->dist];
1194 node = node->children[y < node->plane->dist];
1197 side = startz < node->plane->dist;
1198 if ((endz < node->plane->dist) == side)
1200 node = node->children[side];
1203 // found an intersection
1204 mid = node->plane->dist;
1207 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1208 front += startz * node->plane->normal[2];
1209 back += endz * node->plane->normal[2];
1210 side = front < node->plane->dist;
1211 if ((back < node->plane->dist) == side)
1213 node = node->children[side];
1216 // found an intersection
1217 mid = startz + distz * (front - node->plane->dist) / (front - back);
1221 // go down front side
1222 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1223 return true; // hit something
1226 // check for impact on this node
1227 if (node->numsurfaces)
1229 int i, dsi, dti, lmwidth, lmheight;
1231 msurface_t *surface;
1232 unsigned char *lightmap;
1233 int maps, line3, size3;
1236 float scale, w, w00, w01, w10, w11;
1238 surface = model->data_surfaces + node->firstsurface;
1239 for (i = 0;i < node->numsurfaces;i++, surface++)
1241 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1242 continue; // no lightmaps
1244 // location we want to sample in the lightmap
1245 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;
1246 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;
1251 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1252 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1255 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1257 // calculate bilinear interpolation factors
1258 // and also multiply by fixedpoint conversion factors
1261 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1262 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1263 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1264 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1266 // values for pointer math
1267 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1268 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1270 // look up the pixel
1271 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1273 // bilinear filter each lightmap style, and sum them
1274 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1276 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1277 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1278 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1279 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1280 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1284 return true; // success
1289 // go down back side
1290 node = node->children[side ^ 1];
1292 distz = endz - startz;
1297 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1299 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1300 VectorSet(diffusenormal, 0, 0, 1);
1302 if (!model->brushq1.lightdata)
1304 VectorSet(ambientcolor, 1, 1, 1);
1305 VectorSet(diffusecolor, 0, 0, 0);
1309 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);
1312 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1317 const msurface_t *surface;
1322 float edgenormal[3];
1329 surface = model->data_surfaces + node->firstsurface;
1330 for (i = 0;i < node->numsurfaces;i++, surface++)
1332 // skip surfaces whose bounding box does not include the point
1333 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1335 // skip faces with contents we don't care about
1336 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1338 // get the surface normal - since it is flat we know any vertex normal will suffice
1339 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1341 if (DotProduct(t->dist, normal) > 0)
1343 // iterate edges and see if the point is outside one of them
1344 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1346 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1347 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1348 VectorSubtract(v0, v1, edgedir);
1349 CrossProduct(edgedir, normal, edgenormal);
1350 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1353 // if the point is outside one of the edges, it is not within the surface
1354 if (j < surface->num_vertices)
1357 // we hit a surface, this is the impact point...
1358 VectorCopy(normal, t->trace->plane.normal);
1359 t->trace->plane.dist = DotProduct(normal, p);
1361 // calculate the true fraction
1362 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1363 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1364 midf = t1 / (t1 - t2);
1365 t->trace->realfraction = midf;
1367 // calculate the return fraction which is nudged off the surface a bit
1368 midf = (t1 - DIST_EPSILON) / (t1 - t2);
1369 t->trace->fraction = bound(0, midf, 1);
1371 if (collision_prefernudgedfraction.integer)
1372 t->trace->realfraction = t->trace->fraction;
1374 t->trace->hittexture = surface->texture->currentframe;
1375 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1376 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1377 return surface->texture->currentframe;
1382 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])
1384 const mplane_t *plane;
1387 double midf, mid[3];
1388 const mleaf_t *leaf;
1392 plane = node->plane;
1393 if (plane->type < 3)
1395 t1 = p1[plane->type] - plane->dist;
1396 t2 = p2[plane->type] - plane->dist;
1400 t1 = DotProduct (plane->normal, p1) - plane->dist;
1401 t2 = DotProduct (plane->normal, p2) - plane->dist;
1407 node = node->children[1];
1416 node = node->children[0];
1422 // the line intersects, find intersection point
1423 // LordHavoc: this uses the original trace for maximum accuracy
1424 if (plane->type < 3)
1426 t1 = t->start[plane->type] - plane->dist;
1427 t2 = t->end[plane->type] - plane->dist;
1431 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1432 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1435 midf = t1 / (t1 - t2);
1436 VectorMA(t->start, midf, t->dist, mid);
1438 // recurse both sides, front side first, return if we hit a surface
1439 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1440 return HULLCHECKSTATE_DONE;
1442 // test each surface on the node
1443 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1444 if (t->trace->hittexture)
1445 return HULLCHECKSTATE_DONE;
1447 // recurse back side
1448 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1450 leaf = (const mleaf_t *)node;
1451 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1452 if (!t->trace->startfound)
1454 t->trace->startfound = true;
1455 t->trace->startsupercontents |= side;
1457 if (side & SUPERCONTENTS_LIQUIDSMASK)
1458 t->trace->inwater = true;
1460 t->trace->inopen = true;
1461 if (side & t->trace->hitsupercontentsmask)
1463 // if the first leaf is solid, set startsolid
1464 if (t->trace->allsolid)
1465 t->trace->startsolid = true;
1466 return HULLCHECKSTATE_SOLID;
1470 t->trace->allsolid = false;
1471 return HULLCHECKSTATE_EMPTY;
1475 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)
1477 RecursiveHullCheckTraceInfo_t rhc;
1479 memset(&rhc, 0, sizeof(rhc));
1480 memset(trace, 0, sizeof(trace_t));
1482 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1483 rhc.trace->fraction = 1;
1484 rhc.trace->realfraction = 1;
1485 rhc.trace->allsolid = true;
1486 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1487 VectorCopy(start, rhc.start);
1488 VectorCopy(end, rhc.end);
1489 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1490 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1491 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1494 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1497 unsigned char *outstart = out;
1498 while (out < outend)
1502 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));
1512 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));
1515 for (c = *in++;c > 0;c--)
1519 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));
1530 R_Q1BSP_LoadSplitSky
1532 A sky texture is 256*128, with the right side being a masked overlay
1535 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1540 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1541 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1543 // allocate a texture pool if we need it
1544 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1545 loadmodel->texturepool = R_AllocTexturePool();
1547 if (bytesperpixel == 4)
1549 for (y = 0;y < h;y++)
1551 for (x = 0;x < w;x++)
1553 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1554 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1560 // make an average value for the back to avoid
1561 // a fringe on the top level
1570 for (y = 0;y < h;y++)
1572 for (x = 0;x < w;x++)
1574 p = src[x*width+y+w];
1575 r += palette_rgb[p][0];
1576 g += palette_rgb[p][1];
1577 b += palette_rgb[p][2];
1580 bgra.b[2] = r/(w*h);
1581 bgra.b[1] = g/(w*h);
1582 bgra.b[0] = b/(w*h);
1584 for (y = 0;y < h;y++)
1586 for (x = 0;x < w;x++)
1588 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1590 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1595 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1596 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1597 Mem_Free(solidpixels);
1598 Mem_Free(alphapixels);
1601 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1603 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1604 skinframe_t *skinframe;
1606 texture_t *tx, *tx2, *anims[10], *altanims[10];
1607 texture_t backuptex;
1609 unsigned char *data, *mtdata;
1611 char mapname[MAX_QPATH], name[MAX_QPATH];
1612 unsigned char zeroopaque[4], zerotrans[4];
1613 Vector4Set(zeroopaque, 0, 0, 0, 255);
1614 Vector4Set(zerotrans, 0, 0, 0, 128);
1616 loadmodel->data_textures = NULL;
1618 // add two slots for notexture walls and notexture liquids
1621 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1622 m->nummiptex = LittleLong (m->nummiptex);
1623 loadmodel->num_textures = m->nummiptex + 2;
1624 loadmodel->num_texturesperskin = loadmodel->num_textures;
1629 loadmodel->num_textures = 2;
1630 loadmodel->num_texturesperskin = loadmodel->num_textures;
1633 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1635 // fill out all slots with notexture
1636 if (cls.state != ca_dedicated)
1637 skinframe = R_SkinFrame_LoadMissing();
1640 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1642 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1645 if (cls.state != ca_dedicated)
1647 tx->numskinframes = 1;
1648 tx->skinframerate = 1;
1649 tx->skinframes[0] = skinframe;
1650 tx->currentskinframe = tx->skinframes[0];
1652 tx->basematerialflags = MATERIALFLAG_WALL;
1653 if (i == loadmodel->num_textures - 1)
1655 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1656 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1657 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1661 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1662 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1664 tx->currentframe = tx;
1666 // clear water settings
1669 tx->refractfactor = 1;
1670 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1671 tx->reflectfactor = 1;
1672 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1673 tx->r_water_wateralpha = 1;
1674 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1675 tx->offsetscale = 1;
1677 tx->specularscalemod = 1;
1678 tx->specularpowermod = 1;
1683 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1687 s = loadmodel->name;
1688 if (!strncasecmp(s, "maps/", 5))
1690 FS_StripExtension(s, mapname, sizeof(mapname));
1692 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1694 // LordHavoc: mostly rewritten map texture loader
1695 for (i = 0;i < m->nummiptex;i++)
1697 dofs[i] = LittleLong(dofs[i]);
1698 if (r_nosurftextures.integer)
1702 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1705 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1707 // copy name, but only up to 16 characters
1708 // (the output buffer can hold more than this, but the input buffer is
1710 for (j = 0;j < 16 && dmiptex->name[j];j++)
1711 name[j] = dmiptex->name[j];
1716 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1717 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1720 mtwidth = LittleLong(dmiptex->width);
1721 mtheight = LittleLong(dmiptex->height);
1723 j = LittleLong(dmiptex->offsets[0]);
1727 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1729 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1732 mtdata = (unsigned char *)dmiptex + j;
1735 if ((mtwidth & 15) || (mtheight & 15))
1736 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1738 // LordHavoc: force all names to lowercase
1739 for (j = 0;name[j];j++)
1740 if (name[j] >= 'A' && name[j] <= 'Z')
1741 name[j] += 'a' - 'A';
1743 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1744 backuptex = loadmodel->data_textures[i];
1745 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1747 loadmodel->data_textures[i] = backuptex;
1749 tx = loadmodel->data_textures + i;
1750 strlcpy(tx->name, name, sizeof(tx->name));
1751 tx->width = mtwidth;
1752 tx->height = mtheight;
1754 if (tx->name[0] == '*')
1756 if (!strncmp(tx->name, "*lava", 5))
1758 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1759 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1761 else if (!strncmp(tx->name, "*slime", 6))
1763 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1764 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1768 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1769 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1772 else if (!strncmp(tx->name, "sky", 3))
1774 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1775 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1779 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1780 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1783 if (cls.state != ca_dedicated)
1785 // LordHavoc: HL sky textures are entirely different than quake
1786 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1788 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1790 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), false, false, false, NULL);
1791 if (data && image_width == image_height * 2)
1793 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1796 else if (mtdata != NULL)
1797 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1801 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);
1803 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);
1805 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1808 // did not find external texture, load it from the bsp or wad3
1809 if (loadmodel->brush.ishlbsp)
1811 // internal texture overrides wad
1812 unsigned char *pixels, *freepixels;
1813 pixels = freepixels = NULL;
1815 pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1817 pixels = freepixels = W_GetTextureBGRA(tx->name);
1820 tx->width = image_width;
1821 tx->height = image_height;
1822 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1825 Mem_Free(freepixels);
1827 else if (mtdata) // texture included
1828 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1830 // if skinframe is still NULL the "missing" texture will be used
1832 tx->skinframes[0] = skinframe;
1834 // LordHavoc: some Tenebrae textures get replaced by black
1835 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1836 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1837 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1838 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1841 tx->basematerialflags = MATERIALFLAG_WALL;
1842 if (tx->name[0] == '*')
1844 // LordHavoc: some turbulent textures should not be affected by wateralpha
1845 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1846 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1847 else if (!strncmp(tx->name,"*lava",5)
1848 || !strncmp(tx->name,"*teleport",9)
1849 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1850 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1852 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1853 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1854 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1856 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1858 // replace the texture with black
1859 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1861 else if (!strncmp(tx->name, "sky", 3))
1862 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1863 else if (!strcmp(tx->name, "caulk"))
1864 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1865 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1866 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1868 // start out with no animation
1869 tx->currentframe = tx;
1870 tx->currentskinframe = tx->skinframes[0];
1871 tx->currentmaterialflags = tx->basematerialflags;
1874 // sequence the animations
1875 for (i = 0;i < m->nummiptex;i++)
1877 tx = loadmodel->data_textures + i;
1878 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1880 if (tx->anim_total[0] || tx->anim_total[1])
1881 continue; // already sequenced
1883 // find the number of frames in the animation
1884 memset(anims, 0, sizeof(anims));
1885 memset(altanims, 0, sizeof(altanims));
1887 for (j = i;j < m->nummiptex;j++)
1889 tx2 = loadmodel->data_textures + j;
1890 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1894 if (num >= '0' && num <= '9')
1895 anims[num - '0'] = tx2;
1896 else if (num >= 'a' && num <= 'j')
1897 altanims[num - 'a'] = tx2;
1899 Con_Printf("Bad animating texture %s\n", tx->name);
1903 for (j = 0;j < 10;j++)
1910 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1913 for (j = 0;j < max;j++)
1917 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1921 for (j = 0;j < altmax;j++)
1925 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1934 // if there is no alternate animation, duplicate the primary
1935 // animation into the alternate
1937 for (k = 0;k < 10;k++)
1938 altanims[k] = anims[k];
1941 // link together the primary animation
1942 for (j = 0;j < max;j++)
1945 tx2->animated = true;
1946 tx2->anim_total[0] = max;
1947 tx2->anim_total[1] = altmax;
1948 for (k = 0;k < 10;k++)
1950 tx2->anim_frames[0][k] = anims[k];
1951 tx2->anim_frames[1][k] = altanims[k];
1955 // if there really is an alternate anim...
1956 if (anims[0] != altanims[0])
1958 // link together the alternate animation
1959 for (j = 0;j < altmax;j++)
1962 tx2->animated = true;
1963 // the primary/alternate are reversed here
1964 tx2->anim_total[0] = altmax;
1965 tx2->anim_total[1] = max;
1966 for (k = 0;k < 10;k++)
1968 tx2->anim_frames[0][k] = altanims[k];
1969 tx2->anim_frames[1][k] = anims[k];
1976 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1979 unsigned char *in, *out, *data, d;
1980 char litfilename[MAX_QPATH];
1981 char dlitfilename[MAX_QPATH];
1982 fs_offset_t filesize;
1983 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1985 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1986 for (i=0; i<l->filelen; i++)
1987 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1989 else // LordHavoc: bsp version 29 (normal white lighting)
1991 // LordHavoc: hope is not lost yet, check for a .lit file to load
1992 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1993 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1994 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1995 strlcat (litfilename, ".lit", sizeof (litfilename));
1996 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1997 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2000 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2002 i = LittleLong(((int *)data)[1]);
2005 if (developer_loading.integer)
2006 Con_Printf("loaded %s\n", litfilename);
2007 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2008 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2010 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2013 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2015 i = LittleLong(((int *)data)[1]);
2018 if (developer_loading.integer)
2019 Con_Printf("loaded %s\n", dlitfilename);
2020 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2021 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2022 loadmodel->brushq3.deluxemapping_modelspace = false;
2023 loadmodel->brushq3.deluxemapping = true;
2032 Con_Printf("Unknown .lit file version (%d)\n", i);
2034 else if (filesize == 8)
2035 Con_Print("Empty .lit file, ignoring\n");
2037 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
2044 // LordHavoc: oh well, expand the white lighting data
2047 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
2048 in = mod_base + l->fileofs;
2049 out = loadmodel->brushq1.lightdata;
2050 for (i = 0;i < l->filelen;i++)
2060 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
2062 loadmodel->brushq1.num_compressedpvs = 0;
2063 loadmodel->brushq1.data_compressedpvs = NULL;
2066 loadmodel->brushq1.num_compressedpvs = l->filelen;
2067 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
2068 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
2071 // used only for HalfLife maps
2072 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2074 char key[128], value[4096];
2078 if (!COM_ParseToken_Simple(&data, false, false))
2080 if (com_token[0] != '{')
2084 if (!COM_ParseToken_Simple(&data, false, false))
2086 if (com_token[0] == '}')
2087 break; // end of worldspawn
2088 if (com_token[0] == '_')
2089 strlcpy(key, com_token + 1, sizeof(key));
2091 strlcpy(key, com_token, sizeof(key));
2092 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2093 key[strlen(key)-1] = 0;
2094 if (!COM_ParseToken_Simple(&data, false, false))
2096 dpsnprintf(value, sizeof(value), "%s", com_token);
2097 if (!strcmp("wad", key)) // for HalfLife maps
2099 if (loadmodel->brush.ishlbsp)
2102 for (i = 0;i < (int)sizeof(value);i++)
2103 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2107 for (;i < (int)sizeof(value);i++)
2109 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2110 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2112 else if (value[i] == ';' || value[i] == 0)
2116 W_LoadTextureWadFile(&value[j], false);
2128 static void Mod_Q1BSP_LoadEntities(lump_t *l)
2130 loadmodel->brush.entities = NULL;
2133 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
2134 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
2135 loadmodel->brush.entities[l->filelen] = 0;
2136 if (loadmodel->brush.ishlbsp)
2137 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2141 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
2147 in = (dvertex_t *)(mod_base + l->fileofs);
2148 if (l->filelen % sizeof(*in))
2149 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2150 count = l->filelen / sizeof(*in);
2151 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2153 loadmodel->brushq1.vertexes = out;
2154 loadmodel->brushq1.numvertexes = count;
2156 for ( i=0 ; i<count ; i++, in++, out++)
2158 out->position[0] = LittleFloat(in->point[0]);
2159 out->position[1] = LittleFloat(in->point[1]);
2160 out->position[2] = LittleFloat(in->point[2]);
2164 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
2165 // can be used for this
2167 int SB_ReadInt (unsigned char **buffer)
2170 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
2176 float SB_ReadFloat (unsigned char **buffer)
2184 u.i = SB_ReadInt (buffer);
2188 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
2190 unsigned char *index;
2194 index = (unsigned char *)(mod_base + l->fileofs);
2195 if (l->filelen % (48+4*hullinfo->filehulls))
2196 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2198 count = l->filelen / (48+4*hullinfo->filehulls);
2199 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2201 loadmodel->brushq1.submodels = out;
2202 loadmodel->brush.numsubmodels = count;
2204 for (i = 0; i < count; i++, out++)
2206 // spread out the mins / maxs by a pixel
2207 out->mins[0] = SB_ReadFloat (&index) - 1;
2208 out->mins[1] = SB_ReadFloat (&index) - 1;
2209 out->mins[2] = SB_ReadFloat (&index) - 1;
2210 out->maxs[0] = SB_ReadFloat (&index) + 1;
2211 out->maxs[1] = SB_ReadFloat (&index) + 1;
2212 out->maxs[2] = SB_ReadFloat (&index) + 1;
2213 out->origin[0] = SB_ReadFloat (&index);
2214 out->origin[1] = SB_ReadFloat (&index);
2215 out->origin[2] = SB_ReadFloat (&index);
2216 for (j = 0; j < hullinfo->filehulls; j++)
2217 out->headnode[j] = SB_ReadInt (&index);
2218 out->visleafs = SB_ReadInt (&index);
2219 out->firstface = SB_ReadInt (&index);
2220 out->numfaces = SB_ReadInt (&index);
2224 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2230 in = (dedge_t *)(mod_base + l->fileofs);
2231 if (l->filelen % sizeof(*in))
2232 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2233 count = l->filelen / sizeof(*in);
2234 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2236 loadmodel->brushq1.edges = out;
2237 loadmodel->brushq1.numedges = count;
2239 for ( i=0 ; i<count ; i++, in++, out++)
2241 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2242 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2243 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2245 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);
2246 if(!loadmodel->brushq1.numvertexes)
2247 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2255 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2259 int i, j, k, count, miptex;
2261 in = (texinfo_t *)(mod_base + l->fileofs);
2262 if (l->filelen % sizeof(*in))
2263 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2264 count = l->filelen / sizeof(*in);
2265 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2267 loadmodel->brushq1.texinfo = out;
2268 loadmodel->brushq1.numtexinfo = count;
2270 for (i = 0;i < count;i++, in++, out++)
2272 for (k = 0;k < 2;k++)
2273 for (j = 0;j < 4;j++)
2274 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2276 miptex = LittleLong(in->miptex);
2277 out->flags = LittleLong(in->flags);
2279 out->texture = NULL;
2280 if (loadmodel->data_textures)
2282 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2283 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2285 out->texture = loadmodel->data_textures + miptex;
2287 if (out->flags & TEX_SPECIAL)
2289 // if texture chosen is NULL or the shader needs a lightmap,
2290 // force to notexture water shader
2291 if (out->texture == NULL)
2292 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2296 // if texture chosen is NULL, force to notexture
2297 if (out->texture == NULL)
2298 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2304 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2309 mins[0] = mins[1] = mins[2] = 9999;
2310 maxs[0] = maxs[1] = maxs[2] = -9999;
2312 for (i = 0;i < numverts;i++)
2314 for (j = 0;j < 3;j++, v++)
2324 #define MAX_SUBDIVPOLYTRIANGLES 4096
2325 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2327 static int subdivpolyverts, subdivpolytriangles;
2328 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2329 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2331 static int subdivpolylookupvert(vec3_t v)
2334 for (i = 0;i < subdivpolyverts;i++)
2335 if (subdivpolyvert[i][0] == v[0]
2336 && subdivpolyvert[i][1] == v[1]
2337 && subdivpolyvert[i][2] == v[2])
2339 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2340 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2341 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2342 return subdivpolyverts++;
2345 static void SubdividePolygon(int numverts, float *verts)
2347 int i, i1, i2, i3, f, b, c, p;
2348 vec3_t mins, maxs, front[256], back[256];
2349 float m, *pv, *cv, dist[256], frac;
2352 Host_Error("SubdividePolygon: ran out of verts in buffer");
2354 BoundPoly(numverts, verts, mins, maxs);
2356 for (i = 0;i < 3;i++)
2358 m = (mins[i] + maxs[i]) * 0.5;
2359 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2360 if (maxs[i] - m < 8)
2362 if (m - mins[i] < 8)
2366 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2367 dist[c] = cv[i] - m;
2370 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2374 VectorCopy(pv, front[f]);
2379 VectorCopy(pv, back[b]);
2382 if (dist[p] == 0 || dist[c] == 0)
2384 if ((dist[p] > 0) != (dist[c] > 0) )
2387 frac = dist[p] / (dist[p] - dist[c]);
2388 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2389 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2390 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2396 SubdividePolygon(f, front[0]);
2397 SubdividePolygon(b, back[0]);
2401 i1 = subdivpolylookupvert(verts);
2402 i2 = subdivpolylookupvert(verts + 3);
2403 for (i = 2;i < numverts;i++)
2405 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2407 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2411 i3 = subdivpolylookupvert(verts + i * 3);
2412 subdivpolyindex[subdivpolytriangles][0] = i1;
2413 subdivpolyindex[subdivpolytriangles][1] = i2;
2414 subdivpolyindex[subdivpolytriangles][2] = i3;
2416 subdivpolytriangles++;
2420 //Breaks a polygon up along axial 64 unit
2421 //boundaries so that turbulent and sky warps
2422 //can be done reasonably.
2423 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2429 subdivpolytriangles = 0;
2430 subdivpolyverts = 0;
2431 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2432 if (subdivpolytriangles < 1)
2433 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2435 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2436 mesh->num_vertices = subdivpolyverts;
2437 mesh->num_triangles = subdivpolytriangles;
2438 mesh->vertex = (surfvertex_t *)(mesh + 1);
2439 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2440 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2442 for (i = 0;i < mesh->num_triangles;i++)
2443 for (j = 0;j < 3;j++)
2444 mesh->index[i*3+j] = subdivpolyindex[i][j];
2446 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2448 VectorCopy(subdivpolyvert[i], v->v);
2449 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2450 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2455 extern cvar_t gl_max_lightmapsize;
2456 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2459 msurface_t *surface;
2460 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2461 float texmins[2], texmaxs[2], val;
2462 rtexture_t *lightmaptexture, *deluxemaptexture;
2464 in = (dface_t *)(mod_base + l->fileofs);
2465 if (l->filelen % sizeof(*in))
2466 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2467 count = l->filelen / sizeof(*in);
2468 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2469 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2471 loadmodel->num_surfaces = count;
2473 loadmodel->brushq1.firstrender = true;
2474 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2478 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2480 numedges = (unsigned short)LittleShort(in->numedges);
2481 totalverts += numedges;
2482 totaltris += numedges - 2;
2485 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2487 lightmaptexture = NULL;
2488 deluxemaptexture = r_texture_blanknormalmap;
2490 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2491 totallightmapsamples = 0;
2495 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2497 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2499 // FIXME: validate edges, texinfo, etc?
2500 firstedge = LittleLong(in->firstedge);
2501 numedges = (unsigned short)LittleShort(in->numedges);
2502 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)
2503 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2504 i = (unsigned short)LittleShort(in->texinfo);
2505 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2506 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2507 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2508 surface->texture = surface->lightmapinfo->texinfo->texture;
2510 planenum = (unsigned short)LittleShort(in->planenum);
2511 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2512 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2514 //surface->flags = surface->texture->flags;
2515 //if (LittleShort(in->side))
2516 // surface->flags |= SURF_PLANEBACK;
2517 //surface->plane = loadmodel->brush.data_planes + planenum;
2519 surface->num_firstvertex = totalverts;
2520 surface->num_vertices = numedges;
2521 surface->num_firsttriangle = totaltris;
2522 surface->num_triangles = numedges - 2;
2523 totalverts += numedges;
2524 totaltris += numedges - 2;
2526 // convert edges back to a normal polygon
2527 for (i = 0;i < surface->num_vertices;i++)
2529 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2531 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2533 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2535 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2536 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2537 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2538 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2539 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2540 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2541 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2542 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2545 for (i = 0;i < surface->num_triangles;i++)
2547 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2548 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2549 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2552 // compile additional data about the surface geometry
2553 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);
2554 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);
2555 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2557 // generate surface extents information
2558 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2559 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2560 for (i = 1;i < surface->num_vertices;i++)
2562 for (j = 0;j < 2;j++)
2564 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2565 texmins[j] = min(texmins[j], val);
2566 texmaxs[j] = max(texmaxs[j], val);
2569 for (i = 0;i < 2;i++)
2571 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2572 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2575 smax = surface->lightmapinfo->extents[0] >> 4;
2576 tmax = surface->lightmapinfo->extents[1] >> 4;
2577 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2578 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2581 for (i = 0;i < MAXLIGHTMAPS;i++)
2582 surface->lightmapinfo->styles[i] = in->styles[i];
2583 surface->lightmaptexture = NULL;
2584 surface->deluxemaptexture = r_texture_blanknormalmap;
2585 i = LittleLong(in->lightofs);
2588 surface->lightmapinfo->samples = NULL;
2590 // give non-lightmapped water a 1x white lightmap
2591 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2593 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2594 surface->lightmapinfo->styles[0] = 0;
2595 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2599 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2600 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2601 else // LordHavoc: white lighting (bsp version 29)
2603 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2604 if (loadmodel->brushq1.nmaplightdata)
2605 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2608 // check if we should apply a lightmap to this
2609 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2611 if (ssize > 256 || tsize > 256)
2612 Host_Error("Bad surface extents");
2614 if (lightmapsize < ssize)
2615 lightmapsize = ssize;
2616 if (lightmapsize < tsize)
2617 lightmapsize = tsize;
2619 totallightmapsamples += ssize*tsize;
2621 // force lightmap upload on first time seeing the surface
2623 // additionally this is used by the later code to see if a
2624 // lightmap is needed on this surface (rather than duplicating the
2626 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2627 loadmodel->lit = true;
2631 // small maps (such as ammo boxes especially) don't need big lightmap
2632 // textures, so this code tries to guess a good size based on
2633 // totallightmapsamples (size of the lightmaps lump basically), as well as
2634 // trying to max out the size if there is a lot of lightmap data to store
2635 // additionally, never choose a lightmapsize that is smaller than the
2636 // largest surface encountered (as it would fail)
2638 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2641 // now that we've decided the lightmap texture size, we can do the rest
2642 if (cls.state != ca_dedicated)
2644 int stainmapsize = 0;
2645 mod_alloclightmap_state_t allocState;
2647 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2648 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2650 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2651 float u, v, ubase, vbase, uscale, vscale;
2653 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2656 smax = surface->lightmapinfo->extents[0] >> 4;
2657 tmax = surface->lightmapinfo->extents[1] >> 4;
2658 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2659 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2660 stainmapsize += ssize * tsize * 3;
2662 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2664 // allocate a texture pool if we need it
2665 if (loadmodel->texturepool == NULL)
2666 loadmodel->texturepool = R_AllocTexturePool();
2667 // could not find room, make a new lightmap
2668 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2669 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2670 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2671 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);
2672 if (loadmodel->brushq1.nmaplightdata)
2673 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);
2675 Mod_AllocLightmap_Reset(&allocState);
2676 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2678 surface->lightmaptexture = lightmaptexture;
2679 surface->deluxemaptexture = deluxemaptexture;
2680 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2681 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2683 uscale = 1.0f / (float)lightmapsize;
2684 vscale = 1.0f / (float)lightmapsize;
2685 ubase = lightmapx * uscale;
2686 vbase = lightmapy * vscale;
2688 for (i = 0;i < surface->num_vertices;i++)
2690 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);
2691 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);
2692 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2693 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2694 // LordHavoc: calc lightmap data offset for vertex lighting to use
2697 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2701 if (cl_stainmaps.integer)
2703 // allocate stainmaps for permanent marks on walls and clear white
2704 unsigned char *stainsamples = NULL;
2705 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2706 memset(stainsamples, 255, stainmapsize);
2708 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2710 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2712 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2713 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2714 surface->lightmapinfo->stainsamples = stainsamples;
2715 stainsamples += ssize * tsize * 3;
2720 // generate ushort elements array if possible
2721 if (loadmodel->surfmesh.data_element3s)
2722 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2723 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2726 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2729 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2730 node->parent = parent;
2733 // this is a node, recurse to children
2734 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2735 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2736 // combine supercontents of children
2737 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2742 mleaf_t *leaf = (mleaf_t *)node;
2743 // if this is a leaf, calculate supercontents mask from all collidable
2744 // primitives in the leaf (brushes and collision surfaces)
2745 // also flag if the leaf contains any collision surfaces
2746 leaf->combinedsupercontents = 0;
2747 // combine the supercontents values of all brushes in this leaf
2748 for (j = 0;j < leaf->numleafbrushes;j++)
2749 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2750 // check if this leaf contains any collision surfaces (q3 patches)
2751 for (j = 0;j < leaf->numleafsurfaces;j++)
2753 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2754 if (surface->num_collisiontriangles)
2756 leaf->containscollisionsurfaces = true;
2757 leaf->combinedsupercontents |= surface->texture->supercontents;
2763 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2769 in = (dnode_t *)(mod_base + l->fileofs);
2770 if (l->filelen % sizeof(*in))
2771 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2772 count = l->filelen / sizeof(*in);
2774 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2775 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2777 loadmodel->brush.data_nodes = out;
2778 loadmodel->brush.num_nodes = count;
2780 for ( i=0 ; i<count ; i++, in++, out++)
2782 for (j=0 ; j<3 ; j++)
2784 out->mins[j] = LittleShort(in->mins[j]);
2785 out->maxs[j] = LittleShort(in->maxs[j]);
2788 p = LittleLong(in->planenum);
2789 out->plane = loadmodel->brush.data_planes + p;
2791 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2792 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2794 for (j=0 ; j<2 ; j++)
2796 // LordHavoc: this code supports broken bsp files produced by
2797 // arguire qbsp which can produce more than 32768 nodes, any value
2798 // below count is assumed to be a node number, any other value is
2799 // assumed to be a leaf number
2800 p = (unsigned short)LittleShort(in->children[j]);
2803 if (p < loadmodel->brush.num_nodes)
2804 out->children[j] = loadmodel->brush.data_nodes + p;
2807 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2808 // map it to the solid leaf
2809 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2814 // note this uses 65535 intentionally, -1 is leaf 0
2816 if (p < loadmodel->brush.num_leafs)
2817 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2820 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2821 // map it to the solid leaf
2822 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2828 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2831 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2837 in = (dleaf_t *)(mod_base + l->fileofs);
2838 if (l->filelen % sizeof(*in))
2839 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2840 count = l->filelen / sizeof(*in);
2841 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2843 loadmodel->brush.data_leafs = out;
2844 loadmodel->brush.num_leafs = count;
2845 // get visleafs from the submodel data
2846 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2847 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2848 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2849 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2851 for ( i=0 ; i<count ; i++, in++, out++)
2853 for (j=0 ; j<3 ; j++)
2855 out->mins[j] = LittleShort(in->mins[j]);
2856 out->maxs[j] = LittleShort(in->maxs[j]);
2859 // FIXME: this function could really benefit from some error checking
2861 out->contents = LittleLong(in->contents);
2863 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2864 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2865 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2867 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);
2868 out->firstleafsurface = NULL;
2869 out->numleafsurfaces = 0;
2872 out->clusterindex = i - 1;
2873 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2874 out->clusterindex = -1;
2876 p = LittleLong(in->visofs);
2877 // ignore visofs errors on leaf 0 (solid)
2878 if (p >= 0 && out->clusterindex >= 0)
2880 if (p >= loadmodel->brushq1.num_compressedpvs)
2881 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2883 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);
2886 for (j = 0;j < 4;j++)
2887 out->ambient_sound_level[j] = in->ambient_level[j];
2889 // FIXME: Insert caustics here
2893 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2897 const unsigned char *pvs;
2898 // if there's no vis data, assume supported (because everything is visible all the time)
2899 if (!loadmodel->brush.data_pvsclusters)
2901 // check all liquid leafs to see if they can see into empty leafs, if any
2902 // can we can assume this map supports r_wateralpha
2903 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2905 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2907 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2908 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2909 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2916 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2923 in = (dclipnode_t *)(mod_base + l->fileofs);
2924 if (l->filelen % sizeof(*in))
2925 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2926 count = l->filelen / sizeof(*in);
2927 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2929 loadmodel->brushq1.clipnodes = out;
2930 loadmodel->brushq1.numclipnodes = count;
2932 for (i = 1; i < MAX_MAP_HULLS; i++)
2934 hull = &loadmodel->brushq1.hulls[i];
2935 hull->clipnodes = out;
2936 hull->firstclipnode = 0;
2937 hull->lastclipnode = count-1;
2938 hull->planes = loadmodel->brush.data_planes;
2939 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2940 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2941 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2942 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2943 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2944 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2945 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2948 for (i=0 ; i<count ; i++, out++, in++)
2950 out->planenum = LittleLong(in->planenum);
2951 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2952 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2953 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2954 if (out->children[0] >= count)
2955 out->children[0] -= 65536;
2956 if (out->children[1] >= count)
2957 out->children[1] -= 65536;
2958 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2959 Host_Error("Corrupt clipping hull(out of range planenum)");
2963 //Duplicate the drawing hull structure as a clipping hull
2964 static void Mod_Q1BSP_MakeHull0(void)
2971 hull = &loadmodel->brushq1.hulls[0];
2973 in = loadmodel->brush.data_nodes;
2974 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2976 hull->clipnodes = out;
2977 hull->firstclipnode = 0;
2978 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2979 hull->planes = loadmodel->brush.data_planes;
2981 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2983 out->planenum = in->plane - loadmodel->brush.data_planes;
2984 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2985 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2989 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2994 in = (short *)(mod_base + l->fileofs);
2995 if (l->filelen % sizeof(*in))
2996 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2997 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2998 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3000 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3002 j = (unsigned short) LittleShort(in[i]);
3003 if (j >= loadmodel->num_surfaces)
3004 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3005 loadmodel->brush.data_leafsurfaces[i] = j;
3009 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
3014 in = (int *)(mod_base + l->fileofs);
3015 if (l->filelen % sizeof(*in))
3016 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3017 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
3018 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3020 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3021 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
3025 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
3031 in = (dplane_t *)(mod_base + l->fileofs);
3032 if (l->filelen % sizeof(*in))
3033 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3035 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
3036 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3038 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
3040 out->normal[0] = LittleFloat(in->normal[0]);
3041 out->normal[1] = LittleFloat(in->normal[1]);
3042 out->normal[2] = LittleFloat(in->normal[2]);
3043 out->dist = LittleFloat(in->dist);
3049 static void Mod_Q1BSP_LoadMapBrushes(void)
3053 int submodel, numbrushes;
3054 qboolean firstbrush;
3055 char *text, *maptext;
3056 char mapfilename[MAX_QPATH];
3057 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3058 strlcat (mapfilename, ".map", sizeof (mapfilename));
3059 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3063 if (!COM_ParseToken_Simple(&data, false, false))
3068 if (!COM_ParseToken_Simple(&data, false, false))
3070 if (com_token[0] != '{')
3076 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3079 if (!COM_ParseToken_Simple(&data, false, false))
3081 if (com_token[0] == '}')
3082 break; // end of entity
3083 if (com_token[0] == '{')
3090 if (submodel > loadmodel->brush.numsubmodels)
3092 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3096 model = loadmodel->brush.submodels[submodel];
3103 if (!COM_ParseToken_Simple(&data, false, false))
3105 if (com_token[0] == '}')
3106 break; // end of brush
3107 // each brush face should be this format:
3108 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3109 // FIXME: support hl .map format
3110 for (pointnum = 0;pointnum < 3;pointnum++)
3112 COM_ParseToken_Simple(&data, false, false);
3113 for (componentnum = 0;componentnum < 3;componentnum++)
3115 COM_ParseToken_Simple(&data, false, false);
3116 point[pointnum][componentnum] = atof(com_token);
3118 COM_ParseToken_Simple(&data, false, false);
3120 COM_ParseToken_Simple(&data, false, false);
3121 strlcpy(facetexture, com_token, sizeof(facetexture));
3122 COM_ParseToken_Simple(&data, false, false);
3123 //scroll_s = atof(com_token);
3124 COM_ParseToken_Simple(&data, false, false);
3125 //scroll_t = atof(com_token);
3126 COM_ParseToken_Simple(&data, false, false);
3127 //rotate = atof(com_token);
3128 COM_ParseToken_Simple(&data, false, false);
3129 //scale_s = atof(com_token);
3130 COM_ParseToken_Simple(&data, false, false);
3131 //scale_t = atof(com_token);
3132 TriangleNormal(point[0], point[1], point[2], planenormal);
3133 VectorNormalizeDouble(planenormal);
3134 planedist = DotProduct(point[0], planenormal);
3135 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3145 #define MAX_PORTALPOINTS 64
3147 typedef struct portal_s
3150 mnode_t *nodes[2]; // [0] = front side of plane
3151 struct portal_s *next[2];
3153 double points[3*MAX_PORTALPOINTS];
3154 struct portal_s *chain; // all portals are linked into a list
3158 static memexpandablearray_t portalarray;
3160 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3162 // process only nodes (leafs already had their box calculated)
3166 // calculate children first
3167 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3168 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3170 // make combined bounding box from children
3171 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3172 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3173 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3174 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3175 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3176 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3179 static void Mod_Q1BSP_FinalizePortals(void)
3181 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
3185 mleaf_t *leaf, *endleaf;
3187 // tally up portal and point counts and recalculate bounding boxes for all
3188 // leafs (because qbsp is very sloppy)
3189 leaf = loadmodel->brush.data_leafs;
3190 endleaf = leaf + loadmodel->brush.num_leafs;
3191 if (mod_recalculatenodeboxes.integer)
3193 for (;leaf < endleaf;leaf++)
3195 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3196 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3201 for (portalindex = 0;portalindex < portalrange;portalindex++)
3203 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3206 // note: this check must match the one below or it will usually corrupt memory
3207 // 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
3208 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3211 numpoints += p->numpoints * 2;
3214 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3215 loadmodel->brush.num_portals = numportals;
3216 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3217 loadmodel->brush.num_portalpoints = numpoints;
3218 // clear all leaf portal chains
3219 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3220 loadmodel->brush.data_leafs[i].portals = NULL;
3221 // process all portals in the global portal chain, while freeing them
3222 portal = loadmodel->brush.data_portals;
3223 point = loadmodel->brush.data_portalpoints;
3224 for (portalindex = 0;portalindex < portalrange;portalindex++)
3226 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3229 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3231 // note: this check must match the one above or it will usually corrupt memory
3232 // 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
3233 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3235 // first make the back to front portal(forward portal)
3236 portal->points = point;
3237 portal->numpoints = p->numpoints;
3238 portal->plane.dist = p->plane.dist;
3239 VectorCopy(p->plane.normal, portal->plane.normal);
3240 portal->here = (mleaf_t *)p->nodes[1];
3241 portal->past = (mleaf_t *)p->nodes[0];
3243 for (j = 0;j < portal->numpoints;j++)
3245 VectorCopy(p->points + j*3, point->position);
3248 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3249 PlaneClassify(&portal->plane);
3251 // link into leaf's portal chain
3252 portal->next = portal->here->portals;
3253 portal->here->portals = portal;
3255 // advance to next portal
3258 // then make the front to back portal(backward portal)
3259 portal->points = point;
3260 portal->numpoints = p->numpoints;
3261 portal->plane.dist = -p->plane.dist;
3262 VectorNegate(p->plane.normal, portal->plane.normal);
3263 portal->here = (mleaf_t *)p->nodes[0];
3264 portal->past = (mleaf_t *)p->nodes[1];
3266 for (j = portal->numpoints - 1;j >= 0;j--)
3268 VectorCopy(p->points + j*3, point->position);
3271 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3272 PlaneClassify(&portal->plane);
3274 // link into leaf's portal chain
3275 portal->next = portal->here->portals;
3276 portal->here->portals = portal;
3278 // advance to next portal
3281 // add the portal's polygon points to the leaf bounding boxes
3282 if (mod_recalculatenodeboxes.integer)
3284 for (i = 0;i < 2;i++)
3286 leaf = (mleaf_t *)p->nodes[i];
3287 for (j = 0;j < p->numpoints;j++)
3289 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3290 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3291 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3292 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3293 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3294 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3300 // now recalculate the node bounding boxes from the leafs
3301 if (mod_recalculatenodeboxes.integer)
3302 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3310 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3313 Host_Error("AddPortalToNodes: NULL front node");
3315 Host_Error("AddPortalToNodes: NULL back node");
3316 if (p->nodes[0] || p->nodes[1])
3317 Host_Error("AddPortalToNodes: already included");
3318 // 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
3320 p->nodes[0] = front;
3321 p->next[0] = (portal_t *)front->portals;
3322 front->portals = (mportal_t *)p;
3325 p->next[1] = (portal_t *)back->portals;
3326 back->portals = (mportal_t *)p;
3331 RemovePortalFromNode
3334 static void RemovePortalFromNodes(portal_t *portal)
3338 void **portalpointer;
3340 for (i = 0;i < 2;i++)
3342 node = portal->nodes[i];
3344 portalpointer = (void **) &node->portals;
3347 t = (portal_t *)*portalpointer;
3349 Host_Error("RemovePortalFromNodes: portal not in leaf");
3353 if (portal->nodes[0] == node)
3355 *portalpointer = portal->next[0];
3356 portal->nodes[0] = NULL;
3358 else if (portal->nodes[1] == node)
3360 *portalpointer = portal->next[1];
3361 portal->nodes[1] = NULL;
3364 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3368 if (t->nodes[0] == node)
3369 portalpointer = (void **) &t->next[0];
3370 else if (t->nodes[1] == node)
3371 portalpointer = (void **) &t->next[1];
3373 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3378 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3379 static double *portalpointsbuffer;
3380 static int portalpointsbufferoffset;
3381 static int portalpointsbuffersize;
3382 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3385 mnode_t *front, *back, *other_node;
3386 mplane_t clipplane, *plane;
3387 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3388 int numfrontpoints, numbackpoints;
3389 double *frontpoints, *backpoints;
3391 // if a leaf, we're done
3395 // get some space for our clipping operations to use
3396 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3398 portalpointsbuffersize = portalpointsbufferoffset * 2;
3399 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3401 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3402 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3403 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3404 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3406 plane = node->plane;
3408 front = node->children[0];
3409 back = node->children[1];
3411 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3413 // create the new portal by generating a polygon for the node plane,
3414 // and clipping it by all of the other portals(which came from nodes above this one)
3415 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3416 nodeportal->plane = *plane;
3418 // 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)
3419 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);
3420 nodeportal->numpoints = 4;
3421 side = 0; // shut up compiler warning
3422 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3424 clipplane = portal->plane;
3425 if (portal->nodes[0] == portal->nodes[1])
3426 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3427 if (portal->nodes[0] == node)
3429 else if (portal->nodes[1] == node)
3431 clipplane.dist = -clipplane.dist;
3432 VectorNegate(clipplane.normal, clipplane.normal);
3436 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3438 for (i = 0;i < nodeportal->numpoints*3;i++)
3439 frontpoints[i] = nodeportal->points[i];
3440 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);
3441 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3445 if (nodeportal->numpoints < 3)
3447 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3448 nodeportal->numpoints = 0;
3450 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3452 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3453 nodeportal->numpoints = 0;
3456 AddPortalToNodes(nodeportal, front, back);
3458 // split the portals of this node along this node's plane and assign them to the children of this node
3459 // (migrating the portals downward through the tree)
3460 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3462 if (portal->nodes[0] == portal->nodes[1])
3463 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3464 if (portal->nodes[0] == node)
3466 else if (portal->nodes[1] == node)
3469 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3470 nextportal = portal->next[side];
3471 if (!portal->numpoints)
3474 other_node = portal->nodes[!side];
3475 RemovePortalFromNodes(portal);
3477 // cut the portal into two portals, one on each side of the node plane
3478 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);
3480 if (!numfrontpoints)
3483 AddPortalToNodes(portal, back, other_node);
3485 AddPortalToNodes(portal, other_node, back);
3491 AddPortalToNodes(portal, front, other_node);
3493 AddPortalToNodes(portal, other_node, front);
3497 // the portal is split
3498 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3499 temp = splitportal->chain;
3500 *splitportal = *portal;
3501 splitportal->chain = temp;
3502 for (i = 0;i < numbackpoints*3;i++)
3503 splitportal->points[i] = backpoints[i];
3504 splitportal->numpoints = numbackpoints;
3505 for (i = 0;i < numfrontpoints*3;i++)
3506 portal->points[i] = frontpoints[i];
3507 portal->numpoints = numfrontpoints;
3511 AddPortalToNodes(portal, front, other_node);
3512 AddPortalToNodes(splitportal, back, other_node);
3516 AddPortalToNodes(portal, other_node, front);
3517 AddPortalToNodes(splitportal, other_node, back);
3521 Mod_Q1BSP_RecursiveNodePortals(front);
3522 Mod_Q1BSP_RecursiveNodePortals(back);
3524 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3527 static void Mod_Q1BSP_MakePortals(void)
3529 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3530 portalpointsbufferoffset = 0;
3531 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3532 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3533 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3534 Mem_Free(portalpointsbuffer);
3535 portalpointsbuffer = NULL;
3536 portalpointsbufferoffset = 0;
3537 portalpointsbuffersize = 0;
3538 Mod_Q1BSP_FinalizePortals();
3539 Mem_ExpandableArray_FreeArray(&portalarray);
3542 //Returns PVS data for a given point
3543 //(note: can return NULL)
3544 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3547 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3549 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3550 if (((mleaf_t *)node)->clusterindex >= 0)
3551 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3556 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)
3560 float d = PlaneDiff(org, node->plane);
3562 node = node->children[0];
3563 else if (d < -radius)
3564 node = node->children[1];
3567 // go down both sides
3568 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3569 node = node->children[1];
3572 // if this leaf is in a cluster, accumulate the pvs bits
3573 if (((mleaf_t *)node)->clusterindex >= 0)
3576 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3577 for (i = 0;i < pvsbytes;i++)
3578 pvsbuffer[i] |= pvs[i];
3582 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3583 //of the given point.
3584 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3586 int bytes = model->brush.num_pvsclusterbytes;
3587 bytes = min(bytes, pvsbufferlength);
3588 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3590 memset(pvsbuffer, 0xFF, bytes);
3594 memset(pvsbuffer, 0, bytes);
3595 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3599 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3604 VectorSubtract(inmaxs, inmins, size);
3605 if (cmodel->brush.ishlbsp)
3608 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3609 else if (size[0] <= 32)
3611 if (size[2] < 54) // pick the nearest of 36 or 72
3612 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3614 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3617 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3622 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3623 else if (size[0] <= 32)
3624 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3626 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3628 VectorCopy(inmins, outmins);
3629 VectorAdd(inmins, hull->clip_size, outmaxs);
3632 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3635 int numshadowmeshtriangles = 0;
3636 msurface_t *surface;
3637 if (cls.state == ca_dedicated)
3639 // make a single combined shadow mesh to allow optimized shadow volume creation
3641 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3643 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3644 numshadowmeshtriangles += surface->num_triangles;
3646 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3647 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3648 if (surface->num_triangles > 0)
3649 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));
3650 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3651 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3652 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3654 return numshadowmeshtriangles;
3657 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);
3659 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3664 float dist, modelyawradius, modelradius;
3665 msurface_t *surface;
3666 hullinfo_t hullinfo;
3667 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3668 model_brush_lightstyleinfo_t styleinfo[256];
3669 unsigned char *datapointer;
3671 mod->modeldatatypestring = "Q1BSP";
3673 mod->type = mod_brushq1;
3675 header = (dheader_t *)buffer;
3677 i = LittleLong(header->version);
3678 if (i != BSPVERSION && i != 30)
3679 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3680 mod->brush.ishlbsp = i == 30;
3682 // fill in hull info
3683 VectorClear (hullinfo.hullsizes[0][0]);
3684 VectorClear (hullinfo.hullsizes[0][1]);
3685 if (mod->brush.ishlbsp)
3687 mod->modeldatatypestring = "HLBSP";
3689 hullinfo.filehulls = 4;
3690 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3691 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3692 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3693 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3694 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3695 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3699 hullinfo.filehulls = 4;
3700 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3701 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3702 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3703 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3707 mod_base = (unsigned char*)buffer;
3708 for (i = 0; i < HEADER_LUMPS; i++)
3710 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3711 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3714 mod->soundfromcenter = true;
3715 mod->TraceBox = Mod_Q1BSP_TraceBox;
3716 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
3717 mod->TraceLine = Mod_Q1BSP_TraceLineAgainstSurfaces; // LordHavoc: use the surface-hitting version of TraceLine in all cases
3719 mod->TraceLine = Mod_Q1BSP_TraceLine;
3720 mod->TracePoint = Mod_Q1BSP_TracePoint;
3721 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3722 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3723 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3724 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3725 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3726 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3727 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3728 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3729 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3730 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3731 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3732 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3733 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3734 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3735 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3736 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3737 mod->Draw = R_Q1BSP_Draw;
3738 mod->DrawDepth = R_Q1BSP_DrawDepth;
3739 mod->DrawDebug = R_Q1BSP_DrawDebug;
3740 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3741 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3742 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3743 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3744 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3745 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3746 mod->DrawLight = R_Q1BSP_DrawLight;
3750 mod->brush.qw_md4sum = 0;
3751 mod->brush.qw_md4sum2 = 0;
3752 for (i = 0;i < HEADER_LUMPS;i++)
3755 if (i == LUMP_ENTITIES)
3757 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3758 mod->brush.qw_md4sum ^= LittleLong(temp);
3759 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3761 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3762 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3765 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3766 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3767 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3768 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3769 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3770 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3771 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3772 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3773 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3774 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3775 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3776 // load submodels before leafs because they contain the number of vis leafs
3777 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3778 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3779 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3780 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3782 // check if the map supports transparent water rendering
3783 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3785 if (mod->brushq1.data_compressedpvs)
3786 Mem_Free(mod->brushq1.data_compressedpvs);
3787 mod->brushq1.data_compressedpvs = NULL;
3788 mod->brushq1.num_compressedpvs = 0;
3790 Mod_Q1BSP_MakeHull0();
3791 if (mod_bsp_portalize.integer)
3792 Mod_Q1BSP_MakePortals();
3794 mod->numframes = 2; // regular and alternate animation
3797 // make a single combined shadow mesh to allow optimized shadow volume creation
3798 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3800 if (loadmodel->brush.numsubmodels)
3801 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3803 // LordHavoc: to clear the fog around the original quake submodel code, I
3805 // first of all, some background info on the submodels:
3806 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3807 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3808 // now the weird for loop itself:
3809 // the loop functions in an odd way, on each iteration it sets up the
3810 // current 'mod' model (which despite the confusing code IS the model of
3811 // the number i), at the end of the loop it duplicates the model to become
3812 // the next submodel, and loops back to set up the new submodel.
3814 // LordHavoc: now the explanation of my sane way (which works identically):
3815 // set up the world model, then on each submodel copy from the world model
3816 // and set up the submodel with the respective model info.
3817 totalstylesurfaces = 0;
3819 for (i = 0;i < mod->brush.numsubmodels;i++)
3821 memset(stylecounts, 0, sizeof(stylecounts));
3822 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3824 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3825 for (j = 0;j < MAXLIGHTMAPS;j++)
3826 stylecounts[surface->lightmapinfo->styles[j]]++;
3828 for (k = 0;k < 255;k++)
3832 totalstylesurfaces += stylecounts[k];
3835 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3836 for (i = 0;i < mod->brush.numsubmodels;i++)
3838 // LordHavoc: this code was originally at the end of this loop, but
3839 // has been transformed to something more readable at the start here.
3844 // duplicate the basic information
3845 dpsnprintf(name, sizeof(name), "*%i", i);
3846 mod = Mod_FindName(name, loadmodel->name);
3847 // copy the base model to this one
3849 // rename the clone back to its proper name
3850 strlcpy(mod->name, name, sizeof(mod->name));
3851 mod->brush.parentmodel = loadmodel;
3852 // textures and memory belong to the main model
3853 mod->texturepool = NULL;
3854 mod->mempool = NULL;
3855 mod->brush.GetPVS = NULL;
3856 mod->brush.FatPVS = NULL;
3857 mod->brush.BoxTouchingPVS = NULL;
3858 mod->brush.BoxTouchingLeafPVS = NULL;
3859 mod->brush.BoxTouchingVisibleLeafs = NULL;
3860 mod->brush.FindBoxClusters = NULL;
3861 mod->brush.LightPoint = NULL;
3862 mod->brush.AmbientSoundLevelsForPoint = NULL;
3865 mod->brush.submodel = i;
3867 if (loadmodel->brush.submodels)
3868 loadmodel->brush.submodels[i] = mod;
3870 bm = &mod->brushq1.submodels[i];
3872 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3873 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3875 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3876 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3879 mod->firstmodelsurface = bm->firstface;
3880 mod->nummodelsurfaces = bm->numfaces;
3882 // set node/leaf parents for this submodel
3883 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3885 // make the model surface list (used by shadowing/lighting)
3886 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3887 Mod_MakeSortedSurfaces(mod);
3889 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3890 // (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)
3891 VectorCopy(bm->mins, mod->normalmins);
3892 VectorCopy(bm->maxs, mod->normalmaxs);
3893 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3894 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3895 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3896 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3897 modelradius = modelyawradius + modelradius * modelradius;
3898 modelyawradius = sqrt(modelyawradius);
3899 modelradius = sqrt(modelradius);
3900 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3901 mod->yawmins[2] = mod->normalmins[2];
3902 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3903 mod->yawmaxs[2] = mod->normalmaxs[2];
3904 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3905 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3906 mod->radius = modelradius;
3907 mod->radius2 = modelradius * modelradius;
3909 // this gets altered below if sky or water is used
3910 mod->DrawSky = NULL;
3911 mod->DrawAddWaterPlanes = NULL;
3913 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3914 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3915 if (mod->nummodelsurfaces)
3917 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3918 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3920 if (j < mod->nummodelsurfaces)
3921 mod->DrawSky = R_Q1BSP_DrawSky;
3923 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3924 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
3926 if (j < mod->nummodelsurfaces)
3927 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3929 // build lightstyle update chains
3930 // (used to rapidly mark lightmapupdateflags on many surfaces
3931 // when d_lightstylevalue changes)
3932 memset(stylecounts, 0, sizeof(stylecounts));
3933 for (k = 0;k < mod->nummodelsurfaces;k++)
3935 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3936 for (j = 0;j < MAXLIGHTMAPS;j++)
3937 stylecounts[surface->lightmapinfo->styles[j]]++;
3939 mod->brushq1.num_lightstyles = 0;
3940 for (k = 0;k < 255;k++)
3944 styleinfo[mod->brushq1.num_lightstyles].style = k;
3945 styleinfo[mod->brushq1.num_lightstyles].value = 0;
3946 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3947 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3948 remapstyles[k] = mod->brushq1.num_lightstyles;
3949 mod->brushq1.num_lightstyles++;
3952 for (k = 0;k < mod->nummodelsurfaces;k++)
3954 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3955 for (j = 0;j < MAXLIGHTMAPS;j++)
3957 if (surface->lightmapinfo->styles[j] != 255)
3959 int r = remapstyles[surface->lightmapinfo->styles[j]];
3960 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3964 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3965 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3969 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3970 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3972 //mod->brushq1.num_visleafs = bm->visleafs;
3974 // build a Bounding Interval Hierarchy for culling triangles in light rendering
3975 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
3977 if (mod_q1bsp_polygoncollisions.integer)
3979 mod->collision_bih = mod->render_bih;
3980 // point traces and contents checks still use the bsp tree
3981 mod->TraceLine = Mod_CollisionBIH_TraceLine;
3982 mod->TraceBox = Mod_CollisionBIH_TraceBox;
3983 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
3984 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
3987 // generate VBOs and other shared data before cloning submodels
3991 Mod_Q1BSP_LoadMapBrushes();
3992 //Mod_Q1BSP_ProcessLightList();
3996 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);
3999 static void Mod_Q2BSP_LoadEntities(lump_t *l)
4003 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
4010 in = (void *)(mod_base + l->fileofs);
4011 if (l->filelen % sizeof(*in))
4012 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4013 count = l->filelen / sizeof(*in);
4014 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4017 loadmodel->num = count;
4019 for (i = 0;i < count;i++, in++, out++)
4025 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4032 in = (void *)(mod_base + l->fileofs);
4033 if (l->filelen % sizeof(*in))
4034 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4035 count = l->filelen / sizeof(*in);
4036 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4039 loadmodel->num = count;
4041 for (i = 0;i < count;i++, in++, out++)
4047 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4054 in = (void *)(mod_base + l->fileofs);
4055 if (l->filelen % sizeof(*in))
4056 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4057 count = l->filelen / sizeof(*in);
4058 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4061 loadmodel->num = count;
4063 for (i = 0;i < count;i++, in++, out++)
4069 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4076 in = (void *)(mod_base + l->fileofs);
4077 if (l->filelen % sizeof(*in))
4078 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4079 count = l->filelen / sizeof(*in);
4080 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4083 loadmodel->num = count;
4085 for (i = 0;i < count;i++, in++, out++)
4091 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
4098 in = (void *)(mod_base + l->fileofs);
4099 if (l->filelen % sizeof(*in))
4100 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
4101 count = l->filelen / sizeof(*in);
4102 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4105 loadmodel->num = count;
4107 for (i = 0;i < count;i++, in++, out++)
4113 static void Mod_Q2BSP_LoadFaces(lump_t *l)
4120 in = (void *)(mod_base + l->fileofs);
4121 if (l->filelen % sizeof(*in))
4122 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4123 count = l->filelen / sizeof(*in);
4124 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4127 loadmodel->num = count;
4129 for (i = 0;i < count;i++, in++, out++)
4135 static void Mod_Q2BSP_LoadLighting(lump_t *l)
4142 in = (void *)(mod_base + l->fileofs);
4143 if (l->filelen % sizeof(*in))
4144 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
4145 count = l->filelen / sizeof(*in);
4146 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4149 loadmodel->num = count;
4151 for (i = 0;i < count;i++, in++, out++)
4157 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
4164 in = (void *)(mod_base + l->fileofs);
4165 if (l->filelen % sizeof(*in))
4166 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4167 count = l->filelen / sizeof(*in);
4168 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4171 loadmodel->num = count;
4173 for (i = 0;i < count;i++, in++, out++)
4179 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
4186 in = (void *)(mod_base + l->fileofs);
4187 if (l->filelen % sizeof(*in))
4188 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4189 count = l->filelen / sizeof(*in);
4190 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4193 loadmodel->num = count;
4195 for (i = 0;i < count;i++, in++, out++)
4201 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
4208 in = (void *)(mod_base + l->fileofs);
4209 if (l->filelen % sizeof(*in))
4210 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4211 count = l->filelen / sizeof(*in);
4212 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4215 loadmodel->num = count;
4217 for (i = 0;i < count;i++, in++, out++)
4223 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4230 in = (void *)(mod_base + l->fileofs);
4231 if (l->filelen % sizeof(*in))
4232 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4233 count = l->filelen / sizeof(*in);
4234 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4237 loadmodel->num = count;
4239 for (i = 0;i < count;i++, in++, out++)
4245 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4252 in = (void *)(mod_base + l->fileofs);
4253 if (l->filelen % sizeof(*in))
4254 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4255 count = l->filelen / sizeof(*in);
4256 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4259 loadmodel->num = count;
4261 for (i = 0;i < count;i++, in++, out++)
4267 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4274 in = (void *)(mod_base + l->fileofs);
4275 if (l->filelen % sizeof(*in))
4276 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4277 count = l->filelen / sizeof(*in);
4278 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4281 loadmodel->num = count;
4283 for (i = 0;i < count;i++, in++, out++)
4289 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4296 in = (void *)(mod_base + l->fileofs);
4297 if (l->filelen % sizeof(*in))
4298 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4299 count = l->filelen / sizeof(*in);
4300 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4303 loadmodel->num = count;
4305 for (i = 0;i < count;i++, in++, out++)
4311 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4318 in = (void *)(mod_base + l->fileofs);
4319 if (l->filelen % sizeof(*in))
4320 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4321 count = l->filelen / sizeof(*in);
4322 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4325 loadmodel->num = count;
4327 for (i = 0;i < count;i++, in++, out++)
4333 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4340 in = (void *)(mod_base + l->fileofs);
4341 if (l->filelen % sizeof(*in))
4342 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4343 count = l->filelen / sizeof(*in);
4344 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4347 loadmodel->num = count;
4349 for (i = 0;i < count;i++, in++, out++)
4355 static void Mod_Q2BSP_LoadModels(lump_t *l)
4362 in = (void *)(mod_base + l->fileofs);
4363 if (l->filelen % sizeof(*in))
4364 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4365 count = l->filelen / sizeof(*in);
4366 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4369 loadmodel->num = count;
4371 for (i = 0;i < count;i++, in++, out++)
4377 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4380 q2dheader_t *header;
4382 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4384 mod->modeldatatypestring = "Q2BSP";
4386 mod->type = mod_brushq2;
4388 header = (q2dheader_t *)buffer;
4390 i = LittleLong(header->version);
4391 if (i != Q2BSPVERSION)
4392 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4394 mod_base = (unsigned char *)header;
4396 // swap all the lumps
4397 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4398 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4400 mod->brush.qw_md4sum = 0;
4401 mod->brush.qw_md4sum2 = 0;
4402 for (i = 0;i < Q2HEADER_LUMPS;i++)
4404 if (i == Q2LUMP_ENTITIES)
4406 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4407 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4409 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4412 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4413 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4414 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4415 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4416 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4417 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4418 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4419 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4420 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4421 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4422 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4423 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4424 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4425 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4426 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4427 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4428 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4429 // LordHavoc: must go last because this makes the submodels
4430 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4433 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4434 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4436 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4439 char key[128], value[MAX_INPUTLINE];
4441 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4442 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4443 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4446 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4447 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4448 loadmodel->brush.entities[l->filelen] = 0;
4449 data = loadmodel->brush.entities;
4450 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4451 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4452 loadmodel->brushq3.deluxemapping = false;
4453 if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4457 if (!COM_ParseToken_Simple(&data, false, false))
4459 if (com_token[0] == '}')
4460 break; // end of worldspawn
4461 if (com_token[0] == '_')
4462 strlcpy(key, com_token + 1, sizeof(key));
4464 strlcpy(key, com_token, sizeof(key));
4465 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4466 key[strlen(key)-1] = 0;
4467 if (!COM_ParseToken_Simple(&data, false, false))
4469 strlcpy(value, com_token, sizeof(value));
4470 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4472 #if _MSC_VER >= 1400
4473 #define sscanf sscanf_s
4476 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4477 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4479 VectorSet(v, 64, 64, 128);
4480 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4481 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]);
4482 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4483 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4486 else if (!strcmp("deluxeMaps", key))
4488 if (!strcmp(com_token, "1"))
4490 loadmodel->brushq3.deluxemapping = true;
4491 loadmodel->brushq3.deluxemapping_modelspace = true;
4493 else if (!strcmp(com_token, "2"))
4495 loadmodel->brushq3.deluxemapping = true;
4496 loadmodel->brushq3.deluxemapping_modelspace = false;
4503 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4509 in = (q3dtexture_t *)(mod_base + l->fileofs);
4510 if (l->filelen % sizeof(*in))
4511 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4512 count = l->filelen / sizeof(*in);
4513 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4515 loadmodel->data_textures = out;
4516 loadmodel->num_textures = count;
4517 loadmodel->num_texturesperskin = loadmodel->num_textures;
4519 for (i = 0;i < count;i++)
4521 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4522 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4523 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4524 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4525 // restore the surfaceflags and supercontents
4526 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4527 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4531 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4537 in = (q3dplane_t *)(mod_base + l->fileofs);
4538 if (l->filelen % sizeof(*in))
4539 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4540 count = l->filelen / sizeof(*in);
4541 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4543 loadmodel->brush.data_planes = out;
4544 loadmodel->brush.num_planes = count;
4546 for (i = 0;i < count;i++, in++, out++)
4548 out->normal[0] = LittleFloat(in->normal[0]);
4549 out->normal[1] = LittleFloat(in->normal[1]);
4550 out->normal[2] = LittleFloat(in->normal[2]);
4551 out->dist = LittleFloat(in->dist);
4556 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4559 q3mbrushside_t *out;
4562 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4563 if (l->filelen % sizeof(*in))
4564 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4565 count = l->filelen / sizeof(*in);
4566 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4568 loadmodel->brush.data_brushsides = out;
4569 loadmodel->brush.num_brushsides = count;
4571 for (i = 0;i < count;i++, in++, out++)
4573 n = LittleLong(in->planeindex);
4574 if (n < 0 || n >= loadmodel->brush.num_planes)
4575 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4576 out->plane = loadmodel->brush.data_planes + n;
4577 n = LittleLong(in->textureindex);
4578 if (n < 0 || n >= loadmodel->num_textures)
4579 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4580 out->texture = loadmodel->data_textures + n;
4584 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4586 q3dbrushside_ig_t *in;
4587 q3mbrushside_t *out;
4590 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4591 if (l->filelen % sizeof(*in))
4592 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4593 count = l->filelen / sizeof(*in);
4594 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4596 loadmodel->brush.data_brushsides = out;
4597 loadmodel->brush.num_brushsides = count;
4599 for (i = 0;i < count;i++, in++, out++)
4601 n = LittleLong(in->planeindex);
4602 if (n < 0 || n >= loadmodel->brush.num_planes)
4603 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4604 out->plane = loadmodel->brush.data_planes + n;
4605 n = LittleLong(in->textureindex);
4606 if (n < 0 || n >= loadmodel->num_textures)
4607 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4608 out->texture = loadmodel->data_textures + n;
4612 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4616 int i, j, n, c, count, maxplanes, q3surfaceflags;
4617 colplanef_t *planes;
4619 in = (q3dbrush_t *)(mod_base + l->fileofs);
4620 if (l->filelen % sizeof(*in))
4621 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4622 count = l->filelen / sizeof(*in);
4623 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4625 loadmodel->brush.data_brushes = out;
4626 loadmodel->brush.num_brushes = count;
4631 for (i = 0;i < count;i++, in++, out++)
4633 n = LittleLong(in->firstbrushside);
4634 c = LittleLong(in->numbrushsides);
4635 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4636 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4637 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4638 out->numbrushsides = c;
4639 n = LittleLong(in->textureindex);
4640 if (n < 0 || n >= loadmodel->num_textures)
4641 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4642 out->texture = loadmodel->data_textures + n;
4644 // make a list of mplane_t structs to construct a colbrush from
4645 if (maxplanes < out->numbrushsides)
4647 maxplanes = out->numbrushsides;
4650 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4653 for (j = 0;j < out->numbrushsides;j++)
4655 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4656 planes[j].dist = out->firstbrushside[j].plane->dist;
4657 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4658 planes[j].texture = out->firstbrushside[j].texture;
4659 q3surfaceflags |= planes[j].q3surfaceflags;
4661 // make the colbrush from the planes
4662 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4664 // this whole loop can take a while (e.g. on redstarrepublic4)
4665 CL_KeepaliveMessage(false);
4671 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4677 in = (q3deffect_t *)(mod_base + l->fileofs);
4678 if (l->filelen % sizeof(*in))
4679 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4680 count = l->filelen / sizeof(*in);
4681 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4683 loadmodel->brushq3.data_effects = out;
4684 loadmodel->brushq3.num_effects = count;
4686 for (i = 0;i < count;i++, in++, out++)
4688 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4689 n = LittleLong(in->brushindex);
4690 if (n >= loadmodel->brush.num_brushes)
4692 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4695 out->brushindex = n;
4696 out->unknown = LittleLong(in->unknown);
4700 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4705 in = (q3dvertex_t *)(mod_base + l->fileofs);
4706 if (l->filelen % sizeof(*in))
4707 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4708 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4709 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4710 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4711 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4712 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4713 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4715 for (i = 0;i < count;i++, in++)
4717 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4718 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4719 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4720 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4721 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4722 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4723 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4724 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4725 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4726 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4727 // svector/tvector are calculated later in face loading
4728 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4730 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
4731 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
4732 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
4736 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4737 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4738 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4740 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4741 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4742 loadmodel->lit = true;
4746 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4752 in = (int *)(mod_base + l->fileofs);
4753 if (l->filelen % sizeof(int[3]))
4754 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4755 count = l->filelen / sizeof(*in);
4757 if(!loadmodel->brushq3.num_vertices)
4760 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4761 loadmodel->brushq3.num_triangles = 0;
4765 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4766 loadmodel->brushq3.num_triangles = count / 3;
4767 loadmodel->brushq3.data_element3i = out;
4769 for (i = 0;i < count;i++, in++, out++)
4771 *out = LittleLong(*in);
4772 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4774 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4780 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4782 q3dlightmap_t *input_pointer;
4800 int mergedrowsxcolumns;
4805 unsigned char *mergedpixels;
4806 unsigned char *mergeddeluxepixels;
4807 unsigned char *mergebuf;
4808 char mapname[MAX_QPATH];
4810 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4812 // defaults for q3bsp
4819 loadmodel->brushq3.lightmapsize = 128;
4821 if (cls.state == ca_dedicated)
4824 if(mod_q3bsp_nolightmaps.integer)
4830 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4831 if (developer_loading.integer)
4832 Con_Printf("Using internal lightmaps\n");
4833 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4834 if (l->filelen % sizeof(*input_pointer))
4835 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4836 count = l->filelen / sizeof(*input_pointer);
4837 for(i = 0; i < count; ++i)
4838 inpixels[i] = input_pointer[i].rgb;
4842 // no internal lightmaps
4843 // try external lightmaps
4844 if (developer_loading.integer)
4845 Con_Printf("Using external lightmaps\n");
4846 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4847 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false, NULL);
4851 // using EXTERNAL lightmaps instead
4852 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4854 Mem_Free(inpixels[0]);
4855 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4865 for(count = 1; ; ++count)
4867 inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false, NULL);
4868 if(!inpixels[count])
4869 break; // we got all of them
4870 if(image_width != size || image_height != size)
4872 Mem_Free(inpixels[count]);
4873 inpixels[count] = NULL;
4874 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);
4880 loadmodel->brushq3.lightmapsize = size;
4881 loadmodel->brushq3.num_originallightmaps = count;
4883 // now check the surfaces to see if any of them index an odd numbered
4884 // lightmap, if so this is not a deluxemapped bsp file
4886 // also check what lightmaps are actually used, because q3map2 sometimes
4887 // (always?) makes an unused one at the end, which
4888 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4889 // reason when only one lightmap is used, which can throw off the
4890 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4891 // to see if the second lightmap is blank, if so it is not deluxemapped.
4892 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4893 // in Mod_Q3BSP_LoadEntities was failed
4894 if (!loadmodel->brushq3.deluxemapping)
4896 loadmodel->brushq3.deluxemapping = !(count & 1);
4897 loadmodel->brushq3.deluxemapping_modelspace = true;
4899 if (loadmodel->brushq3.deluxemapping)
4901 int facecount = faceslump->filelen / sizeof(q3dface_t);
4902 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4903 for (i = 0;i < facecount;i++)
4905 j = LittleLong(faces[i].lightmapindex);
4908 endlightmap = max(endlightmap, j + 1);
4909 if ((j & 1) || j + 1 >= count)
4911 loadmodel->brushq3.deluxemapping = false;
4918 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4919 // reason when only one lightmap is used, which can throw off the
4920 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4921 // to see if the second lightmap is blank, if so it is not deluxemapped.
4923 // further research has shown q3map2 sometimes creates a deluxemap and two
4924 // blank lightmaps, which must be handled properly as well
4925 if (endlightmap == 1 && count > 1)
4928 for (i = 0;i < size*size;i++)
4930 if (c[bytesperpixel*i + rgbmap[0]])
4932 if (c[bytesperpixel*i + rgbmap[1]])
4934 if (c[bytesperpixel*i + rgbmap[2]])
4939 // all pixels in the unused lightmap were black...
4940 loadmodel->brushq3.deluxemapping = false;
4945 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4947 // figure out what the most reasonable merge power is within limits
4949 // find the appropriate NxN dimensions to merge to, to avoid wasted space
4950 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
4952 // figure out how big the merged texture has to be
4953 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
4954 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
4955 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
4957 mergedwidth = mergegoal;
4958 mergedheight = mergegoal;
4959 // choose non-square size (2x1 aspect) if only half the space is used;
4960 // this really only happens when the entire set fits in one texture, if
4961 // there are multiple textures, we don't worry about shrinking the last
4962 // one to fit, because the driver prefers the same texture size on
4963 // consecutive draw calls...
4964 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
4967 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
4968 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
4969 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
4970 loadmodel->brushq3.num_lightmapmergedwidthpower++;
4971 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
4972 loadmodel->brushq3.num_lightmapmergedheightpower++;
4973 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
4975 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
4976 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
4977 powerxy = powerx+powery;
4978 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
4980 mergedcolumns = 1 << powerx;
4981 mergedrows = 1 << powery;
4982 mergedrowsxcolumns = 1 << powerxy;
4984 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
4985 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4986 if (loadmodel->brushq3.deluxemapping)
4987 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4989 // allocate a texture pool if we need it
4990 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4991 loadmodel->texturepool = R_AllocTexturePool();
4993 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
4994 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
4995 for (i = 0;i < count;i++)
4997 // figure out which merged lightmap texture this fits into
4998 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
4999 lightmapindex = i >> powerdxy;
5001 // choose the destination address
5002 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5003 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5004 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5005 Con_DPrintf("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);
5007 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5008 for (j = 0;j < size;j++)
5009 for (k = 0;k < size;k++)
5011 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5012 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5013 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5014 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5017 // upload texture if this was the last tile being written to the texture
5018 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5020 if (loadmodel->brushq3.deluxemapping && (i & 1))
5021 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);
5024 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5025 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5026 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);
5031 if (mergeddeluxepixels)
5032 Mem_Free(mergeddeluxepixels);
5033 Mem_Free(mergedpixels);
5036 for(i = 0; i < count; ++i)
5037 Mem_Free(inpixels[i]);
5041 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5046 *collisionstride = stride;
5049 cnt = (num_triangles + stride - 1) / stride;
5050 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5051 for(j = 0; j < cnt; ++j)
5053 mins = &((*collisionbbox6f)[6 * j + 0]);
5054 maxs = &((*collisionbbox6f)[6 * j + 3]);
5055 for(k = 0; k < stride; ++k)
5057 tri = j * stride + k;
5058 if(tri >= num_triangles)
5060 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5061 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5062 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5063 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5064 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5065 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5066 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5067 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5068 if(vert[0] < mins[0]) mins[0] = vert[0];
5069 if(vert[1] < mins[1]) mins[1] = vert[1];
5070 if(vert[2] < mins[2]) mins[2] = vert[2];
5071 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5072 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5073 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5074 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5075 if(vert[0] < mins[0]) mins[0] = vert[0];
5076 if(vert[1] < mins[1]) mins[1] = vert[1];
5077 if(vert[2] < mins[2]) mins[2] = vert[2];
5078 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5079 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5080 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5085 *collisionbbox6f = NULL;
5088 typedef struct patchtess_s
5092 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5095 float *originalvertex3f;
5098 #define PATCHTESS_SAME_LODGROUP(a,b) \
5100 (a).lodgroup[0] == (b).lodgroup[0] && \
5101 (a).lodgroup[1] == (b).lodgroup[1] && \
5102 (a).lodgroup[2] == (b).lodgroup[2] && \
5103 (a).lodgroup[3] == (b).lodgroup[3] && \
5104 (a).lodgroup[4] == (b).lodgroup[4] && \
5105 (a).lodgroup[5] == (b).lodgroup[5] \
5108 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5110 q3dface_t *in, *oldin;
5111 msurface_t *out, *oldout;
5112 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;
5113 float lightmaptcbase[2], lightmaptcscale[2];
5114 //int *originalelement3i;
5115 //int *originalneighbor3i;
5116 float *originalvertex3f;
5117 //float *originalsvector3f;
5118 //float *originaltvector3f;
5119 float *originalnormal3f;
5120 float *originalcolor4f;
5121 float *originaltexcoordtexture2f;
5122 float *originaltexcoordlightmap2f;
5123 float *surfacecollisionvertex3f;
5124 int *surfacecollisionelement3i;
5126 patchtess_t *patchtess = NULL;
5127 int patchtesscount = 0;
5130 in = (q3dface_t *)(mod_base + l->fileofs);
5131 if (l->filelen % sizeof(*in))
5132 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5133 count = l->filelen / sizeof(*in);
5134 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5136 loadmodel->data_surfaces = out;
5137 loadmodel->num_surfaces = count;
5140 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5148 for (;i < count;i++, in++, out++)
5150 // check face type first
5151 type = LittleLong(in->type);
5152 if (type != Q3FACETYPE_FLAT
5153 && type != Q3FACETYPE_PATCH
5154 && type != Q3FACETYPE_MESH
5155 && type != Q3FACETYPE_FLARE)
5157 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5161 n = LittleLong(in->textureindex);
5162 if (n < 0 || n >= loadmodel->num_textures)
5164 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5167 out->texture = loadmodel->data_textures + n;
5168 n = LittleLong(in->effectindex);
5169 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5171 if (developer_extra.integer)
5172 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5178 out->effect = loadmodel->brushq3.data_effects + n;
5180 if (cls.state != ca_dedicated)
5182 out->lightmaptexture = NULL;
5183 out->deluxemaptexture = r_texture_blanknormalmap;
5184 n = LittleLong(in->lightmapindex);
5187 else if (n >= loadmodel->brushq3.num_originallightmaps)
5189 if(loadmodel->brushq3.num_originallightmaps != 0)
5190 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5195 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5196 if (loadmodel->brushq3.deluxemapping)
5197 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5198 loadmodel->lit = true;
5202 firstvertex = LittleLong(in->firstvertex);
5203 numvertices = LittleLong(in->numvertices);
5204 firstelement = LittleLong(in->firstelement);
5205 numtriangles = LittleLong(in->numelements) / 3;
5206 if (numtriangles * 3 != LittleLong(in->numelements))
5208 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));
5211 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5213 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);
5216 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5218 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);
5223 case Q3FACETYPE_FLAT:
5224 case Q3FACETYPE_MESH:
5225 // no processing necessary
5227 case Q3FACETYPE_PATCH:
5228 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5229 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5230 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))
5232 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5235 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5237 // convert patch to Q3FACETYPE_MESH
5238 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5239 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5240 // bound to user settings
5241 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5242 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5243 // bound to sanity settings
5244 xtess = bound(0, xtess, 1024);
5245 ytess = bound(0, ytess, 1024);
5247 // lower quality collision patches! Same procedure as before, but different cvars
5248 // convert patch to Q3FACETYPE_MESH
5249 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5250 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5251 // bound to user settings
5252 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5253 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5254 // bound to sanity settings
5255 cxtess = bound(0, cxtess, 1024);
5256 cytess = bound(0, cytess, 1024);
5258 // store it for the LOD grouping step
5259 patchtess[patchtesscount].info.xsize = patchsize[0];
5260 patchtess[patchtesscount].info.ysize = patchsize[1];
5261 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5262 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5263 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5264 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5266 patchtess[patchtesscount].surface_id = i;
5267 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5268 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5269 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5270 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5271 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5272 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5273 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5276 case Q3FACETYPE_FLARE:
5277 if (developer_extra.integer)
5278 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5282 out->num_vertices = numvertices;
5283 out->num_triangles = numtriangles;
5284 meshvertices += out->num_vertices;
5285 meshtriangles += out->num_triangles;
5288 // Fix patches tesselations so that they make no seams
5292 for(i = 0; i < patchtesscount; ++i)
5294 for(j = i+1; j < patchtesscount; ++j)
5296 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5299 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5306 // Calculate resulting number of triangles
5307 collisionvertices = 0;
5308 collisiontriangles = 0;
5309 for(i = 0; i < patchtesscount; ++i)
5311 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5312 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5313 numvertices = finalwidth * finalheight;
5314 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5316 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5317 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5318 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5319 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5321 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5322 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5323 numvertices = finalwidth * finalheight;
5324 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5326 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5327 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5328 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5329 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5335 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5336 if (collisiontriangles)
5338 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5339 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5343 collisionvertices = 0;
5344 collisiontriangles = 0;
5345 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5347 if (out->num_vertices < 3 || out->num_triangles < 1)
5350 type = LittleLong(in->type);
5351 firstvertex = LittleLong(in->firstvertex);
5352 firstelement = LittleLong(in->firstelement);
5353 out->num_firstvertex = meshvertices;
5354 out->num_firsttriangle = meshtriangles;
5355 out->num_firstcollisiontriangle = collisiontriangles;
5358 case Q3FACETYPE_FLAT:
5359 case Q3FACETYPE_MESH:
5360 // no processing necessary, except for lightmap merging
5361 for (j = 0;j < out->num_vertices;j++)
5363 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5364 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5365 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5366 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5367 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5368 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5369 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5370 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5371 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5372 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5373 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5374 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5375 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5376 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5378 for (j = 0;j < out->num_triangles*3;j++)
5379 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5381 case Q3FACETYPE_PATCH:
5382 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5383 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5384 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5385 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5386 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5387 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5388 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5390 xtess = ytess = cxtess = cytess = -1;
5391 for(j = 0; j < patchtesscount; ++j)
5392 if(patchtess[j].surface_id == i)
5394 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5395 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5396 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5397 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5402 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5403 xtess = ytess = cxtess = cytess = 0;
5406 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5407 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5408 finalvertices = finalwidth * finalheight;
5409 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5410 type = Q3FACETYPE_MESH;
5411 // generate geometry
5412 // (note: normals are skipped because they get recalculated)
5413 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5414 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5415 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5416 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5417 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5418 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5420 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);
5422 if (developer_extra.integer)
5424 if (out->num_triangles < finaltriangles)
5425 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);
5427 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);
5429 // q3map does not put in collision brushes for curves... ugh
5430 // build the lower quality collision geometry
5431 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5432 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5433 finalvertices = finalwidth * finalheight;
5434 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5436 // legacy collision geometry implementation
5437 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5438 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5439 out->num_collisionvertices = finalvertices;
5440 out->num_collisiontriangles = finaltriangles;
5441 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5442 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5444 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5445 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5447 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5449 // now optimize the collision mesh by finding triangle bboxes...
5450 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5451 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);
5453 // store collision geometry for BIH collision tree
5454 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5455 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5456 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5457 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5458 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5460 // remove this once the legacy code is removed
5462 int nc = out->num_collisiontriangles;
5464 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5466 if(nc != out->num_collisiontriangles)
5468 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5473 if (developer_extra.integer)
5474 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);
5476 collisionvertices += finalvertices;
5477 collisiontriangles += out->num_collisiontriangles;
5482 meshvertices += out->num_vertices;
5483 meshtriangles += out->num_triangles;
5484 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5485 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)
5487 if (invalidelements)
5489 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);
5490 for (j = 0;j < out->num_triangles * 3;j++)
5492 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5493 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)
5494 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5498 // calculate a bounding box
5499 VectorClear(out->mins);
5500 VectorClear(out->maxs);
5501 if (out->num_vertices)
5503 if (cls.state != ca_dedicated && out->lightmaptexture)
5505 // figure out which part of the merged lightmap this fits into
5506 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5507 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5508 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5509 lightmapindex &= mergewidth * mergeheight - 1;
5510 lightmaptcscale[0] = 1.0f / mergewidth;
5511 lightmaptcscale[1] = 1.0f / mergeheight;
5512 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5513 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5514 // modify the lightmap texcoords to match this region of the merged lightmap
5515 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5517 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5518 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5521 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5522 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5523 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5525 out->mins[0] = min(out->mins[0], v[0]);
5526 out->maxs[0] = max(out->maxs[0], v[0]);
5527 out->mins[1] = min(out->mins[1], v[1]);
5528 out->maxs[1] = max(out->maxs[1], v[1]);
5529 out->mins[2] = min(out->mins[2], v[2]);
5530 out->maxs[2] = max(out->maxs[2], v[2]);
5532 out->mins[0] -= 1.0f;
5533 out->mins[1] -= 1.0f;
5534 out->mins[2] -= 1.0f;
5535 out->maxs[0] += 1.0f;
5536 out->maxs[1] += 1.0f;
5537 out->maxs[2] += 1.0f;
5539 // set lightmap styles for consistency with q1bsp
5540 //out->lightmapinfo->styles[0] = 0;
5541 //out->lightmapinfo->styles[1] = 255;
5542 //out->lightmapinfo->styles[2] = 255;
5543 //out->lightmapinfo->styles[3] = 255;
5548 for (;i < count;i++, out++)
5550 if(out->num_vertices && out->num_triangles)
5552 if(out->num_vertices == 0)
5554 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5555 if(out->num_triangles == 0)
5556 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5558 else if(out->num_triangles == 0)
5559 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)",
5560 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5561 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5562 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5565 // for per pixel lighting
5566 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);
5568 // generate ushort elements array if possible
5569 if (loadmodel->surfmesh.data_element3s)
5570 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5571 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5573 // free the no longer needed vertex data
5574 loadmodel->brushq3.num_vertices = 0;
5575 if (loadmodel->brushq3.data_vertex3f)
5576 Mem_Free(loadmodel->brushq3.data_vertex3f);
5577 loadmodel->brushq3.data_vertex3f = NULL;
5578 loadmodel->brushq3.data_normal3f = NULL;
5579 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5580 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5581 loadmodel->brushq3.data_color4f = NULL;
5582 // free the no longer needed triangle data
5583 loadmodel->brushq3.num_triangles = 0;
5584 if (loadmodel->brushq3.data_element3i)
5585 Mem_Free(loadmodel->brushq3.data_element3i);
5586 loadmodel->brushq3.data_element3i = NULL;
5589 Mem_Free(patchtess);
5592 static void Mod_Q3BSP_LoadModels(lump_t *l)
5596 int i, j, n, c, count;
5598 in = (q3dmodel_t *)(mod_base + l->fileofs);
5599 if (l->filelen % sizeof(*in))
5600 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5601 count = l->filelen / sizeof(*in);
5602 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5604 loadmodel->brushq3.data_models = out;
5605 loadmodel->brushq3.num_models = count;
5607 for (i = 0;i < count;i++, in++, out++)
5609 for (j = 0;j < 3;j++)
5611 out->mins[j] = LittleFloat(in->mins[j]);
5612 out->maxs[j] = LittleFloat(in->maxs[j]);
5614 n = LittleLong(in->firstface);
5615 c = LittleLong(in->numfaces);
5616 if (n < 0 || n + c > loadmodel->num_surfaces)
5617 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5620 n = LittleLong(in->firstbrush);
5621 c = LittleLong(in->numbrushes);
5622 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5623 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5624 out->firstbrush = n;
5625 out->numbrushes = c;
5629 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5635 in = (int *)(mod_base + l->fileofs);
5636 if (l->filelen % sizeof(*in))
5637 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5638 count = l->filelen / sizeof(*in);
5639 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5641 loadmodel->brush.data_leafbrushes = out;
5642 loadmodel->brush.num_leafbrushes = count;
5644 for (i = 0;i < count;i++, in++, out++)
5646 n = LittleLong(*in);
5647 if (n < 0 || n >= loadmodel->brush.num_brushes)
5648 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5653 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5659 in = (int *)(mod_base + l->fileofs);
5660 if (l->filelen % sizeof(*in))
5661 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5662 count = l->filelen / sizeof(*in);
5663 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5665 loadmodel->brush.data_leafsurfaces = out;
5666 loadmodel->brush.num_leafsurfaces = count;
5668 for (i = 0;i < count;i++, in++, out++)
5670 n = LittleLong(*in);
5671 if (n < 0 || n >= loadmodel->num_surfaces)
5672 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5677 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5681 int i, j, n, c, count;
5683 in = (q3dleaf_t *)(mod_base + l->fileofs);
5684 if (l->filelen % sizeof(*in))
5685 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5686 count = l->filelen / sizeof(*in);
5687 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5689 loadmodel->brush.data_leafs = out;
5690 loadmodel->brush.num_leafs = count;
5692 for (i = 0;i < count;i++, in++, out++)
5696 out->clusterindex = LittleLong(in->clusterindex);
5697 out->areaindex = LittleLong(in->areaindex);
5698 for (j = 0;j < 3;j++)
5700 // yes the mins/maxs are ints
5701 out->mins[j] = LittleLong(in->mins[j]) - 1;
5702 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5704 n = LittleLong(in->firstleafface);
5705 c = LittleLong(in->numleaffaces);
5706 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5707 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5708 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5709 out->numleafsurfaces = c;
5710 n = LittleLong(in->firstleafbrush);
5711 c = LittleLong(in->numleafbrushes);
5712 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5713 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5714 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5715 out->numleafbrushes = c;
5719 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5725 in = (q3dnode_t *)(mod_base + l->fileofs);
5726 if (l->filelen % sizeof(*in))
5727 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5728 count = l->filelen / sizeof(*in);
5730 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5731 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5733 loadmodel->brush.data_nodes = out;
5734 loadmodel->brush.num_nodes = count;
5736 for (i = 0;i < count;i++, in++, out++)
5739 n = LittleLong(in->planeindex);
5740 if (n < 0 || n >= loadmodel->brush.num_planes)
5741 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5742 out->plane = loadmodel->brush.data_planes + n;
5743 for (j = 0;j < 2;j++)
5745 n = LittleLong(in->childrenindex[j]);
5748 if (n >= loadmodel->brush.num_nodes)
5749 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5750 out->children[j] = loadmodel->brush.data_nodes + n;
5755 if (n >= loadmodel->brush.num_leafs)
5756 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5757 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5760 for (j = 0;j < 3;j++)
5762 // yes the mins/maxs are ints
5763 out->mins[j] = LittleLong(in->mins[j]) - 1;
5764 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5768 // set the parent pointers
5769 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5772 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5775 q3dlightgrid_t *out;
5778 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5779 if (l->filelen % sizeof(*in))
5780 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5781 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5782 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5783 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5784 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5785 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5786 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5787 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5788 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5789 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5790 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5791 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5792 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5793 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5794 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]);
5795 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]);
5797 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5800 if (l->filelen < count * (int)sizeof(*in))
5802 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]);
5803 return; // ignore the grid if we cannot understand it
5805 if (l->filelen != count * (int)sizeof(*in))
5806 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5807 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5808 loadmodel->brushq3.data_lightgrid = out;
5809 loadmodel->brushq3.num_lightgrid = count;
5810 // no swapping or validation necessary
5811 memcpy(out, in, count * (int)sizeof(*out));
5815 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5820 if (l->filelen == 0)
5823 // unvised maps often have cluster indices even without pvs, so check
5824 // leafs to find real number of clusters
5825 loadmodel->brush.num_pvsclusters = 1;
5826 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5827 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5830 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5831 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5832 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5833 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5837 in = (q3dpvs_t *)(mod_base + l->fileofs);
5839 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5841 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5842 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5843 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5844 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5845 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5846 if (l->filelen < totalchains + (int)sizeof(*in))
5847 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);
5849 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5850 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5853 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5855 int i, j, k, index[3];
5856 float transformed[3], blend1, blend2, blend, stylescale = 1;
5857 q3dlightgrid_t *a, *s;
5859 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5860 switch(vid.renderpath)
5862 case RENDERPATH_GL20:
5863 case RENDERPATH_D3D9:
5864 case RENDERPATH_D3D10:
5865 case RENDERPATH_D3D11:
5866 case RENDERPATH_SOFT:
5867 case RENDERPATH_GLES2:
5868 // LordHavoc: FIXME: is this true?
5869 stylescale = 1; // added while render
5871 case RENDERPATH_GL11:
5872 case RENDERPATH_GL13:
5873 case RENDERPATH_GLES1:
5874 stylescale = r_refdef.scene.rtlightstylevalue[0];
5878 if (!model->brushq3.num_lightgrid)
5880 ambientcolor[0] = stylescale;
5881 ambientcolor[1] = stylescale;
5882 ambientcolor[2] = stylescale;
5886 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5887 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5888 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5889 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5890 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5891 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5892 index[0] = (int)floor(transformed[0]);
5893 index[1] = (int)floor(transformed[1]);
5894 index[2] = (int)floor(transformed[2]);
5895 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5897 // now lerp the values
5898 VectorClear(diffusenormal);
5899 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5900 for (k = 0;k < 2;k++)
5902 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5903 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5905 for (j = 0;j < 2;j++)
5907 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5908 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5910 for (i = 0;i < 2;i++)
5912 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5913 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5915 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5916 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5917 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5918 // this uses the mod_md3_sin table because the values are
5919 // already in the 0-255 range, the 64+ bias fetches a cosine
5920 // instead of a sine value
5921 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5922 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5923 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5924 //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)));
5929 // normalize the light direction before turning
5930 VectorNormalize(diffusenormal);
5931 //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]);
5934 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5937 double midf, mid[3];
5943 // find the point distances
5944 mplane_t *plane = node->plane;
5945 if (plane->type < 3)
5947 t1 = p1[plane->type] - plane->dist;
5948 t2 = p2[plane->type] - plane->dist;
5952 t1 = DotProduct (plane->normal, p1) - plane->dist;
5953 t2 = DotProduct (plane->normal, p2) - plane->dist;
5960 node = node->children[1];
5969 node = node->children[0];
5975 midf = t1 / (t1 - t2);
5976 VectorLerp(p1, midf, p2, mid);
5978 // recurse both sides, front side first
5979 // return 2 if empty is followed by solid (hit something)
5980 // do not return 2 if both are solid or both empty,
5981 // or if start is solid and end is empty
5982 // as these degenerate cases usually indicate the eye is in solid and
5983 // should see the target point anyway
5984 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
5987 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5992 return ((mleaf_t *)node)->clusterindex < 0;
5995 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5997 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6000 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6001 return trace.fraction == 1;
6005 double tracestart[3], traceend[3];
6006 VectorCopy(start, tracestart);
6007 VectorCopy(end, traceend);
6008 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6012 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)
6015 const bih_leaf_t *leaf;
6016 const bih_node_t *node;
6017 const colbrushf_t *brush;
6020 int nodestackpos = 0;
6021 int nodestack[1024];
6023 memset(trace, 0, sizeof(*trace));
6024 trace->fraction = 1;
6025 trace->realfraction = 1;
6026 trace->hitsupercontentsmask = hitsupercontentsmask;
6028 bih = &model->collision_bih;
6032 nodenum = bih->rootnode;
6033 nodestack[nodestackpos++] = nodenum;
6034 while (nodestackpos)
6036 nodenum = nodestack[--nodestackpos];
6037 node = bih->nodes + nodenum;
6039 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6042 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6044 axis = node->type - BIH_SPLITX;
6045 if (start[axis] >= node->frontmin)
6046 nodestack[nodestackpos++] = node->front;
6047 if (start[axis] <= node->backmax)
6048 nodestack[nodestackpos++] = node->back;
6050 else if (node->type == BIH_UNORDERED)
6052 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6054 leaf = bih->leafs + node->children[axis];
6056 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6062 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6063 Collision_TracePointBrushFloat(trace, start, brush);
6065 case BIH_COLLISIONTRIANGLE:
6066 // collision triangle - skipped because they have no volume
6068 case BIH_RENDERTRIANGLE:
6069 // render triangle - skipped because they have no volume
6077 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)
6079 const bih_leaf_t *leaf;
6080 const bih_node_t *node;
6081 const colbrushf_t *brush;
6083 const texture_t *texture;
6084 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6085 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6086 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6091 if (VectorCompare(start, end))
6093 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6097 nodenum = bih->rootnode;
6099 memset(trace, 0, sizeof(*trace));
6100 trace->fraction = 1;
6101 trace->realfraction = 1;
6102 trace->hitsupercontentsmask = hitsupercontentsmask;
6105 nodestackline[nodestackpos][0] = start[0];
6106 nodestackline[nodestackpos][1] = start[1];
6107 nodestackline[nodestackpos][2] = start[2];
6108 nodestackline[nodestackpos][3] = end[0];
6109 nodestackline[nodestackpos][4] = end[1];
6110 nodestackline[nodestackpos][5] = end[2];
6111 nodestack[nodestackpos++] = nodenum;
6112 while (nodestackpos)
6114 nodenum = nodestack[--nodestackpos];
6115 node = bih->nodes + nodenum;
6116 VectorCopy(nodestackline[nodestackpos], nodestart);
6117 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6118 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]);
6119 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6121 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6123 // recurse children of the split
6124 axis = node->type - BIH_SPLITX;
6125 d1 = node->backmax - nodestart[axis];
6126 d2 = node->backmax - nodeend[axis];
6127 d3 = nodestart[axis] - node->frontmin;
6128 d4 = nodeend[axis] - node->frontmin;
6129 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6131 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;
6132 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;
6133 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;
6134 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6135 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;
6136 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;
6137 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;
6138 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6139 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;
6140 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;
6141 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;
6142 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6143 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6144 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6145 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6146 case 15: /* <<<< */ break;
6149 else if (node->type == BIH_UNORDERED)
6151 // calculate sweep bounds for this node
6152 // copy node bounds into local variables
6153 VectorCopy(node->mins, nodebigmins);
6154 VectorCopy(node->maxs, nodebigmaxs);
6155 // clip line to this node bounds
6156 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); }
6157 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); }
6158 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); }
6159 // some of the line intersected the enlarged node box
6160 // calculate sweep bounds for this node
6161 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]);
6162 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6164 leaf = bih->leafs + node->children[axis];
6165 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6170 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6171 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6173 case BIH_COLLISIONTRIANGLE:
6174 if (!mod_q3bsp_curves_collisions.integer)
6176 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6177 texture = model->data_textures + leaf->textureindex;
6178 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);
6180 case BIH_RENDERTRIANGLE:
6181 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6182 texture = model->data_textures + leaf->textureindex;
6183 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);
6191 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)
6193 if (VectorCompare(start, end))
6195 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6198 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6201 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)
6204 const bih_leaf_t *leaf;
6205 const bih_node_t *node;
6206 const colbrushf_t *brush;
6208 const texture_t *texture;
6209 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6210 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6211 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6212 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6214 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6216 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6217 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6219 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6223 bih = &model->collision_bih;
6226 nodenum = bih->rootnode;
6228 // box trace, performed as brush trace
6229 memset(trace, 0, sizeof(*trace));
6230 trace->fraction = 1;
6231 trace->realfraction = 1;
6232 trace->hitsupercontentsmask = hitsupercontentsmask;
6234 // calculate tracebox-like parameters for efficient culling
6235 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6236 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6237 VectorSubtract(thisbrush_start->mins, start, startmins);
6238 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6239 VectorSubtract(thisbrush_end->mins, end, endmins);
6240 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6241 mins[0] = min(startmins[0], endmins[0]);
6242 mins[1] = min(startmins[1], endmins[1]);
6243 mins[2] = min(startmins[2], endmins[2]);
6244 maxs[0] = max(startmaxs[0], endmaxs[0]);
6245 maxs[1] = max(startmaxs[1], endmaxs[1]);
6246 maxs[2] = max(startmaxs[2], endmaxs[2]);
6249 nodestackline[nodestackpos][0] = start[0];
6250 nodestackline[nodestackpos][1] = start[1];
6251 nodestackline[nodestackpos][2] = start[2];
6252 nodestackline[nodestackpos][3] = end[0];
6253 nodestackline[nodestackpos][4] = end[1];
6254 nodestackline[nodestackpos][5] = end[2];
6255 nodestack[nodestackpos++] = nodenum;
6256 while (nodestackpos)
6258 nodenum = nodestack[--nodestackpos];
6259 node = bih->nodes + nodenum;
6260 VectorCopy(nodestackline[nodestackpos], nodestart);
6261 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6262 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];
6263 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6265 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6267 // recurse children of the split
6268 axis = node->type - BIH_SPLITX;
6269 d1 = node->backmax - nodestart[axis] - mins[axis];
6270 d2 = node->backmax - nodeend[axis] - mins[axis];
6271 d3 = nodestart[axis] - node->frontmin + maxs[axis];
6272 d4 = nodeend[axis] - node->frontmin + maxs[axis];
6273 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6275 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;
6276 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;
6277 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;
6278 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6279 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;
6280 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;
6281 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;
6282 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6283 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;
6284 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;
6285 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;
6286 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6287 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6288 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6289 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6290 case 15: /* <<<< */ break;
6293 else if (node->type == BIH_UNORDERED)
6295 // calculate sweep bounds for this node
6296 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6297 VectorSubtract(node->mins, maxs, nodebigmins);
6298 VectorSubtract(node->maxs, mins, nodebigmaxs);
6299 // clip line to this node bounds
6300 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); }
6301 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); }
6302 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); }
6303 // some of the line intersected the enlarged node box
6304 // calculate sweep bounds for this node
6305 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];
6306 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6308 leaf = bih->leafs + node->children[axis];
6309 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6314 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6315 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6317 case BIH_COLLISIONTRIANGLE:
6318 if (!mod_q3bsp_curves_collisions.integer)
6320 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6321 texture = model->data_textures + leaf->textureindex;
6322 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);
6324 case BIH_RENDERTRIANGLE:
6325 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6326 texture = model->data_textures + leaf->textureindex;
6327 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);
6335 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)
6337 colboxbrushf_t thisbrush_start, thisbrush_end;
6338 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6340 // box trace, performed as brush trace
6341 VectorAdd(start, boxmins, boxstartmins);
6342 VectorAdd(start, boxmaxs, boxstartmaxs);
6343 VectorAdd(end, boxmins, boxendmins);
6344 VectorAdd(end, boxmaxs, boxendmaxs);
6345 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6346 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6347 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6351 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6354 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6355 return trace.startsupercontents;
6358 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)
6361 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6363 int hitsupercontents;
6364 VectorSet(end, start[0], start[1], model->normalmins[2]);
6366 memset(trace, 0, sizeof(*trace));
6367 trace->fraction = 1;
6368 trace->realfraction = 1;
6369 trace->hitsupercontentsmask = hitsupercontentsmask;
6371 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6372 hitsupercontents = trace->hitsupercontents;
6373 memset(trace, 0, sizeof(*trace));
6374 trace->fraction = 1;
6375 trace->realfraction = 1;
6376 trace->hitsupercontentsmask = hitsupercontentsmask;
6377 trace->startsupercontents = hitsupercontents;
6381 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6384 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6387 VectorSet(end, start[0], start[1], model->normalmins[2]);
6388 memset(&trace, 0, sizeof(trace));
6390 trace.realfraction = 1;
6391 trace.hitsupercontentsmask = 0;
6392 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6393 return trace.hitsupercontents;
6399 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6404 // find which leaf the point is in
6406 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6407 // point trace the brushes
6408 leaf = (mleaf_t *)node;
6409 for (i = 0;i < leaf->numleafbrushes;i++)
6411 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6412 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6414 brush->markframe = markframe;
6415 Collision_TracePointBrushFloat(trace, point, brush);
6418 // can't do point traces on curves (they have no thickness)
6421 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)
6423 int i, startside, endside;
6424 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6426 msurface_t *surface;
6429 // walk the tree until we hit a leaf, recursing for any split cases
6433 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6435 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6436 node = node->children[1];
6438 // abort if this part of the bsp tree can not be hit by this trace
6439 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6441 plane = node->plane;
6442 // axial planes are much more common than non-axial, so an optimized
6443 // axial case pays off here
6444 if (plane->type < 3)
6446 dist1 = start[plane->type] - plane->dist;
6447 dist2 = end[plane->type] - plane->dist;
6451 dist1 = DotProduct(start, plane->normal) - plane->dist;
6452 dist2 = DotProduct(end, plane->normal) - plane->dist;
6454 startside = dist1 < 0;
6455 endside = dist2 < 0;
6456 if (startside == endside)
6458 // most of the time the line fragment is on one side of the plane
6459 node = node->children[startside];
6463 // line crosses node plane, split the line
6464 dist1 = PlaneDiff(linestart, plane);
6465 dist2 = PlaneDiff(lineend, plane);
6466 midfrac = dist1 / (dist1 - dist2);
6467 VectorLerp(linestart, midfrac, lineend, mid);
6468 // take the near side first
6469 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6470 // if we found an impact on the front side, don't waste time
6471 // exploring the far side
6472 if (midfrac <= trace->realfraction)
6473 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6478 // abort if this part of the bsp tree can not be hit by this trace
6479 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6482 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6483 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6484 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6485 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6486 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6487 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6488 // line trace the brushes
6489 leaf = (mleaf_t *)node;
6491 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6494 for (i = 0;i < leaf->numleafbrushes;i++)
6496 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6497 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6499 brush->markframe = markframe;
6500 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6503 // can't do point traces on curves (they have no thickness)
6504 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6506 // line trace the curves
6507 for (i = 0;i < leaf->numleafsurfaces;i++)
6509 surface = model->data_surfaces + leaf->firstleafsurface[i];
6510 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6512 surface->deprecatedq3collisionmarkframe = markframe;
6513 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);
6519 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)
6525 msurface_t *surface;
6527 float nodesegmentmins[3], nodesegmentmaxs[3];
6528 // walk the tree until we hit a leaf, recursing for any split cases
6532 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6534 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6535 node = node->children[1];
6537 // abort if this part of the bsp tree can not be hit by this trace
6538 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6540 plane = node->plane;
6541 // axial planes are much more common than non-axial, so an optimized
6542 // axial case pays off here
6543 if (plane->type < 3)
6545 // this is an axial plane, compare bounding box directly to it and
6546 // recurse sides accordingly
6547 // recurse down node sides
6548 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6549 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6550 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6551 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6555 // this is a non-axial plane, so check if the start and end boxes
6556 // are both on one side of the plane to handle 'diagonal' cases
6557 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6561 // segment crosses plane
6562 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6565 // if sides == 0 then the trace itself is bogus (Not A Number values),
6566 // in this case we simply pretend the trace hit nothing
6568 return; // ERROR: NAN bounding box!
6569 // take whichever side the segment box is on
6570 node = node->children[sides - 1];
6573 // abort if this part of the bsp tree can not be hit by this trace
6574 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6576 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6577 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6578 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6579 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6580 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6581 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6583 leaf = (mleaf_t *)node;
6585 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6588 for (i = 0;i < leaf->numleafbrushes;i++)
6590 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6591 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6593 brush->markframe = markframe;
6594 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6597 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6599 for (i = 0;i < leaf->numleafsurfaces;i++)
6601 surface = model->data_surfaces + leaf->firstleafsurface[i];
6602 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6604 surface->deprecatedq3collisionmarkframe = markframe;
6605 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);
6612 static int markframe = 0;
6614 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)
6618 memset(trace, 0, sizeof(*trace));
6619 trace->fraction = 1;
6620 trace->realfraction = 1;
6621 trace->hitsupercontentsmask = hitsupercontentsmask;
6622 if (mod_collision_bih.integer)
6623 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6624 else if (model->brush.submodel)
6626 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6627 if (brush->colbrushf)
6628 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6631 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6634 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)
6637 float segmentmins[3], segmentmaxs[3];
6638 msurface_t *surface;
6641 if (VectorCompare(start, end))
6643 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6647 memset(trace, 0, sizeof(*trace));
6648 trace->fraction = 1;
6649 trace->realfraction = 1;
6650 trace->hitsupercontentsmask = hitsupercontentsmask;
6651 segmentmins[0] = min(start[0], end[0]) - 1;
6652 segmentmins[1] = min(start[1], end[1]) - 1;
6653 segmentmins[2] = min(start[2], end[2]) - 1;
6654 segmentmaxs[0] = max(start[0], end[0]) + 1;
6655 segmentmaxs[1] = max(start[1], end[1]) + 1;
6656 segmentmaxs[2] = max(start[2], end[2]) + 1;
6657 if (mod_collision_bih.integer)
6658 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6659 else if (model->brush.submodel)
6661 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6662 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6663 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6664 if (mod_q3bsp_curves_collisions.integer)
6665 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6666 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6667 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);
6670 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6673 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)
6675 float segmentmins[3], segmentmaxs[3];
6677 msurface_t *surface;
6680 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6682 if (VectorCompare(start->mins, end->mins))
6683 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6685 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6689 // box trace, performed as brush trace
6690 memset(trace, 0, sizeof(*trace));
6691 trace->fraction = 1;
6692 trace->realfraction = 1;
6693 trace->hitsupercontentsmask = hitsupercontentsmask;
6694 segmentmins[0] = min(start->mins[0], end->mins[0]);
6695 segmentmins[1] = min(start->mins[1], end->mins[1]);
6696 segmentmins[2] = min(start->mins[2], end->mins[2]);
6697 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6698 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6699 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6700 if (mod_collision_bih.integer)
6701 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6702 else if (model->brush.submodel)
6704 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6705 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6706 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6707 if (mod_q3bsp_curves_collisions.integer)
6708 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6709 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6710 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);
6713 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6716 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)
6718 colboxbrushf_t thisbrush_start, thisbrush_end;
6719 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6721 // box trace, performed as brush trace
6722 VectorAdd(start, boxmins, boxstartmins);
6723 VectorAdd(start, boxmaxs, boxstartmaxs);
6724 VectorAdd(end, boxmins, boxendmins);
6725 VectorAdd(end, boxmaxs, boxendmaxs);
6726 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6727 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6728 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6731 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6734 int supercontents = 0;
6736 if (mod_collision_bih.integer)
6739 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6740 supercontents = trace.startsupercontents;
6742 // test if the point is inside each brush
6743 else if (model->brush.submodel)
6745 // submodels are effectively one leaf
6746 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6747 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6748 supercontents |= brush->colbrushf->supercontents;
6752 mnode_t *node = model->brush.data_nodes;
6754 // find which leaf the point is in
6756 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6757 leaf = (mleaf_t *)node;
6758 // now check the brushes in the leaf
6759 for (i = 0;i < leaf->numleafbrushes;i++)
6761 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6762 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6763 supercontents |= brush->colbrushf->supercontents;
6766 return supercontents;
6769 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)
6771 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
6775 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6783 int nummodelbrushes = model->nummodelbrushes;
6784 int nummodelsurfaces = model->nummodelsurfaces;
6786 const int *collisionelement3i;
6787 const float *collisionvertex3f;
6788 const int *renderelement3i;
6789 const float *rendervertex3f;
6790 bih_leaf_t *bihleafs;
6791 bih_node_t *bihnodes;
6793 int *temp_leafsortscratch;
6794 const msurface_t *surface;
6795 const q3mbrush_t *brush;
6797 // find out how many BIH leaf nodes we need
6799 if (userendersurfaces)
6801 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6802 bihnumleafs += surface->num_triangles;
6806 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6807 if (brush->colbrushf)
6809 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6811 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6812 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
6814 bihnumleafs += surface->num_collisiontriangles;
6821 // allocate the memory for the BIH leaf nodes
6822 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6824 // now populate the BIH leaf nodes
6827 // add render surfaces
6828 renderelement3i = model->surfmesh.data_element3i;
6829 rendervertex3f = model->surfmesh.data_vertex3f;
6830 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6832 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6834 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6836 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6837 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6838 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6839 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6840 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6841 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6842 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6843 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6844 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6845 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6850 if (!userendersurfaces)
6852 // add collision brushes
6853 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6855 if (!brush->colbrushf)
6857 bihleafs[bihleafindex].type = BIH_BRUSH;
6858 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6859 bihleafs[bihleafindex].surfaceindex = -1;
6860 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6861 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6862 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6866 // add collision surfaces
6867 collisionelement3i = model->brush.data_collisionelement3i;
6868 collisionvertex3f = model->brush.data_collisionvertex3f;
6869 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6871 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6873 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
6874 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6875 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6876 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6877 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6878 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6879 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6880 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6881 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6882 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6888 // allocate buffers for the produced and temporary data
6889 bihmaxnodes = bihnumleafs + 1;
6890 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6891 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6892 temp_leafsortscratch = temp_leafsort + bihnumleafs;
6895 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6897 // we're done with the temporary data
6898 Mem_Free(temp_leafsort);
6900 // resize the BIH nodes array if it over-allocated
6901 if (out->maxnodes > out->numnodes)
6903 out->maxnodes = out->numnodes;
6904 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
6910 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6912 int supercontents = 0;
6913 if (nativecontents & CONTENTSQ3_SOLID)
6914 supercontents |= SUPERCONTENTS_SOLID;
6915 if (nativecontents & CONTENTSQ3_WATER)
6916 supercontents |= SUPERCONTENTS_WATER;
6917 if (nativecontents & CONTENTSQ3_SLIME)
6918 supercontents |= SUPERCONTENTS_SLIME;
6919 if (nativecontents & CONTENTSQ3_LAVA)
6920 supercontents |= SUPERCONTENTS_LAVA;
6921 if (nativecontents & CONTENTSQ3_BODY)
6922 supercontents |= SUPERCONTENTS_BODY;
6923 if (nativecontents & CONTENTSQ3_CORPSE)
6924 supercontents |= SUPERCONTENTS_CORPSE;
6925 if (nativecontents & CONTENTSQ3_NODROP)
6926 supercontents |= SUPERCONTENTS_NODROP;
6927 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6928 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6929 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6930 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6931 if (nativecontents & CONTENTSQ3_DONOTENTER)
6932 supercontents |= SUPERCONTENTS_DONOTENTER;
6933 if (nativecontents & CONTENTSQ3_BOTCLIP)
6934 supercontents |= SUPERCONTENTS_BOTCLIP;
6935 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6936 supercontents |= SUPERCONTENTS_OPAQUE;
6937 return supercontents;
6940 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6942 int nativecontents = 0;
6943 if (supercontents & SUPERCONTENTS_SOLID)
6944 nativecontents |= CONTENTSQ3_SOLID;
6945 if (supercontents & SUPERCONTENTS_WATER)
6946 nativecontents |= CONTENTSQ3_WATER;
6947 if (supercontents & SUPERCONTENTS_SLIME)
6948 nativecontents |= CONTENTSQ3_SLIME;
6949 if (supercontents & SUPERCONTENTS_LAVA)
6950 nativecontents |= CONTENTSQ3_LAVA;
6951 if (supercontents & SUPERCONTENTS_BODY)
6952 nativecontents |= CONTENTSQ3_BODY;
6953 if (supercontents & SUPERCONTENTS_CORPSE)
6954 nativecontents |= CONTENTSQ3_CORPSE;
6955 if (supercontents & SUPERCONTENTS_NODROP)
6956 nativecontents |= CONTENTSQ3_NODROP;
6957 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6958 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6959 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6960 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6961 if (supercontents & SUPERCONTENTS_DONOTENTER)
6962 nativecontents |= CONTENTSQ3_DONOTENTER;
6963 if (supercontents & SUPERCONTENTS_BOTCLIP)
6964 nativecontents |= CONTENTSQ3_BOTCLIP;
6965 if (!(supercontents & SUPERCONTENTS_OPAQUE))
6966 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6967 return nativecontents;
6970 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6975 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6976 node = node->children[1];
6978 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6979 if (loadmodel->brush.num_leafs < numleafs)
6980 loadmodel->brush.num_leafs = numleafs;
6983 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6986 q3dheader_t *header;
6987 float corner[3], yawradius, modelradius;
6989 mod->modeldatatypestring = "Q3BSP";
6991 mod->type = mod_brushq3;
6992 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6995 header = (q3dheader_t *)buffer;
6996 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6997 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6999 i = LittleLong(header->version);
7000 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7001 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7003 mod->soundfromcenter = true;
7004 mod->TraceBox = Mod_Q3BSP_TraceBox;
7005 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7006 mod->TraceLine = Mod_Q3BSP_TraceLine;
7007 mod->TracePoint = Mod_Q3BSP_TracePoint;
7008 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7009 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7010 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7011 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7012 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7013 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7014 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7015 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7016 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7017 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7018 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7019 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7020 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7021 mod->brush.AmbientSoundLevelsForPoint = NULL;
7022 mod->brush.RoundUpToHullSize = NULL;
7023 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7024 mod->Draw = R_Q1BSP_Draw;
7025 mod->DrawDepth = R_Q1BSP_DrawDepth;
7026 mod->DrawDebug = R_Q1BSP_DrawDebug;
7027 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7028 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7029 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7030 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7031 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7032 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7033 mod->DrawLight = R_Q1BSP_DrawLight;
7035 mod_base = (unsigned char *)header;
7037 // swap all the lumps
7038 header->ident = LittleLong(header->ident);
7039 header->version = LittleLong(header->version);
7040 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7041 for (i = 0;i < lumps;i++)
7043 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7044 if((char *) bufferend < (char *) buffer + j)
7045 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7046 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7047 if((char *) bufferend < (char *) buffer + j)
7048 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7051 * NO, do NOT clear them!
7052 * they contain actual data referenced by other stuff.
7053 * Instead, before using the advertisements lump, check header->versio
7055 * Sorry, but otherwise it breaks memory of the first lump.
7056 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7058 header->lumps[i].fileofs = 0;
7059 header->lumps[i].filelen = 0;
7063 mod->brush.qw_md4sum = 0;
7064 mod->brush.qw_md4sum2 = 0;
7065 for (i = 0;i < lumps;i++)
7067 if (i == Q3LUMP_ENTITIES)
7069 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7070 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7072 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7074 // all this checksumming can take a while, so let's send keepalives here too
7075 CL_KeepaliveMessage(false);
7078 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7079 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7080 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7081 if (header->version == Q3BSPVERSION_IG)
7082 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7084 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7085 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7086 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7087 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7088 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7089 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7090 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7091 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7092 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7093 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7094 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7095 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7096 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7097 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7098 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7100 // the MakePortals code works fine on the q3bsp data as well
7101 if (mod_bsp_portalize.integer)
7102 Mod_Q1BSP_MakePortals();
7104 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7105 loadmodel->brush.supportwateralpha = true;
7107 // make a single combined shadow mesh to allow optimized shadow volume creation
7108 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7110 loadmodel->brush.num_leafs = 0;
7111 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7113 if (loadmodel->brush.numsubmodels)
7114 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7117 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7122 // duplicate the basic information
7123 dpsnprintf(name, sizeof(name), "*%i", i);
7124 mod = Mod_FindName(name, loadmodel->name);
7125 // copy the base model to this one
7127 // rename the clone back to its proper name
7128 strlcpy(mod->name, name, sizeof(mod->name));
7129 mod->brush.parentmodel = loadmodel;
7130 // textures and memory belong to the main model
7131 mod->texturepool = NULL;
7132 mod->mempool = NULL;
7133 mod->brush.GetPVS = NULL;
7134 mod->brush.FatPVS = NULL;
7135 mod->brush.BoxTouchingPVS = NULL;
7136 mod->brush.BoxTouchingLeafPVS = NULL;
7137 mod->brush.BoxTouchingVisibleLeafs = NULL;
7138 mod->brush.FindBoxClusters = NULL;
7139 mod->brush.LightPoint = NULL;
7140 mod->brush.AmbientSoundLevelsForPoint = NULL;
7142 mod->brush.submodel = i;
7143 if (loadmodel->brush.submodels)
7144 loadmodel->brush.submodels[i] = mod;
7146 // make the model surface list (used by shadowing/lighting)
7147 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7148 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7149 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7150 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7151 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7152 Mod_MakeSortedSurfaces(mod);
7154 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7155 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7156 // enlarge the bounding box to enclose all geometry of this model,
7157 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7158 // which can in turn mess up the farclip (as well as culling when
7159 // outside the level - an unimportant concern)
7161 //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]);
7162 for (j = 0;j < mod->nummodelsurfaces;j++)
7164 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7165 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7167 if (!surface->num_vertices)
7169 for (k = 0;k < surface->num_vertices;k++, v += 3)
7171 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7172 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7173 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7174 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7175 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7176 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7179 //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]);
7180 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7181 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7182 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7183 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7184 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7185 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7186 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7187 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7188 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7189 mod->yawmins[2] = mod->normalmins[2];
7190 mod->yawmaxs[2] = mod->normalmaxs[2];
7191 mod->radius = modelradius;
7192 mod->radius2 = modelradius * modelradius;
7194 // this gets altered below if sky or water is used
7195 mod->DrawSky = NULL;
7196 mod->DrawAddWaterPlanes = NULL;
7198 for (j = 0;j < mod->nummodelsurfaces;j++)
7199 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7201 if (j < mod->nummodelsurfaces)
7202 mod->DrawSky = R_Q1BSP_DrawSky;
7204 for (j = 0;j < mod->nummodelsurfaces;j++)
7205 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7207 if (j < mod->nummodelsurfaces)
7208 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7210 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7211 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7213 // generate VBOs and other shared data before cloning submodels
7218 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);
7221 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7223 int i = LittleLong(((int *)buffer)[1]);
7224 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7225 Mod_Q3BSP_Load(mod,buffer, bufferend);
7226 else if (i == Q2BSPVERSION)
7227 Mod_Q2BSP_Load(mod,buffer, bufferend);
7229 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7232 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7234 Host_Error("Mod_MAP_Load: not yet implemented");
7237 typedef struct objvertex_s
7248 static unsigned char nobsp_pvs[1] = {1};
7250 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7252 const char *textbase = (char *)buffer, *text = textbase;
7256 char materialname[MAX_QPATH];
7257 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7258 int index1, index2, index3;
7259 objvertex_t vfirst, vprev, vcurrent;
7262 int numtriangles = 0;
7263 int maxtriangles = 0;
7264 objvertex_t *vertices = NULL;
7266 int maxtextures = 0, numtextures = 0, textureindex = 0;
7267 int maxv = 0, numv = 1;
7268 int maxvt = 0, numvt = 1;
7269 int maxvn = 0, numvn = 1;
7270 char *texturenames = NULL;
7271 float dist, modelradius, modelyawradius, yawradius;
7278 objvertex_t *thisvertex = NULL;
7279 int vertexhashindex;
7280 int *vertexhashtable = NULL;
7281 objvertex_t *vertexhashdata = NULL;
7282 objvertex_t *vdata = NULL;
7283 int vertexhashsize = 0;
7284 int vertexhashcount = 0;
7285 skinfile_t *skinfiles = NULL;
7286 unsigned char *data = NULL;
7287 int *submodelfirstsurface;
7288 msurface_t *surface;
7289 msurface_t *tempsurfaces;
7291 memset(&vfirst, 0, sizeof(vfirst));
7292 memset(&vprev, 0, sizeof(vprev));
7293 memset(&vcurrent, 0, sizeof(vcurrent));
7295 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7297 loadmodel->modeldatatypestring = "OBJ";
7299 loadmodel->type = mod_obj;
7300 loadmodel->soundfromcenter = true;
7301 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7302 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7303 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7304 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7305 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7306 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7307 loadmodel->brush.TraceLineOfSight = NULL;
7308 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7309 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7310 loadmodel->brush.GetPVS = NULL;
7311 loadmodel->brush.FatPVS = NULL;
7312 loadmodel->brush.BoxTouchingPVS = NULL;
7313 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7314 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7315 loadmodel->brush.FindBoxClusters = NULL;
7316 loadmodel->brush.LightPoint = NULL;
7317 loadmodel->brush.FindNonSolidLocation = NULL;
7318 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7319 loadmodel->brush.RoundUpToHullSize = NULL;
7320 loadmodel->brush.PointInLeaf = NULL;
7321 loadmodel->Draw = R_Q1BSP_Draw;
7322 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7323 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7324 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7325 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7326 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7327 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7328 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7329 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7330 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7332 skinfiles = Mod_LoadSkinFiles();
7333 if (loadmodel->numskins < 1)
7334 loadmodel->numskins = 1;
7336 // make skinscenes for the skins (no groups)
7337 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7338 for (i = 0;i < loadmodel->numskins;i++)
7340 loadmodel->skinscenes[i].firstframe = i;
7341 loadmodel->skinscenes[i].framecount = 1;
7342 loadmodel->skinscenes[i].loop = true;
7343 loadmodel->skinscenes[i].framerate = 10;
7349 // we always have model 0, i.e. the first "submodel"
7350 loadmodel->brush.numsubmodels = 1;
7352 // parse the OBJ text now
7355 static char emptyarg[1] = "";
7360 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7361 line[linelen] = text[linelen];
7363 for (argc = 0;argc < 4;argc++)
7364 argv[argc] = emptyarg;
7367 while (*s == ' ' || *s == '\t')
7377 while (*s == ' ' || *s == '\t')
7387 if (argv[0][0] == '#')
7389 if (!strcmp(argv[0], "v"))
7393 maxv = max(maxv * 2, 1024);
7394 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7396 v[numv*3+0] = atof(argv[1]);
7397 v[numv*3+2] = atof(argv[2]);
7398 v[numv*3+1] = atof(argv[3]);
7401 else if (!strcmp(argv[0], "vt"))
7405 maxvt = max(maxvt * 2, 1024);
7406 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7408 vt[numvt*2+0] = atof(argv[1]);
7409 vt[numvt*2+1] = 1-atof(argv[2]);
7412 else if (!strcmp(argv[0], "vn"))
7416 maxvn = max(maxvn * 2, 1024);
7417 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7419 vn[numvn*3+0] = atof(argv[1]);
7420 vn[numvn*3+2] = atof(argv[2]);
7421 vn[numvn*3+1] = atof(argv[3]);
7424 else if (!strcmp(argv[0], "f"))
7428 if (maxtextures <= numtextures)
7430 maxtextures = max(maxtextures * 2, 256);
7431 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7433 textureindex = numtextures++;
7434 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7436 for (j = 1;j < argc;j++)
7438 index1 = atoi(argv[j]);
7439 while(argv[j][0] && argv[j][0] != '/')
7443 index2 = atoi(argv[j]);
7444 while(argv[j][0] && argv[j][0] != '/')
7448 index3 = atoi(argv[j]);
7449 // negative refers to a recent vertex
7450 // zero means not specified
7451 // positive means an absolute vertex index
7453 index1 = numv - index1;
7455 index2 = numvt - index2;
7457 index3 = numvn - index3;
7458 vcurrent.nextindex = -1;
7459 vcurrent.textureindex = textureindex;
7460 vcurrent.submodelindex = submodelindex;
7461 if (v && index1 >= 0 && index1 < numv)
7462 VectorCopy(v + 3*index1, vcurrent.v);
7463 if (vt && index2 >= 0 && index2 < numvt)
7464 Vector2Copy(vt + 2*index2, vcurrent.vt);
7465 if (vn && index3 >= 0 && index3 < numvn)
7466 VectorCopy(vn + 3*index3, vcurrent.vn);
7467 if (numtriangles == 0)
7469 VectorCopy(vcurrent.v, mins);
7470 VectorCopy(vcurrent.v, maxs);
7474 mins[0] = min(mins[0], vcurrent.v[0]);
7475 mins[1] = min(mins[1], vcurrent.v[1]);
7476 mins[2] = min(mins[2], vcurrent.v[2]);
7477 maxs[0] = max(maxs[0], vcurrent.v[0]);
7478 maxs[1] = max(maxs[1], vcurrent.v[1]);
7479 maxs[2] = max(maxs[2], vcurrent.v[2]);
7485 if (maxtriangles <= numtriangles)
7487 maxtriangles = max(maxtriangles * 2, 32768);
7488 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7490 vertices[numtriangles*3+0] = vfirst;
7491 vertices[numtriangles*3+1] = vprev;
7492 vertices[numtriangles*3+2] = vcurrent;
7498 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7500 submodelindex = atof(argv[1]);
7501 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7503 else if (!strcmp(argv[0], "usemtl"))
7505 for (i = 0;i < numtextures;i++)
7506 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7508 if (i < numtextures)
7512 if (maxtextures <= numtextures)
7514 maxtextures = max(maxtextures * 2, 256);
7515 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7517 textureindex = numtextures++;
7518 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7523 // now that we have the OBJ data loaded as-is, we can convert it
7525 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7526 VectorCopy(mins, loadmodel->normalmins);
7527 VectorCopy(maxs, loadmodel->normalmaxs);
7528 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7529 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7530 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7531 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7532 modelradius = modelyawradius + modelradius * modelradius;
7533 modelyawradius = sqrt(modelyawradius);
7534 modelradius = sqrt(modelradius);
7535 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7536 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7537 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7538 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7539 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7540 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7541 loadmodel->radius = modelradius;
7542 loadmodel->radius2 = modelradius * modelradius;
7544 // allocate storage for triangles
7545 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7546 // allocate vertex hash structures to build an optimal vertex subset
7547 vertexhashsize = numtriangles*2;
7548 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7549 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7550 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7551 vertexhashcount = 0;
7553 // gather surface stats for assigning vertex/triangle ranges
7557 loadmodel->num_surfaces = 0;
7558 // allocate storage for the worst case number of surfaces, later we resize
7559 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7560 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7561 surface = tempsurfaces;
7562 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7564 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7565 for (textureindex = 0;textureindex < numtextures;textureindex++)
7567 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7569 thisvertex = vertices + vertexindex;
7570 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7573 // skip the surface creation if there are no triangles for it
7574 if (vertexindex == numtriangles*3)
7576 // create a surface for these vertices
7577 surfacevertices = 0;
7578 surfaceelements = 0;
7579 // we hack in a texture index in the surface to be fixed up later...
7580 surface->texture = (texture_t *)((size_t)textureindex);
7581 // calculate bounds as we go
7582 VectorCopy(thisvertex->v, surface->mins);
7583 VectorCopy(thisvertex->v, surface->maxs);
7584 for (;vertexindex < numtriangles*3;vertexindex++)
7586 thisvertex = vertices + vertexindex;
7587 if (thisvertex->submodelindex != submodelindex)
7589 if (thisvertex->textureindex != textureindex)
7591 // add vertex to surface bounds
7592 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7593 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7594 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7595 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7596 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7597 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7598 // add the vertex if it is not found in the merged set, and
7599 // get its index (triangle element) for the surface
7600 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7601 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7603 vdata = vertexhashdata + i;
7604 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7609 i = vertexhashcount++;
7610 vdata = vertexhashdata + i;
7611 *vdata = *thisvertex;
7612 vdata->nextindex = vertexhashtable[vertexhashindex];
7613 vertexhashtable[vertexhashindex] = i;
7616 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7619 surfacetriangles = surfaceelements / 3;
7620 surface->num_vertices = surfacevertices;
7621 surface->num_triangles = surfacetriangles;
7622 surface->num_firstvertex = firstvertex;
7623 surface->num_firsttriangle = firsttriangle;
7624 firstvertex += surface->num_vertices;
7625 firsttriangle += surface->num_triangles;
7627 loadmodel->num_surfaces++;
7630 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7631 numvertices = firstvertex;
7632 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7633 tempsurfaces = NULL;
7635 // allocate storage for final mesh data
7636 loadmodel->num_textures = numtextures * loadmodel->numskins;
7637 loadmodel->num_texturesperskin = numtextures;
7638 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 *));
7639 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7640 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7641 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7642 loadmodel->surfmesh.num_vertices = numvertices;
7643 loadmodel->surfmesh.num_triangles = numtriangles;
7644 if (r_enableshadowvolumes.integer)
7645 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7646 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7647 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7648 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7649 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7650 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7651 if (loadmodel->surfmesh.num_vertices <= 65536)
7652 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7654 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7656 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7657 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7658 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7661 // load the textures
7662 for (textureindex = 0;textureindex < numtextures;textureindex++)
7663 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7664 Mod_FreeSkinFiles(skinfiles);
7666 // set the surface textures to their real values now that we loaded them...
7667 for (i = 0;i < loadmodel->num_surfaces;i++)
7668 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7672 Mem_Free(texturenames);
7676 Mem_Free(vertexhashtable);
7677 Mem_Free(vertexhashdata);
7679 // make a single combined shadow mesh to allow optimized shadow volume creation
7680 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7682 // compute all the mesh information that was not loaded from the file
7683 if (loadmodel->surfmesh.data_element3s)
7684 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7685 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7686 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7687 // generate normals if the file did not have them
7688 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7689 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);
7690 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);
7691 if (loadmodel->surfmesh.data_neighbor3i)
7692 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7694 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7695 loadmodel->brush.num_visleafs = 1;
7696 loadmodel->brush.num_leafs = 1;
7697 loadmodel->brush.num_nodes = 0;
7698 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7699 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7700 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7701 loadmodel->brush.num_pvsclusters = 1;
7702 loadmodel->brush.num_pvsclusterbytes = 1;
7703 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7704 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7705 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7706 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7707 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7708 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7709 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7710 loadmodel->brush.data_leafs->clusterindex = 0;
7711 loadmodel->brush.data_leafs->areaindex = 0;
7712 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7713 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7714 loadmodel->brush.data_leafs->numleafbrushes = 0;
7715 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7716 loadmodel->brush.supportwateralpha = true;
7718 if (loadmodel->brush.numsubmodels)
7719 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7722 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7727 // duplicate the basic information
7728 dpsnprintf(name, sizeof(name), "*%i", i);
7729 mod = Mod_FindName(name, loadmodel->name);
7730 // copy the base model to this one
7732 // rename the clone back to its proper name
7733 strlcpy(mod->name, name, sizeof(mod->name));
7734 mod->brush.parentmodel = loadmodel;
7735 // textures and memory belong to the main model
7736 mod->texturepool = NULL;
7737 mod->mempool = NULL;
7738 mod->brush.GetPVS = NULL;
7739 mod->brush.FatPVS = NULL;
7740 mod->brush.BoxTouchingPVS = NULL;
7741 mod->brush.BoxTouchingLeafPVS = NULL;
7742 mod->brush.BoxTouchingVisibleLeafs = NULL;
7743 mod->brush.FindBoxClusters = NULL;
7744 mod->brush.LightPoint = NULL;
7745 mod->brush.AmbientSoundLevelsForPoint = NULL;
7747 mod->brush.submodel = i;
7748 if (loadmodel->brush.submodels)
7749 loadmodel->brush.submodels[i] = mod;
7751 // make the model surface list (used by shadowing/lighting)
7752 mod->firstmodelsurface = submodelfirstsurface[i];
7753 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7754 mod->firstmodelbrush = 0;
7755 mod->nummodelbrushes = 0;
7756 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
7757 Mod_MakeSortedSurfaces(mod);
7759 VectorClear(mod->normalmins);
7760 VectorClear(mod->normalmaxs);
7762 for (j = 0;j < mod->nummodelsurfaces;j++)
7764 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7765 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7767 if (!surface->num_vertices)
7772 VectorCopy(v, mod->normalmins);
7773 VectorCopy(v, mod->normalmaxs);
7775 for (k = 0;k < surface->num_vertices;k++, v += 3)
7777 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7778 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7779 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7780 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7781 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7782 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7785 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7786 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7787 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7788 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7789 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7790 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7791 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7792 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7793 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7794 mod->yawmins[2] = mod->normalmins[2];
7795 mod->yawmaxs[2] = mod->normalmaxs[2];
7796 mod->radius = modelradius;
7797 mod->radius2 = modelradius * modelradius;
7799 // this gets altered below if sky or water is used
7800 mod->DrawSky = NULL;
7801 mod->DrawAddWaterPlanes = NULL;
7803 for (j = 0;j < mod->nummodelsurfaces;j++)
7804 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7806 if (j < mod->nummodelsurfaces)
7807 mod->DrawSky = R_Q1BSP_DrawSky;
7809 for (j = 0;j < mod->nummodelsurfaces;j++)
7810 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7812 if (j < mod->nummodelsurfaces)
7813 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7815 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
7816 mod->render_bih = mod->collision_bih;
7818 // generate VBOs and other shared data before cloning submodels
7823 Mem_Free(submodelfirstsurface);
7825 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);
7828 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
7830 // we already have done PVS culling at this point...
7831 // so we don't need to do it again.
7834 vec3_t testorigin, mins, maxs;
7836 testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
7837 testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
7838 testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
7840 if(model->brush.TraceLineOfSight(model, eye, testorigin))
7843 // expand the box a little
7844 mins[0] = (t+1) * minsX[0] - t * maxsX[0];
7845 maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
7846 mins[1] = (t+1) * minsX[1] - t * maxsX[1];
7847 maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
7848 mins[2] = (t+1) * minsX[2] - t * maxsX[2];
7849 maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
7851 for(i = 0; i != numsamples; ++i)
7853 testorigin[0] = lhrandom(mins[0], maxs[0]);
7854 testorigin[1] = lhrandom(mins[1], maxs[1]);
7855 testorigin[2] = lhrandom(mins[2], maxs[2]);
7857 if(model->brush.TraceLineOfSight(model, eye, testorigin))