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 r_fxaa = {CVAR_SAVE, "r_fxaa", "0", "fast approximate anti aliasing"};
43 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"};
44 cvar_t mod_obj_orientation = {0, "mod_obj_orientation", "1", "fix orientation of OBJ models to the usual conventions (if zero, use coordinates as is)"};
45 cvar_t mod_q2bsp_littransparentsurfaces = {0, "mod_q2bsp_littransparentsurfaces", "0", "allows lighting on rain in 3v3gloom3 and other cases of transparent surfaces that have lightmaps that were ignored by quake2"};
46 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
47 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)"};
48 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)"};
49 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
50 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
51 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, ..."};
52 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)"};
53 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
54 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
55 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"};
56 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
57 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
58 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
59 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
60 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"};
61 cvar_t mod_q3shader_force_terrain_alphaflag = {0, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
63 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)"};
64 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"};
65 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"};
67 static texture_t mod_q1bsp_texture_solid;
68 static texture_t mod_q1bsp_texture_sky;
69 static texture_t mod_q1bsp_texture_lava;
70 static texture_t mod_q1bsp_texture_slime;
71 static texture_t mod_q1bsp_texture_water;
73 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end);
75 void Mod_BrushInit(void)
77 // Cvar_RegisterVariable(&r_subdivide_size);
78 Cvar_RegisterVariable(&mod_bsp_portalize);
79 Cvar_RegisterVariable(&r_novis);
80 Cvar_RegisterVariable(&r_nosurftextures);
81 Cvar_RegisterVariable(&r_subdivisions_tolerance);
82 Cvar_RegisterVariable(&r_subdivisions_mintess);
83 Cvar_RegisterVariable(&r_subdivisions_maxtess);
84 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
85 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
86 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
87 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
88 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
89 Cvar_RegisterVariable(&r_trippy);
90 Cvar_RegisterVariable(&r_fxaa);
91 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
92 Cvar_RegisterVariable(&mod_obj_orientation);
93 Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
94 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
95 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
96 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
97 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
98 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
99 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
100 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
101 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
102 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
103 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
104 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
105 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
106 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
107 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
108 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
109 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
110 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
111 Cvar_RegisterVariable(&mod_collision_bih);
112 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
114 // these games were made for older DP engines and are no longer
115 // maintained; use this hack to show their textures properly
116 if(gamemode == GAME_NEXUIZ)
117 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
119 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
120 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
121 mod_q1bsp_texture_solid.surfaceflags = 0;
122 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
124 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
125 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
126 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
127 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
129 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
130 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
131 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
132 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
134 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
135 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
136 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
137 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
139 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
140 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
141 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
142 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
145 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
152 // LordHavoc: modified to start at first clip node,
153 // in other words: first node of the (sub)model
154 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
156 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
158 return (mleaf_t *)node;
161 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
165 leaf = Mod_Q1BSP_PointInLeaf(model, p);
168 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
171 memcpy(out, leaf->ambient_sound_level, i);
177 memset(out, 0, outsize);
180 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
183 int nodestackindex = 0;
184 mnode_t *node, *nodestack[1024];
185 if (!model->brush.num_pvsclusters)
187 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
193 // node - recurse down the BSP tree
194 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
198 return -1; // ERROR: NAN bounding box!
199 // box is on one side of plane, take that path
200 node = node->children[sides-1];
204 // box crosses plane, take one path and remember the other
205 if (nodestackindex < 1024)
206 nodestack[nodestackindex++] = node->children[0];
207 node = node->children[1];
213 // leaf - add clusterindex to list
214 if (numclusters < maxclusters)
215 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
219 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
223 if (nodestackindex < 1024)
224 nodestack[nodestackindex++] = node->children[0];
225 node = node->children[1];
230 // leaf - add clusterindex to list
231 if (numclusters < maxclusters)
232 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
237 // try another path we didn't take earlier
238 if (nodestackindex == 0)
240 node = nodestack[--nodestackindex];
242 // return number of clusters found (even if more than the maxclusters)
246 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
248 int nodestackindex = 0;
249 mnode_t *node, *nodestack[1024];
250 if (!model->brush.num_pvsclusters)
252 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
258 // node - recurse down the BSP tree
259 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
263 return -1; // ERROR: NAN bounding box!
264 // box is on one side of plane, take that path
265 node = node->children[sides-1];
269 // box crosses plane, take one path and remember the other
270 if (nodestackindex < 1024)
271 nodestack[nodestackindex++] = node->children[0];
272 node = node->children[1];
278 // leaf - check cluster bit
279 int clusterindex = ((mleaf_t *)node)->clusterindex;
280 if (CHECKPVSBIT(pvs, clusterindex))
282 // it is visible, return immediately with the news
287 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
291 if (nodestackindex < 1024)
292 nodestack[nodestackindex++] = node->children[0];
293 node = node->children[1];
298 // leaf - check cluster bit
299 int clusterindex = ((mleaf_t *)node)->clusterindex;
300 if (CHECKPVSBIT(pvs, clusterindex))
302 // it is visible, return immediately with the news
308 // nothing to see here, try another path we didn't take earlier
309 if (nodestackindex == 0)
311 node = nodestack[--nodestackindex];
317 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
319 int nodestackindex = 0;
320 mnode_t *node, *nodestack[1024];
321 if (!model->brush.num_leafs)
323 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
329 // node - recurse down the BSP tree
330 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
334 return -1; // ERROR: NAN bounding box!
335 // box is on one side of plane, take that path
336 node = node->children[sides-1];
340 // box crosses plane, take one path and remember the other
341 if (nodestackindex < 1024)
342 nodestack[nodestackindex++] = node->children[0];
343 node = node->children[1];
349 // leaf - check cluster bit
350 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
351 if (CHECKPVSBIT(pvs, clusterindex))
353 // it is visible, return immediately with the news
358 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
362 if (nodestackindex < 1024)
363 nodestack[nodestackindex++] = node->children[0];
364 node = node->children[1];
369 // leaf - check cluster bit
370 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
371 if (CHECKPVSBIT(pvs, clusterindex))
373 // it is visible, return immediately with the news
379 // nothing to see here, try another path we didn't take earlier
380 if (nodestackindex == 0)
382 node = nodestack[--nodestackindex];
388 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
390 int nodestackindex = 0;
391 mnode_t *node, *nodestack[1024];
392 if (!model->brush.num_leafs)
394 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
400 // node - recurse down the BSP tree
401 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
405 return -1; // ERROR: NAN bounding box!
406 // box is on one side of plane, take that path
407 node = node->children[sides-1];
411 // box crosses plane, take one path and remember the other
412 if (nodestackindex < 1024)
413 nodestack[nodestackindex++] = node->children[0];
414 node = node->children[1];
420 // leaf - check if it is visible
421 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
423 // it is visible, return immediately with the news
428 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
432 if (nodestackindex < 1024)
433 nodestack[nodestackindex++] = node->children[0];
434 node = node->children[1];
439 // leaf - check if it is visible
440 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
442 // it is visible, return immediately with the news
448 // nothing to see here, try another path we didn't take earlier
449 if (nodestackindex == 0)
451 node = nodestack[--nodestackindex];
457 typedef struct findnonsolidlocationinfo_s
460 vec3_t absmin, absmax;
466 findnonsolidlocationinfo_t;
468 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
471 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
473 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
474 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
475 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
476 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
477 VectorSubtract(vert[1], vert[0], edge[0]);
478 VectorSubtract(vert[2], vert[1], edge[1]);
479 CrossProduct(edge[1], edge[0], facenormal);
480 if (facenormal[0] || facenormal[1] || facenormal[2])
482 VectorNormalize(facenormal);
483 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
484 if (f <= info->bestdist && f >= -info->bestdist)
486 VectorSubtract(vert[0], vert[2], edge[2]);
487 VectorNormalize(edge[0]);
488 VectorNormalize(edge[1]);
489 VectorNormalize(edge[2]);
490 CrossProduct(facenormal, edge[0], edgenormal[0]);
491 CrossProduct(facenormal, edge[1], edgenormal[1]);
492 CrossProduct(facenormal, edge[2], edgenormal[2]);
494 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
495 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
496 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
498 // we got lucky, the center is within the face
499 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
503 if (info->bestdist > dist)
505 info->bestdist = dist;
506 VectorScale(facenormal, (info->radius - -dist), info->nudge);
511 if (info->bestdist > dist)
513 info->bestdist = dist;
514 VectorScale(facenormal, (info->radius - dist), info->nudge);
520 // check which edge or vertex the center is nearest
521 for (i = 0;i < 3;i++)
523 f = DotProduct(info->center, edge[i]);
524 if (f >= DotProduct(vert[0], edge[i])
525 && f <= DotProduct(vert[1], edge[i]))
528 VectorMA(info->center, -f, edge[i], point);
529 dist = sqrt(DotProduct(point, point));
530 if (info->bestdist > dist)
532 info->bestdist = dist;
533 VectorScale(point, (info->radius / dist), info->nudge);
535 // skip both vertex checks
536 // (both are further away than this edge)
541 // not on edge, check first vertex of edge
542 VectorSubtract(info->center, vert[i], point);
543 dist = sqrt(DotProduct(point, point));
544 if (info->bestdist > dist)
546 info->bestdist = dist;
547 VectorScale(point, (info->radius / dist), info->nudge);
556 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
558 int surfacenum, k, *mark;
560 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
562 surface = info->model->data_surfaces + *mark;
563 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
565 if(surface->deprecatedq3num_bboxstride > 0)
568 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
569 for(i = 0; i < cnt; ++i)
571 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
573 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
575 tri = i * surface->deprecatedq3num_bboxstride + k;
576 if(tri >= surface->num_triangles)
578 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
585 for (k = 0;k < surface->num_triangles;k++)
587 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
594 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
598 float f = PlaneDiff(info->center, node->plane);
599 if (f >= -info->bestdist)
600 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
601 if (f <= info->bestdist)
602 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
606 if (((mleaf_t *)node)->numleafsurfaces)
607 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
611 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
614 findnonsolidlocationinfo_t info;
620 VectorCopy(in, info.center);
621 info.radius = radius;
626 VectorClear(info.nudge);
627 info.bestdist = radius;
628 VectorCopy(info.center, info.absmin);
629 VectorCopy(info.center, info.absmax);
630 info.absmin[0] -= info.radius + 1;
631 info.absmin[1] -= info.radius + 1;
632 info.absmin[2] -= info.radius + 1;
633 info.absmax[0] += info.radius + 1;
634 info.absmax[1] += info.radius + 1;
635 info.absmax[2] += info.radius + 1;
636 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
637 VectorAdd(info.center, info.nudge, info.center);
639 while (info.bestdist < radius && ++i < 10);
640 VectorCopy(info.center, out);
643 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
645 switch(nativecontents)
650 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
652 return SUPERCONTENTS_WATER;
654 return SUPERCONTENTS_SLIME;
656 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
658 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
663 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
665 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
666 return CONTENTS_SOLID;
667 if (supercontents & SUPERCONTENTS_SKY)
669 if (supercontents & SUPERCONTENTS_LAVA)
670 return CONTENTS_LAVA;
671 if (supercontents & SUPERCONTENTS_SLIME)
672 return CONTENTS_SLIME;
673 if (supercontents & SUPERCONTENTS_WATER)
674 return CONTENTS_WATER;
675 return CONTENTS_EMPTY;
678 typedef struct RecursiveHullCheckTraceInfo_s
680 // the hull we're tracing through
683 // the trace structure to fill in
686 // start, end, and end - start (in model space)
691 RecursiveHullCheckTraceInfo_t;
693 // 1/32 epsilon to keep floating point happy
694 #define DIST_EPSILON (0.03125)
696 #define HULLCHECKSTATE_EMPTY 0
697 #define HULLCHECKSTATE_SOLID 1
698 #define HULLCHECKSTATE_DONE 2
700 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
702 // status variables, these don't need to be saved on the stack when
703 // recursing... but are because this should be thread-safe
704 // (note: tracing against a bbox is not thread-safe, yet)
709 // variables that need to be stored on the stack when recursing
714 // keep looping until we hit a leaf
717 // find the point distances
718 node = t->hull->clipnodes + num;
719 plane = t->hull->planes + node->planenum;
721 // axial planes can be calculated more quickly without the DotProduct
724 t1 = p1[plane->type] - plane->dist;
725 t2 = p2[plane->type] - plane->dist;
729 t1 = DotProduct (plane->normal, p1) - plane->dist;
730 t2 = DotProduct (plane->normal, p2) - plane->dist;
733 // negative plane distances indicate children[1] (behind plane)
737 // if the line starts and ends on the same side of the plane, recurse
738 // into that child instantly
739 if (p1side == p2side)
741 #if COLLISIONPARANOID >= 3
747 // loop back and process the start child
748 num = node->children[p1side];
752 // find the midpoint where the line crosses the plane, use the
753 // original line for best accuracy
754 #if COLLISIONPARANOID >= 3
759 t1 = t->start[plane->type] - plane->dist;
760 t2 = t->end[plane->type] - plane->dist;
764 t1 = DotProduct (plane->normal, t->start) - plane->dist;
765 t2 = DotProduct (plane->normal, t->end) - plane->dist;
767 midf = t1 / (t1 - t2);
768 midf = bound(p1f, midf, p2f);
769 VectorMA(t->start, midf, t->dist, mid);
771 // we now have a mid point, essentially splitting the line into
772 // the segments in the near child and the far child, we can now
773 // recurse those in order and get their results
775 // recurse both sides, front side first
776 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
777 // if this side is not empty, return what it is (solid or done)
778 if (ret != HULLCHECKSTATE_EMPTY)
781 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
782 // if other side is not solid, return what it is (empty or done)
783 if (ret != HULLCHECKSTATE_SOLID)
786 // front is air and back is solid, this is the impact point...
788 // copy the plane information, flipping it if needed
791 t->trace->plane.dist = -plane->dist;
792 VectorNegate (plane->normal, t->trace->plane.normal);
796 t->trace->plane.dist = plane->dist;
797 VectorCopy (plane->normal, t->trace->plane.normal);
800 // calculate the return fraction which is nudged off the surface a bit
801 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
802 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
803 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
804 t->trace->fraction = bound(0, midf, 1);
806 #if COLLISIONPARANOID >= 3
809 return HULLCHECKSTATE_DONE;
813 // we reached a leaf contents
816 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
817 if (!t->trace->startfound)
819 t->trace->startfound = true;
820 t->trace->startsupercontents |= num;
822 if (num & SUPERCONTENTS_LIQUIDSMASK)
823 t->trace->inwater = true;
825 t->trace->inopen = true;
826 if (num & SUPERCONTENTS_SOLID)
827 t->trace->hittexture = &mod_q1bsp_texture_solid;
828 else if (num & SUPERCONTENTS_SKY)
829 t->trace->hittexture = &mod_q1bsp_texture_sky;
830 else if (num & SUPERCONTENTS_LAVA)
831 t->trace->hittexture = &mod_q1bsp_texture_lava;
832 else if (num & SUPERCONTENTS_SLIME)
833 t->trace->hittexture = &mod_q1bsp_texture_slime;
835 t->trace->hittexture = &mod_q1bsp_texture_water;
836 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
837 t->trace->hitsupercontents = num;
838 if (num & t->trace->hitsupercontentsmask)
840 // if the first leaf is solid, set startsolid
841 if (t->trace->allsolid)
842 t->trace->startsolid = true;
843 #if COLLISIONPARANOID >= 3
846 return HULLCHECKSTATE_SOLID;
850 t->trace->allsolid = false;
851 #if COLLISIONPARANOID >= 3
854 return HULLCHECKSTATE_EMPTY;
858 //#if COLLISIONPARANOID < 2
859 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
862 mclipnode_t *nodes = t->hull->clipnodes;
863 mplane_t *planes = t->hull->planes;
865 VectorCopy(t->start, point);
868 plane = planes + nodes[num].planenum;
869 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
871 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
872 t->trace->startsupercontents |= num;
873 if (num & SUPERCONTENTS_LIQUIDSMASK)
874 t->trace->inwater = true;
876 t->trace->inopen = true;
877 if (num & t->trace->hitsupercontentsmask)
879 t->trace->allsolid = t->trace->startsolid = true;
880 return HULLCHECKSTATE_SOLID;
884 t->trace->allsolid = t->trace->startsolid = false;
885 return HULLCHECKSTATE_EMPTY;
890 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, int skipsupercontentsmask)
892 RecursiveHullCheckTraceInfo_t rhc;
894 memset(&rhc, 0, sizeof(rhc));
895 memset(trace, 0, sizeof(trace_t));
897 rhc.trace->fraction = 1;
898 rhc.trace->allsolid = true;
899 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
900 VectorCopy(start, rhc.start);
901 VectorCopy(start, rhc.end);
902 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
905 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, int skipsupercontentsmask);
907 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, int skipsupercontentsmask)
909 RecursiveHullCheckTraceInfo_t rhc;
911 if (VectorCompare(start, end))
913 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
917 // sometimes we want to traceline against polygons so we can report the texture that was hit rather than merely a contents, but using this method breaks one of negke's maps so it must be a cvar check...
918 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
920 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
924 memset(&rhc, 0, sizeof(rhc));
925 memset(trace, 0, sizeof(trace_t));
927 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
928 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
929 rhc.trace->fraction = 1;
930 rhc.trace->allsolid = true;
931 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
932 VectorCopy(start, rhc.start);
933 VectorCopy(end, rhc.end);
934 VectorSubtract(rhc.end, rhc.start, rhc.dist);
935 #if COLLISIONPARANOID >= 2
936 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]);
937 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
942 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
943 memset(&testtrace, 0, sizeof(trace_t));
944 rhc.trace = &testtrace;
945 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
946 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
947 rhc.trace->fraction = 1;
948 rhc.trace->allsolid = true;
949 VectorCopy(test, rhc.start);
950 VectorCopy(test, rhc.end);
951 VectorClear(rhc.dist);
952 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
953 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
954 if (!trace->startsolid && testtrace.startsolid)
955 Con_Printf(" - ended in solid!\n");
959 if (VectorLength2(rhc.dist))
960 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
962 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
966 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, int skipsupercontentsmask)
968 // this function currently only supports same size start and end
970 RecursiveHullCheckTraceInfo_t rhc;
972 if (VectorCompare(boxmins, boxmaxs))
974 if (VectorCompare(start, end))
975 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
977 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
981 memset(&rhc, 0, sizeof(rhc));
982 memset(trace, 0, sizeof(trace_t));
984 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
985 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
986 rhc.trace->fraction = 1;
987 rhc.trace->allsolid = true;
988 VectorSubtract(boxmaxs, boxmins, boxsize);
990 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
991 else if (model->brush.ishlbsp)
993 // LordHavoc: this has to have a minor tolerance (the .1) because of
994 // minor float precision errors from the box being transformed around
995 if (boxsize[0] < 32.1)
997 if (boxsize[2] < 54) // pick the nearest of 36 or 72
998 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
1000 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
1003 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1007 // LordHavoc: this has to have a minor tolerance (the .1) because of
1008 // minor float precision errors from the box being transformed around
1009 if (boxsize[0] < 32.1)
1010 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1012 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1014 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1015 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1016 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1017 #if COLLISIONPARANOID >= 2
1018 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]);
1019 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1024 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1025 memset(&testtrace, 0, sizeof(trace_t));
1026 rhc.trace = &testtrace;
1027 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1028 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1029 rhc.trace->fraction = 1;
1030 rhc.trace->allsolid = true;
1031 VectorCopy(test, rhc.start);
1032 VectorCopy(test, rhc.end);
1033 VectorClear(rhc.dist);
1034 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1035 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1036 if (!trace->startsolid && testtrace.startsolid)
1037 Con_Printf(" - ended in solid!\n");
1041 if (VectorLength2(rhc.dist))
1042 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1044 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1048 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1050 int num = model->brushq1.hulls[0].firstclipnode;
1052 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1053 mplane_t *planes = model->brushq1.hulls[0].planes;
1056 plane = planes + nodes[num].planenum;
1057 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1059 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1062 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 skipsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1066 colplanef_t cbox_planes[6];
1068 cbox.hasaabbplanes = true;
1069 cbox.supercontents = boxsupercontents;
1072 cbox.numtriangles = 0;
1073 cbox.planes = cbox_planes;
1075 cbox.elements = NULL;
1083 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];
1084 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];
1085 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];
1086 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];
1087 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];
1088 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];
1089 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1090 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1091 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1092 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1093 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1094 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1095 memset(trace, 0, sizeof(trace_t));
1096 trace->hitsupercontentsmask = hitsupercontentsmask;
1097 trace->skipsupercontentsmask = skipsupercontentsmask;
1098 trace->fraction = 1;
1099 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1101 RecursiveHullCheckTraceInfo_t rhc;
1102 static hull_t box_hull;
1103 static mclipnode_t box_clipnodes[6];
1104 static mplane_t box_planes[6];
1105 // fill in a default trace
1106 memset(&rhc, 0, sizeof(rhc));
1107 memset(trace, 0, sizeof(trace_t));
1108 //To keep everything totally uniform, bounding boxes are turned into small
1109 //BSP trees instead of being compared directly.
1110 // create a temp hull from bounding box sizes
1111 box_planes[0].dist = cmaxs[0] - mins[0];
1112 box_planes[1].dist = cmins[0] - maxs[0];
1113 box_planes[2].dist = cmaxs[1] - mins[1];
1114 box_planes[3].dist = cmins[1] - maxs[1];
1115 box_planes[4].dist = cmaxs[2] - mins[2];
1116 box_planes[5].dist = cmins[2] - maxs[2];
1117 #if COLLISIONPARANOID >= 3
1118 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]);
1121 if (box_hull.clipnodes == NULL)
1125 //Set up the planes and clipnodes so that the six floats of a bounding box
1126 //can just be stored out and get a proper hull_t structure.
1128 box_hull.clipnodes = box_clipnodes;
1129 box_hull.planes = box_planes;
1130 box_hull.firstclipnode = 0;
1131 box_hull.lastclipnode = 5;
1133 for (i = 0;i < 6;i++)
1135 box_clipnodes[i].planenum = i;
1139 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1141 box_clipnodes[i].children[side^1] = i + 1;
1143 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1145 box_planes[i].type = i>>1;
1146 box_planes[i].normal[i>>1] = 1;
1150 // trace a line through the generated clipping hull
1151 //rhc.boxsupercontents = boxsupercontents;
1152 rhc.hull = &box_hull;
1154 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1155 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1156 rhc.trace->fraction = 1;
1157 rhc.trace->allsolid = true;
1158 VectorCopy(start, rhc.start);
1159 VectorCopy(end, rhc.end);
1160 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1161 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1162 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1163 if (rhc.trace->startsupercontents)
1164 rhc.trace->startsupercontents = boxsupercontents;
1168 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1170 memset(trace, 0, sizeof(trace_t));
1171 trace->fraction = 1;
1172 trace->hitsupercontentsmask = hitsupercontentsmask;
1173 trace->skipsupercontentsmask = skipsupercontentsmask;
1174 if (BoxesOverlap(start, start, cmins, cmaxs))
1176 trace->startsupercontents |= boxsupercontents;
1177 if ((hitsupercontentsmask & boxsupercontents) && !(skipsupercontentsmask & boxsupercontents))
1179 trace->startsolid = true;
1180 trace->allsolid = true;
1185 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1188 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0);
1189 return trace.fraction == 1;
1192 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)
1196 float mid, distz = endz - startz;
1200 switch (node->plane->type)
1203 node = node->children[x < node->plane->dist];
1204 continue; // loop back and process the new node
1206 node = node->children[y < node->plane->dist];
1207 continue; // loop back and process the new node
1209 side = startz < node->plane->dist;
1210 if ((endz < node->plane->dist) == side)
1212 node = node->children[side];
1213 continue; // loop back and process the new node
1215 // found an intersection
1216 mid = node->plane->dist;
1219 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1220 front += startz * node->plane->normal[2];
1221 back += endz * node->plane->normal[2];
1222 side = front < node->plane->dist;
1223 if ((back < node->plane->dist) == side)
1225 node = node->children[side];
1226 continue; // loop back and process the new node
1228 // found an intersection
1229 mid = startz + distz * (front - node->plane->dist) / (front - back);
1233 // go down front side
1234 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1235 return true; // hit something
1237 // check for impact on this node
1238 if (node->numsurfaces)
1241 int dsi, dti, lmwidth, lmheight;
1243 msurface_t *surface;
1244 unsigned char *lightmap;
1245 int maps, line3, size3;
1248 float scale, w, w00, w01, w10, w11;
1250 surface = model->data_surfaces + node->firstsurface;
1251 for (i = 0;i < node->numsurfaces;i++, surface++)
1253 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1254 continue; // no lightmaps
1256 // location we want to sample in the lightmap
1257 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;
1258 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;
1261 // thanks to jitspoe for pointing out that this int cast was
1262 // rounding toward zero, so we floor it
1263 dsi = (int)floor(ds);
1264 dti = (int)floor(dt);
1265 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1266 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1269 // we have to tolerate a position of lmwidth-1 for some rare
1270 // cases - in which case the sampling position still gets
1271 // clamped but the color gets interpolated to that edge.
1272 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1274 // in the rare cases where we're sampling slightly off
1275 // the polygon, clamp the sampling position (we can still
1276 // interpolate outside it, where it becomes extrapolation)
1281 if (dsi > lmwidth-2)
1283 if (dti > lmheight-2)
1286 // calculate bilinear interpolation factors
1287 // and also multiply by fixedpoint conversion factors to
1288 // compensate for lightmaps being 0-255 (as 0-2), we use
1289 // r_refdef.scene.rtlightstylevalue here which is already
1290 // 0.000-2.148 range
1291 // (if we used r_refdef.scene.lightstylevalue this
1292 // divisor would be 32768 rather than 128)
1295 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1296 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1297 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1298 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1300 // values for pointer math
1301 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1302 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1304 // look up the pixel
1305 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1307 // bilinear filter each lightmap style, and sum them
1308 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1310 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1311 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1312 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1313 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1314 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1318 return true; // success
1323 // go down back side
1324 node = node->children[side ^ 1];
1326 distz = endz - startz;
1327 // loop back and process the new node
1330 // did not hit anything
1334 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1336 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1337 VectorSet(diffusenormal, 0, 0, 1);
1339 if (!model->brushq1.lightdata)
1341 VectorSet(ambientcolor, 1, 1, 1);
1342 VectorSet(diffusecolor, 0, 0, 0);
1346 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);
1349 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1354 const msurface_t *surface;
1359 float edgenormal[3];
1366 surface = model->data_surfaces + node->firstsurface;
1367 for (i = 0;i < node->numsurfaces;i++, surface++)
1369 // skip surfaces whose bounding box does not include the point
1370 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1372 // skip faces with contents we don't care about
1373 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1375 // ignore surfaces matching the skipsupercontentsmask (this is rare)
1376 if (t->trace->skipsupercontentsmask & surface->texture->supercontents)
1378 // get the surface normal - since it is flat we know any vertex normal will suffice
1379 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1381 if (DotProduct(t->dist, normal) > 0)
1383 // iterate edges and see if the point is outside one of them
1384 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1386 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1387 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1388 VectorSubtract(v0, v1, edgedir);
1389 CrossProduct(edgedir, normal, edgenormal);
1390 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1393 // if the point is outside one of the edges, it is not within the surface
1394 if (j < surface->num_vertices)
1397 // we hit a surface, this is the impact point...
1398 VectorCopy(normal, t->trace->plane.normal);
1399 t->trace->plane.dist = DotProduct(normal, p);
1401 // calculate the return fraction which is nudged off the surface a bit
1402 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1403 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1404 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1405 t->trace->fraction = bound(0, midf, 1);
1407 t->trace->hittexture = surface->texture->currentframe;
1408 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1409 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1410 return surface->texture->currentframe;
1415 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])
1417 const mplane_t *plane;
1420 double midf, mid[3];
1421 const mleaf_t *leaf;
1425 plane = node->plane;
1426 if (plane->type < 3)
1428 t1 = p1[plane->type] - plane->dist;
1429 t2 = p2[plane->type] - plane->dist;
1433 t1 = DotProduct (plane->normal, p1) - plane->dist;
1434 t2 = DotProduct (plane->normal, p2) - plane->dist;
1440 node = node->children[1];
1449 node = node->children[0];
1455 // the line intersects, find intersection point
1456 // LordHavoc: this uses the original trace for maximum accuracy
1457 if (plane->type < 3)
1459 t1 = t->start[plane->type] - plane->dist;
1460 t2 = t->end[plane->type] - plane->dist;
1464 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1465 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1468 midf = t1 / (t1 - t2);
1469 VectorMA(t->start, midf, t->dist, mid);
1471 // recurse both sides, front side first, return if we hit a surface
1472 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1473 return HULLCHECKSTATE_DONE;
1475 // test each surface on the node
1476 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1477 if (t->trace->hittexture)
1478 return HULLCHECKSTATE_DONE;
1480 // recurse back side
1481 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1483 leaf = (const mleaf_t *)node;
1484 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1485 if (!t->trace->startfound)
1487 t->trace->startfound = true;
1488 t->trace->startsupercontents |= side;
1490 if (side & SUPERCONTENTS_LIQUIDSMASK)
1491 t->trace->inwater = true;
1493 t->trace->inopen = true;
1494 if (side & t->trace->hitsupercontentsmask)
1496 // if the first leaf is solid, set startsolid
1497 if (t->trace->allsolid)
1498 t->trace->startsolid = true;
1499 return HULLCHECKSTATE_SOLID;
1503 t->trace->allsolid = false;
1504 return HULLCHECKSTATE_EMPTY;
1508 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, int skipsupercontentsmask)
1510 RecursiveHullCheckTraceInfo_t rhc;
1512 memset(&rhc, 0, sizeof(rhc));
1513 memset(trace, 0, sizeof(trace_t));
1515 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1516 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1517 rhc.trace->fraction = 1;
1518 rhc.trace->allsolid = true;
1519 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1520 VectorCopy(start, rhc.start);
1521 VectorCopy(end, rhc.end);
1522 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1523 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1524 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1527 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1530 unsigned char *outstart = out;
1531 while (out < outend)
1535 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));
1545 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));
1548 for (c = *in++;c > 0;c--)
1552 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));
1563 R_Q1BSP_LoadSplitSky
1565 A sky texture is 256*128, with the right side being a masked overlay
1568 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1573 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1574 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1576 // allocate a texture pool if we need it
1577 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1578 loadmodel->texturepool = R_AllocTexturePool();
1580 if (bytesperpixel == 4)
1582 for (y = 0;y < h;y++)
1584 for (x = 0;x < w;x++)
1586 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1587 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1593 // make an average value for the back to avoid
1594 // a fringe on the top level
1603 for (y = 0;y < h;y++)
1605 for (x = 0;x < w;x++)
1607 p = src[x*width+y+w];
1608 r += palette_rgb[p][0];
1609 g += palette_rgb[p][1];
1610 b += palette_rgb[p][2];
1613 bgra.b[2] = r/(w*h);
1614 bgra.b[1] = g/(w*h);
1615 bgra.b[0] = b/(w*h);
1617 for (y = 0;y < h;y++)
1619 for (x = 0;x < w;x++)
1621 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1623 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1628 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1629 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1630 Mem_Free(solidpixels);
1631 Mem_Free(alphapixels);
1634 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1636 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1637 skinframe_t *skinframemissing;
1638 texture_t *tx, *tx2, *anims[10], *altanims[10];
1639 texture_t backuptex;
1640 unsigned char *data, *mtdata;
1642 char mapname[MAX_QPATH], name[MAX_QPATH];
1643 unsigned char zeroopaque[4], zerotrans[4];
1646 Vector4Set(zeroopaque, 0, 0, 0, 255);
1647 Vector4Set(zerotrans, 0, 0, 0, 128);
1649 loadmodel->data_textures = NULL;
1651 // add two slots for notexture walls and notexture liquids
1654 nummiptex = MSG_ReadLittleLong(sb);
1655 loadmodel->num_textures = nummiptex + 2;
1656 loadmodel->num_texturesperskin = loadmodel->num_textures;
1660 loadmodel->num_textures = 2;
1661 loadmodel->num_texturesperskin = loadmodel->num_textures;
1664 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1666 // fill out all slots with notexture
1667 if (cls.state != ca_dedicated)
1668 skinframemissing = R_SkinFrame_LoadMissing();
1670 skinframemissing = NULL;
1671 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1673 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1676 tx->basealpha = 1.0f;
1677 if (cls.state != ca_dedicated)
1679 tx->materialshaderpass = tx->shaderpasses[0] = Mod_CreateShaderPass(skinframemissing);
1680 tx->currentskinframe = skinframemissing;
1682 tx->basematerialflags = MATERIALFLAG_WALL;
1683 if (i == loadmodel->num_textures - 1)
1685 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1686 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1687 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1691 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1692 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1694 tx->currentframe = tx;
1696 // clear water settings
1699 tx->refractfactor = 1;
1700 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1701 tx->reflectfactor = 1;
1702 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1703 tx->r_water_wateralpha = 1;
1704 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1705 tx->offsetscale = 1;
1707 tx->specularscalemod = 1;
1708 tx->specularpowermod = 1;
1709 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1710 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1711 // JUST GREP FOR "specularscalemod = 1".
1716 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1720 s = loadmodel->name;
1721 if (!strncasecmp(s, "maps/", 5))
1723 FS_StripExtension(s, mapname, sizeof(mapname));
1725 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1726 // LordHavoc: mostly rewritten map texture loader
1727 for (i = 0;i < nummiptex;i++)
1729 doffset = MSG_ReadLittleLong(sb);
1730 if (r_nosurftextures.integer)
1734 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1738 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1740 // copy name, but only up to 16 characters
1741 // (the output buffer can hold more than this, but the input buffer is
1743 for (j = 0;j < 16;j++)
1744 name[j] = MSG_ReadByte(&miptexsb);
1746 // pretty up the buffer (replacing any trailing garbage with 0)
1747 for (j = (int)strlen(name);j < 16;j++)
1752 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1753 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1756 mtwidth = MSG_ReadLittleLong(&miptexsb);
1757 mtheight = MSG_ReadLittleLong(&miptexsb);
1759 j = MSG_ReadLittleLong(&miptexsb);
1763 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1765 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1768 mtdata = miptexsb.data + j;
1771 if ((mtwidth & 15) || (mtheight & 15))
1772 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1774 // LordHavoc: force all names to lowercase
1775 for (j = 0;name[j];j++)
1776 if (name[j] >= 'A' && name[j] <= 'Z')
1777 name[j] += 'a' - 'A';
1779 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1780 backuptex = loadmodel->data_textures[i];
1781 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1783 loadmodel->data_textures[i] = backuptex;
1785 tx = loadmodel->data_textures + i;
1786 strlcpy(tx->name, name, sizeof(tx->name));
1787 tx->width = mtwidth;
1788 tx->height = mtheight;
1789 tx->basealpha = 1.0f;
1791 if (tx->name[0] == '*')
1793 if (!strncmp(tx->name, "*lava", 5))
1795 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1796 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1798 else if (!strncmp(tx->name, "*slime", 6))
1800 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1801 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1805 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1806 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1809 else if (!strncmp(tx->name, "sky", 3))
1811 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1812 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1813 // for the surface traceline we need to hit this surface as a solid...
1814 tx->supercontents |= SUPERCONTENTS_SOLID;
1818 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1819 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1822 if (cls.state != ca_dedicated)
1824 // LordHavoc: HL sky textures are entirely different than quake
1825 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1827 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1829 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1830 if (data && image_width == image_height * 2)
1832 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1835 else if (mtdata != NULL)
1836 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1840 skinframe_t *skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1842 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1844 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1847 // did not find external texture, load it from the bsp or wad3
1848 if (loadmodel->brush.ishlbsp)
1850 // internal texture overrides wad
1851 unsigned char *pixels, *freepixels;
1852 pixels = freepixels = NULL;
1854 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1856 pixels = freepixels = W_GetTextureBGRA(tx->name);
1859 tx->width = image_width;
1860 tx->height = image_height;
1861 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1864 Mem_Free(freepixels);
1866 else if (mtdata) // texture included
1867 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1869 // if skinframe is still NULL the "missing" texture has already been assigned to this
1871 tx->materialshaderpass->skinframes[0] = skinframe;
1873 // LordHavoc: some Tenebrae textures get replaced by black
1874 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1875 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1876 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1877 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1880 tx->basematerialflags = MATERIALFLAG_WALL;
1881 if (tx->name[0] == '*')
1883 // LordHavoc: some turbulent textures should not be affected by wateralpha
1884 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1885 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1886 else if (!strncmp(tx->name,"*lava",5)
1887 || !strncmp(tx->name,"*teleport",9)
1888 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1889 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1891 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1892 if (tx->materialshaderpass->skinframes[0]->hasalpha)
1893 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1895 else if (tx->name[0] == '{') // fence textures
1897 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1899 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1901 // replace the texture with black
1902 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1904 else if (!strncmp(tx->name, "sky", 3))
1905 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1906 else if (!strcmp(tx->name, "caulk"))
1907 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1908 else if (tx->materialshaderpass->skinframes[0]->hasalpha)
1909 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1911 // start out with no animation
1912 tx->currentframe = tx;
1913 tx->currentskinframe = tx->materialshaderpass->skinframes[0];
1914 tx->currentmaterialflags = tx->basematerialflags;
1917 // sequence the animations
1918 for (i = 0;i < nummiptex;i++)
1920 tx = loadmodel->data_textures + i;
1921 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1924 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1926 Con_Printf("Bad animating texture %s\n", tx->name);
1929 if (tx->anim_total[0] || tx->anim_total[1])
1930 continue; // already sequenced
1932 // find the number of frames in the animation
1933 memset(anims, 0, sizeof(anims));
1934 memset(altanims, 0, sizeof(altanims));
1936 for (j = i;j < nummiptex;j++)
1938 tx2 = loadmodel->data_textures + j;
1939 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1943 if (num >= '0' && num <= '9')
1944 anims[num - '0'] = tx2;
1945 else if (num >= 'a' && num <= 'j')
1946 altanims[num - 'a'] = tx2;
1947 // No need to warn otherwise - we already did above.
1951 for (j = 0;j < 10;j++)
1958 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1961 for (j = 0;j < max;j++)
1965 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1969 for (j = 0;j < altmax;j++)
1973 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1980 // If we have exactly one frame, something's wrong.
1981 if (max + altmax <= 1)
1983 Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
1988 // if there is no alternate animation, duplicate the primary
1989 // animation into the alternate
1991 for (k = 0;k < 10;k++)
1992 altanims[k] = anims[k];
1998 Con_Printf("Missing frame 0 of %s\n", tx->name);
2000 // however, we can handle this by duplicating the alternate animation into the primary
2002 for (k = 0;k < 10;k++)
2003 anims[k] = altanims[k];
2007 // link together the primary animation
2008 for (j = 0;j < max;j++)
2011 tx2->animated = 1; // q1bsp
2012 tx2->anim_total[0] = max;
2013 tx2->anim_total[1] = altmax;
2014 for (k = 0;k < 10;k++)
2016 tx2->anim_frames[0][k] = anims[k];
2017 tx2->anim_frames[1][k] = altanims[k];
2021 // if there really is an alternate anim...
2022 if (anims[0] != altanims[0])
2024 // link together the alternate animation
2025 for (j = 0;j < altmax;j++)
2028 tx2->animated = 1; // q1bsp
2029 // the primary/alternate are reversed here
2030 tx2->anim_total[0] = altmax;
2031 tx2->anim_total[1] = max;
2032 for (k = 0;k < 10;k++)
2034 tx2->anim_frames[0][k] = altanims[k];
2035 tx2->anim_frames[1][k] = anims[k];
2042 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2045 unsigned char *in, *out, *data, d;
2046 char litfilename[MAX_QPATH];
2047 char dlitfilename[MAX_QPATH];
2048 fs_offset_t filesize;
2049 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2051 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2052 for (i = 0;i < sb->cursize;i++)
2053 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2055 else // LordHavoc: bsp version 29 (normal white lighting)
2057 // LordHavoc: hope is not lost yet, check for a .lit file to load
2058 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2059 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2060 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2061 strlcat (litfilename, ".lit", sizeof (litfilename));
2062 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2063 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2066 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2068 i = LittleLong(((int *)data)[1]);
2071 if (developer_loading.integer)
2072 Con_Printf("loaded %s\n", litfilename);
2073 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2074 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2076 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2079 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2081 i = LittleLong(((int *)data)[1]);
2084 if (developer_loading.integer)
2085 Con_Printf("loaded %s\n", dlitfilename);
2086 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2087 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2088 loadmodel->brushq3.deluxemapping_modelspace = false;
2089 loadmodel->brushq3.deluxemapping = true;
2098 Con_Printf("Unknown .lit file version (%d)\n", i);
2100 else if (filesize == 8)
2101 Con_Print("Empty .lit file, ignoring\n");
2103 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2110 // LordHavoc: oh well, expand the white lighting data
2113 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2115 out = loadmodel->brushq1.lightdata;
2116 for (i = 0;i < sb->cursize;i++)
2126 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2128 loadmodel->brushq1.num_compressedpvs = 0;
2129 loadmodel->brushq1.data_compressedpvs = NULL;
2132 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2133 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2134 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2137 // used only for HalfLife maps
2138 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2140 char key[128], value[4096];
2144 if (!COM_ParseToken_Simple(&data, false, false, true))
2146 if (com_token[0] != '{')
2150 if (!COM_ParseToken_Simple(&data, false, false, true))
2152 if (com_token[0] == '}')
2153 break; // end of worldspawn
2154 if (com_token[0] == '_')
2155 strlcpy(key, com_token + 1, sizeof(key));
2157 strlcpy(key, com_token, sizeof(key));
2158 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2159 key[strlen(key)-1] = 0;
2160 if (!COM_ParseToken_Simple(&data, false, false, true))
2162 dpsnprintf(value, sizeof(value), "%s", com_token);
2163 if (!strcmp("wad", key)) // for HalfLife maps
2165 if (loadmodel->brush.ishlbsp)
2168 for (i = 0;i < (int)sizeof(value);i++)
2169 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2171 if (i < (int)sizeof(value) && value[i])
2173 for (;i < (int)sizeof(value);i++)
2175 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2176 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2178 else if (value[i] == ';' || value[i] == 0)
2182 W_LoadTextureWadFile(&value[j], false);
2194 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2196 loadmodel->brush.entities = NULL;
2199 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2200 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2201 loadmodel->brush.entities[sb->cursize] = 0;
2202 if (loadmodel->brush.ishlbsp)
2203 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2207 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2211 int structsize = 12;
2213 if (sb->cursize % structsize)
2214 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2215 count = sb->cursize / structsize;
2216 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2218 loadmodel->brushq1.vertexes = out;
2219 loadmodel->brushq1.numvertexes = count;
2221 for ( i=0 ; i<count ; i++, out++)
2223 out->position[0] = MSG_ReadLittleFloat(sb);
2224 out->position[1] = MSG_ReadLittleFloat(sb);
2225 out->position[2] = MSG_ReadLittleFloat(sb);
2229 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2233 int structsize = (48+4*hullinfo->filehulls);
2235 if (sb->cursize % structsize)
2236 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2238 count = sb->cursize / structsize;
2239 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2241 loadmodel->brushq1.submodels = out;
2242 loadmodel->brush.numsubmodels = count;
2244 for (i = 0; i < count; i++, out++)
2246 // spread out the mins / maxs by a pixel
2247 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2248 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2249 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2250 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2251 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2252 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2253 out->origin[0] = MSG_ReadLittleFloat(sb);
2254 out->origin[1] = MSG_ReadLittleFloat(sb);
2255 out->origin[2] = MSG_ReadLittleFloat(sb);
2256 for (j = 0; j < hullinfo->filehulls; j++)
2257 out->headnode[j] = MSG_ReadLittleLong(sb);
2258 out->visleafs = MSG_ReadLittleLong(sb);
2259 out->firstface = MSG_ReadLittleLong(sb);
2260 out->numfaces = MSG_ReadLittleLong(sb);
2264 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2268 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2270 if (sb->cursize % structsize)
2271 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2272 count = sb->cursize / structsize;
2273 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2275 loadmodel->brushq1.edges = out;
2276 loadmodel->brushq1.numedges = count;
2278 for ( i=0 ; i<count ; i++, out++)
2280 if (loadmodel->brush.isbsp2)
2282 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2283 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2287 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2288 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2290 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2292 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);
2293 if(!loadmodel->brushq1.numvertexes)
2294 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2302 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2305 int i, j, k, count, miptex;
2306 int structsize = 40;
2308 if (sb->cursize % structsize)
2309 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2310 count = sb->cursize / structsize;
2311 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2313 loadmodel->brushq1.texinfo = out;
2314 loadmodel->brushq1.numtexinfo = count;
2316 for (i = 0;i < count;i++, out++)
2318 for (k = 0;k < 2;k++)
2319 for (j = 0;j < 4;j++)
2320 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2322 miptex = MSG_ReadLittleLong(sb);
2323 out->q1flags = MSG_ReadLittleLong(sb);
2325 if (out->q1flags & TEX_SPECIAL)
2327 // if texture chosen is NULL or the shader needs a lightmap,
2328 // force to notexture water shader
2329 out->textureindex = loadmodel->num_textures - 1;
2333 // if texture chosen is NULL, force to notexture
2334 out->textureindex = loadmodel->num_textures - 2;
2336 // see if the specified miptex is valid and try to use it instead
2337 if (loadmodel->data_textures)
2339 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2340 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2342 out->textureindex = miptex;
2348 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2353 mins[0] = mins[1] = mins[2] = 9999;
2354 maxs[0] = maxs[1] = maxs[2] = -9999;
2356 for (i = 0;i < numverts;i++)
2358 for (j = 0;j < 3;j++, v++)
2368 #define MAX_SUBDIVPOLYTRIANGLES 4096
2369 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2371 static int subdivpolyverts, subdivpolytriangles;
2372 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2373 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2375 static int subdivpolylookupvert(vec3_t v)
2378 for (i = 0;i < subdivpolyverts;i++)
2379 if (subdivpolyvert[i][0] == v[0]
2380 && subdivpolyvert[i][1] == v[1]
2381 && subdivpolyvert[i][2] == v[2])
2383 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2384 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2385 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2386 return subdivpolyverts++;
2389 static void SubdividePolygon(int numverts, float *verts)
2391 int i, i1, i2, i3, f, b, c, p;
2392 vec3_t mins, maxs, front[256], back[256];
2393 float m, *pv, *cv, dist[256], frac;
2396 Host_Error("SubdividePolygon: ran out of verts in buffer");
2398 BoundPoly(numverts, verts, mins, maxs);
2400 for (i = 0;i < 3;i++)
2402 m = (mins[i] + maxs[i]) * 0.5;
2403 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2404 if (maxs[i] - m < 8)
2406 if (m - mins[i] < 8)
2410 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2411 dist[c] = cv[i] - m;
2414 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2418 VectorCopy(pv, front[f]);
2423 VectorCopy(pv, back[b]);
2426 if (dist[p] == 0 || dist[c] == 0)
2428 if ((dist[p] > 0) != (dist[c] > 0) )
2431 frac = dist[p] / (dist[p] - dist[c]);
2432 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2433 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2434 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2440 SubdividePolygon(f, front[0]);
2441 SubdividePolygon(b, back[0]);
2445 i1 = subdivpolylookupvert(verts);
2446 i2 = subdivpolylookupvert(verts + 3);
2447 for (i = 2;i < numverts;i++)
2449 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2451 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2455 i3 = subdivpolylookupvert(verts + i * 3);
2456 subdivpolyindex[subdivpolytriangles][0] = i1;
2457 subdivpolyindex[subdivpolytriangles][1] = i2;
2458 subdivpolyindex[subdivpolytriangles][2] = i3;
2460 subdivpolytriangles++;
2464 //Breaks a polygon up along axial 64 unit
2465 //boundaries so that turbulent and sky warps
2466 //can be done reasonably.
2467 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2473 subdivpolytriangles = 0;
2474 subdivpolyverts = 0;
2475 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2476 if (subdivpolytriangles < 1)
2477 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2479 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2480 mesh->num_vertices = subdivpolyverts;
2481 mesh->num_triangles = subdivpolytriangles;
2482 mesh->vertex = (surfvertex_t *)(mesh + 1);
2483 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2484 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2486 for (i = 0;i < mesh->num_triangles;i++)
2487 for (j = 0;j < 3;j++)
2488 mesh->index[i*3+j] = subdivpolyindex[i][j];
2490 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2492 VectorCopy(subdivpolyvert[i], v->v);
2493 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2494 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2499 extern cvar_t gl_max_lightmapsize;
2500 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2502 msurface_t *surface;
2503 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2504 float texmins[2], texmaxs[2], val;
2505 rtexture_t *lightmaptexture, *deluxemaptexture;
2507 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2509 if (sb->cursize % structsize)
2510 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2511 count = sb->cursize / structsize;
2512 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2513 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2515 loadmodel->num_surfaces = count;
2517 loadmodel->brushq1.firstrender = true;
2518 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2522 for (surfacenum = 0;surfacenum < count;surfacenum++)
2524 if (loadmodel->brush.isbsp2)
2525 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2527 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2528 totalverts += numedges;
2529 totaltris += numedges - 2;
2532 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2534 lightmaptexture = NULL;
2535 deluxemaptexture = r_texture_blanknormalmap;
2537 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2538 totallightmapsamples = 0;
2542 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2544 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2545 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2546 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2547 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2548 firstedge = MSG_ReadLittleLong(sb);
2549 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2550 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2551 for (i = 0;i < MAXLIGHTMAPS;i++)
2552 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2553 lightmapoffset = MSG_ReadLittleLong(sb);
2555 // FIXME: validate edges, texinfo, etc?
2556 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)
2557 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2558 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2559 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2560 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2561 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2563 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2564 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2566 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2567 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2568 lightmapoffset = -1;
2570 //surface->flags = surface->texture->flags;
2571 //if (LittleShort(in->side))
2572 // surface->flags |= SURF_PLANEBACK;
2573 //surface->plane = loadmodel->brush.data_planes + planenum;
2575 surface->num_firstvertex = totalverts;
2576 surface->num_vertices = numedges;
2577 surface->num_firsttriangle = totaltris;
2578 surface->num_triangles = numedges - 2;
2579 totalverts += numedges;
2580 totaltris += numedges - 2;
2582 // convert edges back to a normal polygon
2583 for (i = 0;i < surface->num_vertices;i++)
2585 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2587 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2589 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2591 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2592 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2593 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2594 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2595 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2596 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2597 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2598 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2601 for (i = 0;i < surface->num_triangles;i++)
2603 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2604 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2605 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2608 // compile additional data about the surface geometry
2609 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);
2610 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);
2611 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2613 // generate surface extents information
2614 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2615 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2616 for (i = 1;i < surface->num_vertices;i++)
2618 for (j = 0;j < 2;j++)
2620 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2621 texmins[j] = min(texmins[j], val);
2622 texmaxs[j] = max(texmaxs[j], val);
2625 for (i = 0;i < 2;i++)
2627 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2628 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2631 smax = surface->lightmapinfo->extents[0] >> 4;
2632 tmax = surface->lightmapinfo->extents[1] >> 4;
2633 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2634 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2637 surface->lightmaptexture = NULL;
2638 surface->deluxemaptexture = r_texture_blanknormalmap;
2639 if (lightmapoffset == -1)
2641 surface->lightmapinfo->samples = NULL;
2643 // give non-lightmapped water a 1x white lightmap
2644 if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2646 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2647 surface->lightmapinfo->styles[0] = 0;
2648 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2652 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LordHavoc: HalfLife map (bsp version 30)
2653 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2654 else // LordHavoc: white lighting (bsp version 29)
2656 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2657 if (loadmodel->brushq1.nmaplightdata)
2658 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2661 // check if we should apply a lightmap to this
2662 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2664 if (ssize > 256 || tsize > 256)
2665 Host_Error("Bad surface extents");
2667 if (lightmapsize < ssize)
2668 lightmapsize = ssize;
2669 if (lightmapsize < tsize)
2670 lightmapsize = tsize;
2672 totallightmapsamples += ssize*tsize;
2674 // force lightmap upload on first time seeing the surface
2676 // additionally this is used by the later code to see if a
2677 // lightmap is needed on this surface (rather than duplicating the
2679 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2680 loadmodel->lit = true;
2684 // small maps (such as ammo boxes especially) don't need big lightmap
2685 // textures, so this code tries to guess a good size based on
2686 // totallightmapsamples (size of the lightmaps lump basically), as well as
2687 // trying to max out the size if there is a lot of lightmap data to store
2688 // additionally, never choose a lightmapsize that is smaller than the
2689 // largest surface encountered (as it would fail)
2691 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2694 // now that we've decided the lightmap texture size, we can do the rest
2695 if (cls.state != ca_dedicated)
2697 int stainmapsize = 0;
2698 mod_alloclightmap_state_t allocState;
2700 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2701 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2703 int iu, iv, lightmapx = 0, lightmapy = 0;
2704 float u, v, ubase, vbase, uscale, vscale;
2706 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2709 smax = surface->lightmapinfo->extents[0] >> 4;
2710 tmax = surface->lightmapinfo->extents[1] >> 4;
2711 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2712 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2713 stainmapsize += ssize * tsize * 3;
2715 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2717 // allocate a texture pool if we need it
2718 if (loadmodel->texturepool == NULL)
2719 loadmodel->texturepool = R_AllocTexturePool();
2720 // could not find room, make a new lightmap
2721 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2722 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2723 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2724 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2725 if (loadmodel->brushq1.nmaplightdata)
2726 loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2728 Mod_AllocLightmap_Reset(&allocState);
2729 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2731 surface->lightmaptexture = lightmaptexture;
2732 surface->deluxemaptexture = deluxemaptexture;
2733 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2734 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2736 uscale = 1.0f / (float)lightmapsize;
2737 vscale = 1.0f / (float)lightmapsize;
2738 ubase = lightmapx * uscale;
2739 vbase = lightmapy * vscale;
2741 for (i = 0;i < surface->num_vertices;i++)
2743 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);
2744 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);
2745 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2746 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2747 // LordHavoc: calc lightmap data offset for vertex lighting to use
2750 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2754 if (cl_stainmaps.integer)
2756 // allocate stainmaps for permanent marks on walls and clear white
2757 unsigned char *stainsamples = NULL;
2758 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2759 memset(stainsamples, 255, stainmapsize);
2761 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2763 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2765 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2766 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2767 surface->lightmapinfo->stainsamples = stainsamples;
2768 stainsamples += ssize * tsize * 3;
2773 // generate ushort elements array if possible
2774 if (loadmodel->surfmesh.data_element3s)
2775 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2776 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2779 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2782 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2783 node->parent = parent;
2786 // this is a node, recurse to children
2787 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2788 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2789 // combine supercontents of children
2790 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2795 mleaf_t *leaf = (mleaf_t *)node;
2796 // if this is a leaf, calculate supercontents mask from all collidable
2797 // primitives in the leaf (brushes and collision surfaces)
2798 // also flag if the leaf contains any collision surfaces
2799 leaf->combinedsupercontents = 0;
2800 // combine the supercontents values of all brushes in this leaf
2801 for (j = 0;j < leaf->numleafbrushes;j++)
2802 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2803 // check if this leaf contains any collision surfaces (q3 patches)
2804 for (j = 0;j < leaf->numleafsurfaces;j++)
2806 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2807 if (surface->num_collisiontriangles)
2809 leaf->containscollisionsurfaces = true;
2810 leaf->combinedsupercontents |= surface->texture->supercontents;
2816 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2818 int i, j, count, p, child[2];
2820 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2822 if (sb->cursize % structsize)
2823 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2824 count = sb->cursize / structsize;
2826 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2827 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2829 loadmodel->brush.data_nodes = out;
2830 loadmodel->brush.num_nodes = count;
2832 for ( i=0 ; i<count ; i++, out++)
2834 p = MSG_ReadLittleLong(sb);
2835 out->plane = loadmodel->brush.data_planes + p;
2837 if (loadmodel->brush.isbsp2rmqe)
2839 child[0] = MSG_ReadLittleLong(sb);
2840 child[1] = MSG_ReadLittleLong(sb);
2841 out->mins[0] = MSG_ReadLittleShort(sb);
2842 out->mins[1] = MSG_ReadLittleShort(sb);
2843 out->mins[2] = MSG_ReadLittleShort(sb);
2844 out->maxs[0] = MSG_ReadLittleShort(sb);
2845 out->maxs[1] = MSG_ReadLittleShort(sb);
2846 out->maxs[2] = MSG_ReadLittleShort(sb);
2847 out->firstsurface = MSG_ReadLittleLong(sb);
2848 out->numsurfaces = MSG_ReadLittleLong(sb);
2850 else if (loadmodel->brush.isbsp2)
2852 child[0] = MSG_ReadLittleLong(sb);
2853 child[1] = MSG_ReadLittleLong(sb);
2854 out->mins[0] = MSG_ReadLittleFloat(sb);
2855 out->mins[1] = MSG_ReadLittleFloat(sb);
2856 out->mins[2] = MSG_ReadLittleFloat(sb);
2857 out->maxs[0] = MSG_ReadLittleFloat(sb);
2858 out->maxs[1] = MSG_ReadLittleFloat(sb);
2859 out->maxs[2] = MSG_ReadLittleFloat(sb);
2860 out->firstsurface = MSG_ReadLittleLong(sb);
2861 out->numsurfaces = MSG_ReadLittleLong(sb);
2865 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2866 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2867 if (child[0] >= count)
2869 if (child[1] >= count)
2872 out->mins[0] = MSG_ReadLittleShort(sb);
2873 out->mins[1] = MSG_ReadLittleShort(sb);
2874 out->mins[2] = MSG_ReadLittleShort(sb);
2875 out->maxs[0] = MSG_ReadLittleShort(sb);
2876 out->maxs[1] = MSG_ReadLittleShort(sb);
2877 out->maxs[2] = MSG_ReadLittleShort(sb);
2879 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2880 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2883 for (j=0 ; j<2 ; j++)
2885 // LordHavoc: this code supports broken bsp files produced by
2886 // arguire qbsp which can produce more than 32768 nodes, any value
2887 // below count is assumed to be a node number, any other value is
2888 // assumed to be a leaf number
2892 if (p < loadmodel->brush.num_nodes)
2893 out->children[j] = loadmodel->brush.data_nodes + p;
2896 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2897 // map it to the solid leaf
2898 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2903 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2905 if (p < loadmodel->brush.num_leafs)
2906 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2909 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2910 // map it to the solid leaf
2911 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2917 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2920 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2923 int i, j, count, p, firstmarksurface, nummarksurfaces;
2924 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2926 if (sb->cursize % structsize)
2927 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2928 count = sb->cursize / structsize;
2929 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2931 loadmodel->brush.data_leafs = out;
2932 loadmodel->brush.num_leafs = count;
2933 // get visleafs from the submodel data
2934 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2935 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2936 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2937 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2939 // FIXME: this function could really benefit from some error checking
2940 for ( i=0 ; i<count ; i++, out++)
2942 out->contents = MSG_ReadLittleLong(sb);
2944 out->clusterindex = i - 1;
2945 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2946 out->clusterindex = -1;
2948 p = MSG_ReadLittleLong(sb);
2949 // ignore visofs errors on leaf 0 (solid)
2950 if (p >= 0 && out->clusterindex >= 0)
2952 if (p >= loadmodel->brushq1.num_compressedpvs)
2953 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2955 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);
2958 if (loadmodel->brush.isbsp2rmqe)
2960 out->mins[0] = MSG_ReadLittleShort(sb);
2961 out->mins[1] = MSG_ReadLittleShort(sb);
2962 out->mins[2] = MSG_ReadLittleShort(sb);
2963 out->maxs[0] = MSG_ReadLittleShort(sb);
2964 out->maxs[1] = MSG_ReadLittleShort(sb);
2965 out->maxs[2] = MSG_ReadLittleShort(sb);
2967 firstmarksurface = MSG_ReadLittleLong(sb);
2968 nummarksurfaces = MSG_ReadLittleLong(sb);
2970 else if (loadmodel->brush.isbsp2)
2972 out->mins[0] = MSG_ReadLittleFloat(sb);
2973 out->mins[1] = MSG_ReadLittleFloat(sb);
2974 out->mins[2] = MSG_ReadLittleFloat(sb);
2975 out->maxs[0] = MSG_ReadLittleFloat(sb);
2976 out->maxs[1] = MSG_ReadLittleFloat(sb);
2977 out->maxs[2] = MSG_ReadLittleFloat(sb);
2979 firstmarksurface = MSG_ReadLittleLong(sb);
2980 nummarksurfaces = MSG_ReadLittleLong(sb);
2984 out->mins[0] = MSG_ReadLittleShort(sb);
2985 out->mins[1] = MSG_ReadLittleShort(sb);
2986 out->mins[2] = MSG_ReadLittleShort(sb);
2987 out->maxs[0] = MSG_ReadLittleShort(sb);
2988 out->maxs[1] = MSG_ReadLittleShort(sb);
2989 out->maxs[2] = MSG_ReadLittleShort(sb);
2991 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2992 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2995 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2997 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2998 out->numleafsurfaces = nummarksurfaces;
3002 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
3003 out->firstleafsurface = NULL;
3004 out->numleafsurfaces = 0;
3007 for (j = 0;j < 4;j++)
3008 out->ambient_sound_level[j] = MSG_ReadByte(sb);
3012 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
3016 const unsigned char *pvs;
3017 // if there's no vis data, assume supported (because everything is visible all the time)
3018 if (!loadmodel->brush.data_pvsclusters)
3020 // check all liquid leafs to see if they can see into empty leafs, if any
3021 // can we can assume this map supports r_wateralpha
3022 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3024 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3026 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3027 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3028 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3035 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3040 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3042 if (sb->cursize % structsize)
3043 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3044 count = sb->cursize / structsize;
3045 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3047 loadmodel->brushq1.clipnodes = out;
3048 loadmodel->brushq1.numclipnodes = count;
3050 for (i = 1; i < MAX_MAP_HULLS; i++)
3052 hull = &loadmodel->brushq1.hulls[i];
3053 hull->clipnodes = out;
3054 hull->firstclipnode = 0;
3055 hull->lastclipnode = count-1;
3056 hull->planes = loadmodel->brush.data_planes;
3057 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3058 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3059 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3060 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3061 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3062 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3063 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3066 for (i=0 ; i<count ; i++, out++)
3068 out->planenum = MSG_ReadLittleLong(sb);
3069 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3070 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3071 if (loadmodel->brush.isbsp2)
3073 out->children[0] = MSG_ReadLittleLong(sb);
3074 out->children[1] = MSG_ReadLittleLong(sb);
3075 if (out->children[0] >= count)
3076 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3077 if (out->children[1] >= count)
3078 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3082 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3083 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3084 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3085 if (out->children[0] >= count)
3086 out->children[0] -= 65536;
3087 if (out->children[1] >= count)
3088 out->children[1] -= 65536;
3093 //Duplicate the drawing hull structure as a clipping hull
3094 static void Mod_Q1BSP_MakeHull0(void)
3101 hull = &loadmodel->brushq1.hulls[0];
3103 in = loadmodel->brush.data_nodes;
3104 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3106 hull->clipnodes = out;
3107 hull->firstclipnode = 0;
3108 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3109 hull->planes = loadmodel->brush.data_planes;
3111 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3113 out->planenum = in->plane - loadmodel->brush.data_planes;
3114 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3115 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3119 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3122 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3124 if (sb->cursize % structsize)
3125 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3126 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3127 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3129 if (loadmodel->brush.isbsp2)
3131 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3133 j = MSG_ReadLittleLong(sb);
3134 if (j < 0 || j >= loadmodel->num_surfaces)
3135 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3136 loadmodel->brush.data_leafsurfaces[i] = j;
3141 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3143 j = (unsigned short) MSG_ReadLittleShort(sb);
3144 if (j >= loadmodel->num_surfaces)
3145 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3146 loadmodel->brush.data_leafsurfaces[i] = j;
3151 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3156 if (sb->cursize % structsize)
3157 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3158 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3159 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3161 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3162 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3166 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3170 int structsize = 20;
3172 if (sb->cursize % structsize)
3173 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3174 loadmodel->brush.num_planes = sb->cursize / structsize;
3175 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3177 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3179 out->normal[0] = MSG_ReadLittleFloat(sb);
3180 out->normal[1] = MSG_ReadLittleFloat(sb);
3181 out->normal[2] = MSG_ReadLittleFloat(sb);
3182 out->dist = MSG_ReadLittleFloat(sb);
3183 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3188 static void Mod_Q1BSP_LoadMapBrushes(void)
3192 int submodel, numbrushes;
3193 qboolean firstbrush;
3194 char *text, *maptext;
3195 char mapfilename[MAX_QPATH];
3196 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3197 strlcat (mapfilename, ".map", sizeof (mapfilename));
3198 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3202 if (!COM_ParseToken_Simple(&data, false, false, true))
3207 if (!COM_ParseToken_Simple(&data, false, false, true))
3209 if (com_token[0] != '{')
3215 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3218 if (!COM_ParseToken_Simple(&data, false, false, true))
3220 if (com_token[0] == '}')
3221 break; // end of entity
3222 if (com_token[0] == '{')
3229 if (submodel > loadmodel->brush.numsubmodels)
3231 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3235 model = loadmodel->brush.submodels[submodel];
3242 if (!COM_ParseToken_Simple(&data, false, false, true))
3244 if (com_token[0] == '}')
3245 break; // end of brush
3246 // each brush face should be this format:
3247 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3248 // FIXME: support hl .map format
3249 for (pointnum = 0;pointnum < 3;pointnum++)
3251 COM_ParseToken_Simple(&data, false, false, true);
3252 for (componentnum = 0;componentnum < 3;componentnum++)
3254 COM_ParseToken_Simple(&data, false, false, true);
3255 point[pointnum][componentnum] = atof(com_token);
3257 COM_ParseToken_Simple(&data, false, false, true);
3259 COM_ParseToken_Simple(&data, false, false, true);
3260 strlcpy(facetexture, com_token, sizeof(facetexture));
3261 COM_ParseToken_Simple(&data, false, false, true);
3262 //scroll_s = atof(com_token);
3263 COM_ParseToken_Simple(&data, false, false, true);
3264 //scroll_t = atof(com_token);
3265 COM_ParseToken_Simple(&data, false, false, true);
3266 //rotate = atof(com_token);
3267 COM_ParseToken_Simple(&data, false, false, true);
3268 //scale_s = atof(com_token);
3269 COM_ParseToken_Simple(&data, false, false, true);
3270 //scale_t = atof(com_token);
3271 TriangleNormal(point[0], point[1], point[2], planenormal);
3272 VectorNormalizeDouble(planenormal);
3273 planedist = DotProduct(point[0], planenormal);
3274 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3284 #define MAX_PORTALPOINTS 64
3286 typedef struct portal_s
3289 mnode_t *nodes[2]; // [0] = front side of plane
3290 struct portal_s *next[2];
3292 double points[3*MAX_PORTALPOINTS];
3293 struct portal_s *chain; // all portals are linked into a list
3297 static memexpandablearray_t portalarray;
3299 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3301 // process only nodes (leafs already had their box calculated)
3305 // calculate children first
3306 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3307 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3309 // make combined bounding box from children
3310 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3311 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3312 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3313 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3314 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3315 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3318 static void Mod_Q1BSP_FinalizePortals(void)
3320 int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3324 mleaf_t *leaf, *endleaf;
3326 // tally up portal and point counts and recalculate bounding boxes for all
3327 // leafs (because qbsp is very sloppy)
3328 leaf = loadmodel->brush.data_leafs;
3329 endleaf = leaf + loadmodel->brush.num_leafs;
3330 if (mod_recalculatenodeboxes.integer)
3332 for (;leaf < endleaf;leaf++)
3334 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3335 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3340 for (portalindex = 0;portalindex < portalrange;portalindex++)
3342 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3345 // note: this check must match the one below or it will usually corrupt memory
3346 // 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
3347 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3350 numpoints += p->numpoints * 2;
3353 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3354 loadmodel->brush.num_portals = numportals;
3355 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3356 loadmodel->brush.num_portalpoints = numpoints;
3357 // clear all leaf portal chains
3358 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3359 loadmodel->brush.data_leafs[i].portals = NULL;
3360 // process all portals in the global portal chain, while freeing them
3361 portal = loadmodel->brush.data_portals;
3362 point = loadmodel->brush.data_portalpoints;
3363 for (portalindex = 0;portalindex < portalrange;portalindex++)
3365 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3368 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3370 // note: this check must match the one above or it will usually corrupt memory
3371 // 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
3372 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3374 // first make the back to front portal(forward portal)
3375 portal->points = point;
3376 portal->numpoints = p->numpoints;
3377 portal->plane.dist = p->plane.dist;
3378 VectorCopy(p->plane.normal, portal->plane.normal);
3379 portal->here = (mleaf_t *)p->nodes[1];
3380 portal->past = (mleaf_t *)p->nodes[0];
3382 for (j = 0;j < portal->numpoints;j++)
3384 VectorCopy(p->points + j*3, point->position);
3387 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3388 PlaneClassify(&portal->plane);
3390 // link into leaf's portal chain
3391 portal->next = portal->here->portals;
3392 portal->here->portals = portal;
3394 // advance to next portal
3397 // then make the front to back portal(backward portal)
3398 portal->points = point;
3399 portal->numpoints = p->numpoints;
3400 portal->plane.dist = -p->plane.dist;
3401 VectorNegate(p->plane.normal, portal->plane.normal);
3402 portal->here = (mleaf_t *)p->nodes[0];
3403 portal->past = (mleaf_t *)p->nodes[1];
3405 for (j = portal->numpoints - 1;j >= 0;j--)
3407 VectorCopy(p->points + j*3, point->position);
3410 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3411 PlaneClassify(&portal->plane);
3413 // link into leaf's portal chain
3414 portal->next = portal->here->portals;
3415 portal->here->portals = portal;
3417 // advance to next portal
3420 // add the portal's polygon points to the leaf bounding boxes
3421 if (mod_recalculatenodeboxes.integer)
3423 for (i = 0;i < 2;i++)
3425 leaf = (mleaf_t *)p->nodes[i];
3426 for (j = 0;j < p->numpoints;j++)
3428 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3429 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3430 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3431 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3432 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3433 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3439 // now recalculate the node bounding boxes from the leafs
3440 if (mod_recalculatenodeboxes.integer)
3441 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3449 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3452 Host_Error("AddPortalToNodes: NULL front node");
3454 Host_Error("AddPortalToNodes: NULL back node");
3455 if (p->nodes[0] || p->nodes[1])
3456 Host_Error("AddPortalToNodes: already included");
3457 // 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
3459 p->nodes[0] = front;
3460 p->next[0] = (portal_t *)front->portals;
3461 front->portals = (mportal_t *)p;
3464 p->next[1] = (portal_t *)back->portals;
3465 back->portals = (mportal_t *)p;
3470 RemovePortalFromNode
3473 static void RemovePortalFromNodes(portal_t *portal)
3477 void **portalpointer;
3479 for (i = 0;i < 2;i++)
3481 node = portal->nodes[i];
3483 portalpointer = (void **) &node->portals;
3486 t = (portal_t *)*portalpointer;
3488 Host_Error("RemovePortalFromNodes: portal not in leaf");
3492 if (portal->nodes[0] == node)
3494 *portalpointer = portal->next[0];
3495 portal->nodes[0] = NULL;
3497 else if (portal->nodes[1] == node)
3499 *portalpointer = portal->next[1];
3500 portal->nodes[1] = NULL;
3503 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3507 if (t->nodes[0] == node)
3508 portalpointer = (void **) &t->next[0];
3509 else if (t->nodes[1] == node)
3510 portalpointer = (void **) &t->next[1];
3512 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3517 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3518 static double *portalpointsbuffer;
3519 static int portalpointsbufferoffset;
3520 static int portalpointsbuffersize;
3521 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3524 mnode_t *front, *back, *other_node;
3525 mplane_t clipplane, *plane;
3526 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3527 int numfrontpoints, numbackpoints;
3528 double *frontpoints, *backpoints;
3530 // if a leaf, we're done
3534 // get some space for our clipping operations to use
3535 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3537 portalpointsbuffersize = portalpointsbufferoffset * 2;
3538 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3540 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3541 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3542 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3543 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3545 plane = node->plane;
3547 front = node->children[0];
3548 back = node->children[1];
3550 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3552 // create the new portal by generating a polygon for the node plane,
3553 // and clipping it by all of the other portals(which came from nodes above this one)
3554 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3555 nodeportal->plane = *plane;
3557 // 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)
3558 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);
3559 nodeportal->numpoints = 4;
3560 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3561 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3563 clipplane = portal->plane;
3564 if (portal->nodes[0] == portal->nodes[1])
3565 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3566 if (portal->nodes[0] == node)
3568 else if (portal->nodes[1] == node)
3570 clipplane.dist = -clipplane.dist;
3571 VectorNegate(clipplane.normal, clipplane.normal);
3576 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3577 side = 0; // hush warning
3580 for (i = 0;i < nodeportal->numpoints*3;i++)
3581 frontpoints[i] = nodeportal->points[i];
3582 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);
3583 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3587 if (nodeportal->numpoints < 3)
3589 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3590 nodeportal->numpoints = 0;
3592 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3594 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3595 nodeportal->numpoints = 0;
3598 AddPortalToNodes(nodeportal, front, back);
3600 // split the portals of this node along this node's plane and assign them to the children of this node
3601 // (migrating the portals downward through the tree)
3602 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3604 if (portal->nodes[0] == portal->nodes[1])
3605 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3606 if (portal->nodes[0] == node)
3608 else if (portal->nodes[1] == node)
3612 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3613 side = 0; // hush warning
3615 nextportal = portal->next[side];
3616 if (!portal->numpoints)
3619 other_node = portal->nodes[!side];
3620 RemovePortalFromNodes(portal);
3622 // cut the portal into two portals, one on each side of the node plane
3623 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);
3625 if (!numfrontpoints)
3628 AddPortalToNodes(portal, back, other_node);
3630 AddPortalToNodes(portal, other_node, back);
3636 AddPortalToNodes(portal, front, other_node);
3638 AddPortalToNodes(portal, other_node, front);
3642 // the portal is split
3643 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3644 temp = splitportal->chain;
3645 *splitportal = *portal;
3646 splitportal->chain = temp;
3647 for (i = 0;i < numbackpoints*3;i++)
3648 splitportal->points[i] = backpoints[i];
3649 splitportal->numpoints = numbackpoints;
3650 for (i = 0;i < numfrontpoints*3;i++)
3651 portal->points[i] = frontpoints[i];
3652 portal->numpoints = numfrontpoints;
3656 AddPortalToNodes(portal, front, other_node);
3657 AddPortalToNodes(splitportal, back, other_node);
3661 AddPortalToNodes(portal, other_node, front);
3662 AddPortalToNodes(splitportal, other_node, back);
3666 Mod_Q1BSP_RecursiveNodePortals(front);
3667 Mod_Q1BSP_RecursiveNodePortals(back);
3669 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3672 static void Mod_Q1BSP_MakePortals(void)
3674 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3675 portalpointsbufferoffset = 0;
3676 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3677 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3678 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3679 Mem_Free(portalpointsbuffer);
3680 portalpointsbuffer = NULL;
3681 portalpointsbufferoffset = 0;
3682 portalpointsbuffersize = 0;
3683 Mod_Q1BSP_FinalizePortals();
3684 Mem_ExpandableArray_FreeArray(&portalarray);
3687 //Returns PVS data for a given point
3688 //(note: can return NULL)
3689 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3692 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3694 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3695 if (((mleaf_t *)node)->clusterindex >= 0)
3696 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3701 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)
3705 float d = PlaneDiff(org, node->plane);
3707 node = node->children[0];
3708 else if (d < -radius)
3709 node = node->children[1];
3712 // go down both sides
3713 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3714 node = node->children[1];
3717 // if this leaf is in a cluster, accumulate the pvs bits
3718 if (((mleaf_t *)node)->clusterindex >= 0)
3721 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3722 for (i = 0;i < pvsbytes;i++)
3723 pvsbuffer[i] |= pvs[i];
3727 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3728 //of the given point.
3729 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3731 int bytes = model->brush.num_pvsclusterbytes;
3732 bytes = min(bytes, pvsbufferlength);
3733 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3735 memset(pvsbuffer, 0xFF, bytes);
3739 memset(pvsbuffer, 0, bytes);
3740 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3744 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3749 VectorSubtract(inmaxs, inmins, size);
3750 if (cmodel->brush.ishlbsp)
3753 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3754 else if (size[0] <= 32)
3756 if (size[2] < 54) // pick the nearest of 36 or 72
3757 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3759 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3762 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3767 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3768 else if (size[0] <= 32)
3769 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3771 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3773 VectorCopy(inmins, outmins);
3774 VectorAdd(inmins, hull->clip_size, outmaxs);
3777 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3780 int numshadowmeshtriangles = 0;
3781 msurface_t *surface;
3782 if (cls.state == ca_dedicated)
3784 // make a single combined shadow mesh to allow optimized shadow volume creation
3786 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3788 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3789 numshadowmeshtriangles += surface->num_triangles;
3791 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3792 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3793 if (surface->num_triangles > 0)
3794 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));
3795 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3796 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3797 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3799 return numshadowmeshtriangles;
3802 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, int skipsupercontentsmask);
3804 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3807 sizebuf_t lumpsb[HEADER_LUMPS];
3809 float dist, modelyawradius, modelradius;
3810 msurface_t *surface;
3811 hullinfo_t hullinfo;
3812 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3813 model_brush_lightstyleinfo_t styleinfo[256];
3814 unsigned char *datapointer;
3817 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3819 mod->type = mod_brushq1;
3821 mod->brush.ishlbsp = false;
3822 mod->brush.isbsp2rmqe = false;
3823 mod->brush.isbsp2 = false;
3824 mod->brush.isq2bsp = false;
3825 mod->brush.isq3bsp = false;
3826 mod->brush.skymasking = true;
3827 i = MSG_ReadLittleLong(&sb);
3831 mod->modeldatatypestring = "Q1BSP";
3834 mod->brush.ishlbsp = true;
3835 mod->modeldatatypestring = "HLBSP";
3837 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3838 mod->brush.isbsp2 = true;
3839 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3840 mod->modeldatatypestring = "Q1BSP2rmqe";
3842 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3843 mod->brush.isbsp2 = true;
3844 mod->modeldatatypestring = "Q1BSP2";
3847 mod->modeldatatypestring = "Unknown BSP";
3848 Host_Error("Mod_Q1BSP_Load: %s has wrong version number %i: supported versions are 29 (Quake), 30 (Half-Life), \"BSP2\" or \"2PSB\" (rmqe)", mod->name, i);
3852 // fill in hull info
3853 VectorClear (hullinfo.hullsizes[0][0]);
3854 VectorClear (hullinfo.hullsizes[0][1]);
3855 if (mod->brush.ishlbsp)
3857 hullinfo.filehulls = 4;
3858 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3859 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3860 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3861 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3862 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3863 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3867 hullinfo.filehulls = 4;
3868 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3869 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3870 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3871 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3875 for (i = 0; i < HEADER_LUMPS; i++)
3877 int offset = MSG_ReadLittleLong(&sb);
3878 int size = MSG_ReadLittleLong(&sb);
3879 if (offset < 0 || offset + size > sb.cursize)
3880 Host_Error("Mod_Q1BSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
3881 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3884 mod->soundfromcenter = true;
3885 mod->TraceBox = Mod_Q1BSP_TraceBox;
3886 mod->TraceLine = Mod_Q1BSP_TraceLine;
3887 mod->TracePoint = Mod_Q1BSP_TracePoint;
3888 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3889 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3890 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3891 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3892 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3893 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3894 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3895 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3896 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3897 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3898 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3899 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3900 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3901 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3902 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3903 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3904 mod->Draw = R_Q1BSP_Draw;
3905 mod->DrawDepth = R_Q1BSP_DrawDepth;
3906 mod->DrawDebug = R_Q1BSP_DrawDebug;
3907 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3908 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3909 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3910 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3911 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3912 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3913 mod->DrawLight = R_Q1BSP_DrawLight;
3917 mod->brush.qw_md4sum = 0;
3918 mod->brush.qw_md4sum2 = 0;
3919 for (i = 0;i < HEADER_LUMPS;i++)
3922 if (i == LUMP_ENTITIES)
3924 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3925 mod->brush.qw_md4sum ^= LittleLong(temp);
3926 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3928 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3931 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3932 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3933 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3934 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3935 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3936 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3937 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3938 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3939 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3940 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3941 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3942 // load submodels before leafs because they contain the number of vis leafs
3943 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3944 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3945 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3946 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3948 for (i = 0; i < HEADER_LUMPS; i++)
3949 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3950 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3952 // check if the map supports transparent water rendering
3953 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3955 // we don't need the compressed pvs data anymore
3956 if (mod->brushq1.data_compressedpvs)
3957 Mem_Free(mod->brushq1.data_compressedpvs);
3958 mod->brushq1.data_compressedpvs = NULL;
3959 mod->brushq1.num_compressedpvs = 0;
3961 Mod_Q1BSP_MakeHull0();
3962 if (mod_bsp_portalize.integer)
3963 Mod_Q1BSP_MakePortals();
3965 mod->numframes = 2; // regular and alternate animation
3968 // make a single combined shadow mesh to allow optimized shadow volume creation
3969 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3971 if (loadmodel->brush.numsubmodels)
3972 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3974 // LordHavoc: to clear the fog around the original quake submodel code, I
3976 // first of all, some background info on the submodels:
3977 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3978 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3979 // now the weird for loop itself:
3980 // the loop functions in an odd way, on each iteration it sets up the
3981 // current 'mod' model (which despite the confusing code IS the model of
3982 // the number i), at the end of the loop it duplicates the model to become
3983 // the next submodel, and loops back to set up the new submodel.
3985 // LordHavoc: now the explanation of my sane way (which works identically):
3986 // set up the world model, then on each submodel copy from the world model
3987 // and set up the submodel with the respective model info.
3988 totalstylesurfaces = 0;
3990 for (i = 0;i < mod->brush.numsubmodels;i++)
3992 memset(stylecounts, 0, sizeof(stylecounts));
3993 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3995 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3996 for (j = 0;j < MAXLIGHTMAPS;j++)
3997 stylecounts[surface->lightmapinfo->styles[j]]++;
3999 for (k = 0;k < 255;k++)
4003 totalstylesurfaces += stylecounts[k];
4006 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4007 for (i = 0;i < mod->brush.numsubmodels;i++)
4009 // LordHavoc: this code was originally at the end of this loop, but
4010 // has been transformed to something more readable at the start here.
4015 // duplicate the basic information
4016 dpsnprintf(name, sizeof(name), "*%i", i);
4017 mod = Mod_FindName(name, loadmodel->name);
4018 // copy the base model to this one
4020 // rename the clone back to its proper name
4021 strlcpy(mod->name, name, sizeof(mod->name));
4022 mod->brush.parentmodel = loadmodel;
4023 // textures and memory belong to the main model
4024 mod->texturepool = NULL;
4025 mod->mempool = NULL;
4026 mod->brush.GetPVS = NULL;
4027 mod->brush.FatPVS = NULL;
4028 mod->brush.BoxTouchingPVS = NULL;
4029 mod->brush.BoxTouchingLeafPVS = NULL;
4030 mod->brush.BoxTouchingVisibleLeafs = NULL;
4031 mod->brush.FindBoxClusters = NULL;
4032 mod->brush.LightPoint = NULL;
4033 mod->brush.AmbientSoundLevelsForPoint = NULL;
4036 mod->brush.submodel = i;
4038 if (loadmodel->brush.submodels)
4039 loadmodel->brush.submodels[i] = mod;
4041 bm = &mod->brushq1.submodels[i];
4043 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4044 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4046 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4047 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4050 mod->firstmodelsurface = bm->firstface;
4051 mod->nummodelsurfaces = bm->numfaces;
4053 // set node/leaf parents for this submodel
4054 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4056 // make the model surface list (used by shadowing/lighting)
4057 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4058 Mod_MakeSortedSurfaces(mod);
4060 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4061 // (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)
4062 VectorCopy(bm->mins, mod->normalmins);
4063 VectorCopy(bm->maxs, mod->normalmaxs);
4064 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4065 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4066 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4067 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4068 modelradius = modelyawradius + modelradius * modelradius;
4069 modelyawradius = sqrt(modelyawradius);
4070 modelradius = sqrt(modelradius);
4071 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4072 mod->yawmins[2] = mod->normalmins[2];
4073 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4074 mod->yawmaxs[2] = mod->normalmaxs[2];
4075 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4076 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4077 mod->radius = modelradius;
4078 mod->radius2 = modelradius * modelradius;
4080 // this gets altered below if sky or water is used
4081 mod->DrawSky = NULL;
4082 mod->DrawAddWaterPlanes = NULL;
4084 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4085 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4086 if (mod->nummodelsurfaces)
4088 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4089 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4091 if (j < mod->nummodelsurfaces)
4092 mod->DrawSky = R_Q1BSP_DrawSky;
4094 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4095 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4097 if (j < mod->nummodelsurfaces)
4098 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4100 // build lightstyle update chains
4101 // (used to rapidly mark lightmapupdateflags on many surfaces
4102 // when d_lightstylevalue changes)
4103 memset(stylecounts, 0, sizeof(stylecounts));
4104 for (k = 0;k < mod->nummodelsurfaces;k++)
4106 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4107 for (j = 0;j < MAXLIGHTMAPS;j++)
4108 stylecounts[surface->lightmapinfo->styles[j]]++;
4110 mod->brushq1.num_lightstyles = 0;
4111 for (k = 0;k < 255;k++)
4115 styleinfo[mod->brushq1.num_lightstyles].style = k;
4116 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4117 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4118 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4119 remapstyles[k] = mod->brushq1.num_lightstyles;
4120 mod->brushq1.num_lightstyles++;
4123 for (k = 0;k < mod->nummodelsurfaces;k++)
4125 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4126 for (j = 0;j < MAXLIGHTMAPS;j++)
4128 if (surface->lightmapinfo->styles[j] != 255)
4130 int r = remapstyles[surface->lightmapinfo->styles[j]];
4131 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4135 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4136 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4140 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4141 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4143 //mod->brushq1.num_visleafs = bm->visleafs;
4145 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4146 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4148 if (mod_q1bsp_polygoncollisions.integer)
4150 mod->collision_bih = mod->render_bih;
4151 // point traces and contents checks still use the bsp tree
4152 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4153 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4154 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4155 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4158 // generate VBOs and other shared data before cloning submodels
4162 Mod_Q1BSP_LoadMapBrushes();
4163 //Mod_Q1BSP_ProcessLightList();
4167 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);
4170 int Mod_Q2BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
4172 int supercontents = 0;
4173 if (nativecontents & CONTENTSQ2_SOLID)
4174 supercontents |= SUPERCONTENTS_SOLID;
4175 if (nativecontents & CONTENTSQ2_WATER)
4176 supercontents |= SUPERCONTENTS_WATER;
4177 if (nativecontents & CONTENTSQ2_SLIME)
4178 supercontents |= SUPERCONTENTS_SLIME;
4179 if (nativecontents & CONTENTSQ2_LAVA)
4180 supercontents |= SUPERCONTENTS_LAVA;
4181 if (nativecontents & CONTENTSQ2_MONSTER)
4182 supercontents |= SUPERCONTENTS_BODY;
4183 if (nativecontents & CONTENTSQ2_DEADMONSTER)
4184 supercontents |= SUPERCONTENTS_CORPSE;
4185 if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4186 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4187 if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4188 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4189 if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4190 supercontents |= SUPERCONTENTS_OPAQUE;
4191 return supercontents;
4194 int Mod_Q2BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
4196 int nativecontents = 0;
4197 if (supercontents & SUPERCONTENTS_SOLID)
4198 nativecontents |= CONTENTSQ2_SOLID;
4199 if (supercontents & SUPERCONTENTS_WATER)
4200 nativecontents |= CONTENTSQ2_WATER;
4201 if (supercontents & SUPERCONTENTS_SLIME)
4202 nativecontents |= CONTENTSQ2_SLIME;
4203 if (supercontents & SUPERCONTENTS_LAVA)
4204 nativecontents |= CONTENTSQ2_LAVA;
4205 if (supercontents & SUPERCONTENTS_BODY)
4206 nativecontents |= CONTENTSQ2_MONSTER;
4207 if (supercontents & SUPERCONTENTS_CORPSE)
4208 nativecontents |= CONTENTSQ2_DEADMONSTER;
4209 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4210 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4211 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4212 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4213 if (!(supercontents & SUPERCONTENTS_OPAQUE))
4214 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4215 return nativecontents;
4218 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4221 loadmodel->brushq1.num_compressedpvs = 0;
4222 loadmodel->brushq1.data_compressedpvs = NULL;
4223 loadmodel->brush.num_pvsclusters = 0;
4224 loadmodel->brush.num_pvsclusterbytes = 0;
4225 loadmodel->brush.data_pvsclusters = NULL;
4230 count = MSG_ReadLittleLong(sb);
4231 loadmodel->brush.num_pvsclusters = count;
4232 loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4233 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4234 for (i = 0;i < count;i++)
4236 int pvsofs = MSG_ReadLittleLong(sb);
4237 /*int phsofs = */MSG_ReadLittleLong(sb);
4238 // decompress the vis data for this cluster
4239 // (note this accesses the underlying data store of sb, which is kind of evil)
4240 Mod_Q1BSP_DecompressVis(sb->data + pvsofs, sb->data + sb->cursize, loadmodel->brush.data_pvsclusters + i * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (i+1) * loadmodel->brush.num_pvsclusterbytes);
4242 // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4243 sb->readcount = sb->cursize;
4246 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4248 int i, j, count, p, child[2];
4250 int structsize = 28;
4252 if (sb->cursize % structsize)
4253 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4254 count = sb->cursize / structsize;
4256 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4257 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4259 loadmodel->brush.data_nodes = out;
4260 loadmodel->brush.num_nodes = count;
4262 for ( i=0 ; i<count ; i++, out++)
4264 p = MSG_ReadLittleLong(sb);
4265 out->plane = loadmodel->brush.data_planes + p;
4266 child[0] = MSG_ReadLittleLong(sb);
4267 child[1] = MSG_ReadLittleLong(sb);
4268 out->mins[0] = MSG_ReadLittleShort(sb);
4269 out->mins[1] = MSG_ReadLittleShort(sb);
4270 out->mins[2] = MSG_ReadLittleShort(sb);
4271 out->maxs[0] = MSG_ReadLittleShort(sb);
4272 out->maxs[1] = MSG_ReadLittleShort(sb);
4273 out->maxs[2] = MSG_ReadLittleShort(sb);
4274 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4275 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4276 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4278 Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4279 out->firstsurface = 0;
4280 out->numsurfaces = 0;
4282 for (j=0 ; j<2 ; j++)
4287 if (p < loadmodel->brush.num_nodes)
4288 out->children[j] = loadmodel->brush.data_nodes + p;
4291 Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4292 // map it to the solid leaf
4293 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4298 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4300 if (p < loadmodel->brush.num_leafs)
4301 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4304 Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4305 // map it to the solid leaf
4306 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4312 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
4315 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4319 int structsize = 76;
4320 int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4321 char filename[MAX_QPATH];
4323 if (sb->cursize % structsize)
4324 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4325 count = sb->cursize / structsize;
4326 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4327 loadmodel->brushq1.texinfo = out;
4328 loadmodel->brushq1.numtexinfo = count;
4329 loadmodel->num_texturesperskin = 0;
4330 loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4332 for (i = 0;i < count;i++, out++)
4335 for (k = 0;k < 2;k++)
4336 for (j = 0;j < 4;j++)
4337 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4339 out->q2flags = MSG_ReadLittleLong(sb);
4340 out->q2value = MSG_ReadLittleLong(sb);
4341 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4342 out->q2texture[31] = 0; // make absolutely sure it is terminated
4343 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4345 // find an existing match for the texture if possible
4346 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4347 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4348 if (!strcmp(filename, loadmodel->data_textures[j].name)
4349 && out->q2flags == loadmodel->data_textures[j].q2flags
4350 && out->q2value == loadmodel->data_textures[j].q2value)
4352 // if we don't find the texture, store the new texture
4353 if (j == loadmodel->num_texturesperskin)
4355 if (loadmodel->num_texturesperskin < maxtextures)
4357 texture_t *tx = loadmodel->data_textures + j;
4358 int q2flags = out->q2flags;
4359 unsigned char *walfile = NULL;
4360 fs_offset_t walfilesize = 0;
4361 Mod_LoadTextureFromQ3Shader(tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4362 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4363 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4367 LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4377 tx->q2flags = out->q2flags;
4378 tx->q2value = out->q2value;
4379 // also modify the texture to have the correct contents and such based on flags
4380 // note that we create multiple texture_t structures if q2flags differs
4381 if (q2flags & Q2SURF_LIGHT)
4383 // doesn't mean anything to us
4385 if (q2flags & Q2SURF_SLICK)
4387 // would be nice to support...
4389 if (q2flags & Q2SURF_SKY)
4391 // sky is a rather specific thing
4392 q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4393 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
4394 tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4395 tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4397 if (q2flags & Q2SURF_WARP)
4399 // we use a scroll instead of a warp
4400 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4401 // if it's also transparent, we can enable the WATERSHADER
4402 // but we do not set the WATERALPHA flag because we don't
4403 // want to honor r_wateralpha in q2bsp
4404 // (it would go against the artistic intent)
4405 if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4406 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4408 if (q2flags & Q2SURF_TRANS33)
4410 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4411 tx->basealpha = 1.0f / 3.0f;
4412 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4413 if (tx->q2contents & Q2CONTENTS_SOLID)
4414 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4416 if (q2flags & Q2SURF_TRANS66)
4418 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4419 tx->basealpha = 2.0f / 3.0f;
4420 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4421 if (tx->q2contents & Q2CONTENTS_SOLID)
4422 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4424 if (q2flags & Q2SURF_FLOWING)
4426 tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4427 if (q2flags & Q2SURF_WARP)
4428 tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
4430 tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
4431 tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
4433 if (q2flags & Q2SURF_ALPHATEST)
4435 // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4436 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4438 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4440 if (!mod_q2bsp_littransparentsurfaces.integer)
4441 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4443 if (q2flags & Q2SURF_NODRAW)
4445 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4447 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4448 tx->q2contents |= Q2CONTENTS_DETAIL;
4449 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4450 tx->q2contents |= Q2CONTENTS_SOLID;
4451 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4453 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(loadmodel, tx->q2contents);
4454 // set the current values to the base values
4455 tx->currentframe = tx;
4456 tx->currentskinframe = tx->materialshaderpass->skinframes[0];
4457 tx->currentmaterialflags = tx->basematerialflags;
4458 loadmodel->num_texturesperskin++;
4459 loadmodel->num_textures = loadmodel->num_texturesperskin;
4463 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4464 j = 0; // use first texture and give up
4467 // store the index we found for this texture
4468 out->textureindex = j;
4471 // realloc the textures array now that we know how many we actually need
4472 loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4474 // now assemble the texture chains
4475 // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier
4476 for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4479 texture_t *t = loadmodel->data_textures + out->textureindex;
4480 t->currentframe = t; // fix the reallocated pointer
4482 // if this is not animated, skip it
4483 // if this is already processed, skip it (part of an existing sequence)
4484 if (out->q2nexttexinfo == 0 || t->animated)
4487 // store the array of frames to use
4488 t->animated = 2; // q2bsp animation
4489 t->anim_total[0] = 0;
4490 t->anim_total[1] = 0;
4491 // gather up to 10 frames (we don't support more)
4492 for (j = i;j >= 0 && t->anim_total[0] < (int)(sizeof(t->anim_frames[0])/sizeof(t->anim_frames[0][0]));j = loadmodel->brushq1.texinfo[j].q2nexttexinfo)
4494 // detect looping and stop there
4495 if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4497 t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4499 // we could look for the +a sequence here if this is the +0 sequence,
4500 // but it seems that quake2 did not implement that (even though the
4501 // files exist in the baseq2 content)
4503 // write the frame sequence to all the textures involved (just like
4504 // in the q1bsp loader)
4506 // note that this can overwrite the rest of the sequence - so if the
4507 // start of a sequence is found later than the other parts of the
4508 // sequence, it will go back and rewrite them correctly.
4509 for (k = 0;k < t->anim_total[0];k++)
4511 texture_t *txk = t->anim_frames[0][k];
4512 txk->animated = t->animated;
4513 txk->anim_total[0] = t->anim_total[0];
4514 for (l = 0;l < t->anim_total[0];l++)
4515 txk->anim_frames[0][l] = t->anim_frames[0][l];
4520 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4522 // LordHavoc: this fits exactly the same format that we use in .lit files
4523 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4524 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4527 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4530 int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4531 int structsize = 28;
4533 if (sb->cursize % structsize)
4534 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4535 count = sb->cursize / structsize;
4536 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4538 loadmodel->brush.data_leafs = out;
4539 loadmodel->brush.num_leafs = count;
4541 // FIXME: this function could really benefit from some error checking
4542 for ( i=0 ; i<count ; i++, out++)
4544 out->contents = MSG_ReadLittleLong(sb);
4545 out->clusterindex = MSG_ReadLittleShort(sb);
4546 out->areaindex = MSG_ReadLittleShort(sb);
4547 out->mins[0] = MSG_ReadLittleShort(sb);
4548 out->mins[1] = MSG_ReadLittleShort(sb);
4549 out->mins[2] = MSG_ReadLittleShort(sb);
4550 out->maxs[0] = MSG_ReadLittleShort(sb);
4551 out->maxs[1] = MSG_ReadLittleShort(sb);
4552 out->maxs[2] = MSG_ReadLittleShort(sb);
4554 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4555 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4556 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4557 nummarkbrushes = (unsigned short)MSG_ReadLittleShort(sb);
4559 for (j = 0;j < 4;j++)
4560 out->ambient_sound_level[j] = 0;
4562 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4564 Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4565 out->clusterindex = -1;
4568 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4570 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4571 out->numleafsurfaces = nummarksurfaces;
4575 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4576 out->firstleafsurface = NULL;
4577 out->numleafsurfaces = 0;
4580 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4582 out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4583 out->numleafbrushes = nummarkbrushes;
4587 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4588 out->firstleafbrush = NULL;
4589 out->numleafbrushes = 0;
4594 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4599 if (sb->cursize % structsize)
4600 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4601 loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4602 loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4604 for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4606 j = (unsigned short) MSG_ReadLittleShort(sb);
4607 if (j >= loadmodel->brush.num_brushes)
4608 Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4609 loadmodel->brush.data_leafbrushes[i] = j;
4613 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4615 q3mbrushside_t *out;
4619 if (sb->cursize % structsize)
4620 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4621 count = sb->cursize / structsize;
4622 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4624 loadmodel->brush.data_brushsides = out;
4625 loadmodel->brush.num_brushsides = count;
4627 for (i = 0;i < count;i++, out++)
4629 n = (unsigned short)MSG_ReadLittleShort(sb);
4630 if (n < 0 || n >= loadmodel->brush.num_planes)
4631 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4632 out->plane = loadmodel->brush.data_planes + n;
4633 n = MSG_ReadLittleShort(sb);
4636 if (n >= loadmodel->brushq1.numtexinfo)
4637 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4638 out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4642 //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4643 out->texture = &mod_q1bsp_texture_solid;
4648 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4651 int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4652 colplanef_t *planes;
4653 int structsize = 12;
4654 qboolean brushmissingtextures;
4655 int numbrushesmissingtextures = 0;
4656 int numcreatedtextures = 0;
4658 if (sb->cursize % structsize)
4659 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4660 count = sb->cursize / structsize;
4661 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4663 loadmodel->brush.data_brushes = out;
4664 loadmodel->brush.num_brushes = count;
4669 for (i = 0; i < count; i++, out++)
4671 firstside = MSG_ReadLittleLong(sb);
4672 numsides = MSG_ReadLittleLong(sb);
4673 contents = MSG_ReadLittleLong(sb);
4674 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4675 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4677 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4678 out->numbrushsides = numsides;
4679 // convert the contents to our values
4680 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(loadmodel, contents);
4682 // problem: q2bsp brushes have contents but not a texture
4683 // problem: q2bsp brushsides *may* have a texture or may not
4684 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4685 // solution: nasty hacks
4686 brushmissingtextures = false;
4687 out->texture = NULL;
4688 for (j = 0; j < out->numbrushsides; j++)
4690 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4691 brushmissingtextures = true;
4694 // if we can find a matching texture on a brush side we can use it instead of creating one
4695 if (out->firstbrushside[j].texture->supercontents == supercontents)
4696 out->texture = out->firstbrushside[j].texture;
4699 if (brushmissingtextures || out->texture == NULL)
4701 numbrushesmissingtextures++;
4702 // if we didn't find any appropriate texture (matching contents), we'll have to create one
4703 // we could search earlier ones for a matching one but that can be slow
4704 if (out->texture == NULL)
4706 texture_t *validtexture;
4707 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4708 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4709 validtexture->surfaceflags = 0;
4710 validtexture->supercontents = supercontents;
4711 numcreatedtextures++;
4712 out->texture = validtexture;
4714 // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4715 for (j = 0; j < out->numbrushsides; j++)
4716 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4717 out->firstbrushside[j].texture = out->texture;
4720 // make a colbrush from the brush
4722 // make a list of mplane_t structs to construct a colbrush from
4723 if (maxplanes < out->numbrushsides)
4725 maxplanes = out->numbrushsides;
4728 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4730 for (j = 0;j < out->numbrushsides;j++)
4732 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4733 planes[j].dist = out->firstbrushside[j].plane->dist;
4734 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4735 planes[j].texture = out->firstbrushside[j].texture;
4736 q3surfaceflags |= planes[j].q3surfaceflags;
4738 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4740 // this whole loop can take a while (e.g. on redstarrepublic4)
4741 CL_KeepaliveMessage(false);
4745 if (numcreatedtextures)
4746 Con_DPrintf("Mod_Q2BSP_LoadBrushes: %i brushes own sides that lack textures or have differing contents from the brush, %i textures have been created to describe these contents.\n", numbrushesmissingtextures, numcreatedtextures);
4749 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4751 // this is probably a "proof of purchase" lump of some sort, it seems to be 0 size in most bsp files (but not q2dm1.bsp for instance)
4752 sb->readcount = sb->cursize;
4755 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4757 // we currently don't use areas, they represent closable doors as vis blockers
4758 sb->readcount = sb->cursize;
4761 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4763 // we currently don't use areas, they represent closable doors as vis blockers
4764 sb->readcount = sb->cursize;
4767 static void Mod_Q2BSP_LoadSubmodels(sizebuf_t *sb)
4771 int structsize = 48;
4773 if (sb->cursize % structsize)
4774 Host_Error ("Mod_Q2BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
4776 count = sb->cursize / structsize;
4777 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
4779 loadmodel->brushq1.submodels = out;
4780 loadmodel->brush.numsubmodels = count;
4782 // this is identical to the q1 submodel structure except for having 1 hull
4783 for (i = 0; i < count; i++, out++)
4785 // spread out the mins / maxs by a pixel
4786 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
4787 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
4788 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
4789 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
4790 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
4791 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
4792 out->origin[0] = MSG_ReadLittleFloat(sb);
4793 out->origin[1] = MSG_ReadLittleFloat(sb);
4794 out->origin[2] = MSG_ReadLittleFloat(sb);
4795 out->headnode[0] = MSG_ReadLittleLong(sb);
4796 out->firstface = MSG_ReadLittleLong(sb);
4797 out->numfaces = MSG_ReadLittleLong(sb);
4801 static void Mod_Q2BSP_FindSubmodelBrushRange_r(dp_model_t *mod, mnode_t *node, int *first, int *last)
4807 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4808 node = node->children[1];
4810 leaf = (mleaf_t*)node;
4811 for (i = 0;i < leaf->numleafbrushes;i++)
4813 int brushnum = leaf->firstleafbrush[i];
4814 if (*first > brushnum)
4816 if (*last < brushnum)
4821 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4824 sizebuf_t lumpsb[Q2HEADER_LUMPS];
4826 float dist, modelyawradius, modelradius;
4827 msurface_t *surface;
4828 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4829 model_brush_lightstyleinfo_t styleinfo[256];
4830 unsigned char *datapointer;
4833 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4835 mod->type = mod_brushq2;
4837 mod->brush.ishlbsp = false;
4838 mod->brush.isbsp2rmqe = false;
4839 mod->brush.isbsp2 = false;
4840 mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4841 mod->brush.isq3bsp = false;
4842 mod->brush.skymasking = true;
4843 mod->modeldatatypestring = "Q2BSP";
4845 i = MSG_ReadLittleLong(&sb);
4846 if (i != Q2BSPMAGIC)
4847 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4849 i = MSG_ReadLittleLong(&sb);
4850 if (i != Q2BSPVERSION)
4851 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4854 for (i = 0; i < Q2HEADER_LUMPS; i++)
4856 int offset = MSG_ReadLittleLong(&sb);
4857 int size = MSG_ReadLittleLong(&sb);
4858 if (offset < 0 || offset + size > sb.cursize)
4859 Host_Error("Mod_Q2BSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
4860 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4863 mod->soundfromcenter = true;
4864 mod->TracePoint = Mod_CollisionBIH_TracePoint;
4865 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4866 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4867 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4868 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4869 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4870 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4871 mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4872 mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4873 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
4874 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
4875 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
4876 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
4877 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
4878 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
4879 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
4880 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
4881 mod->brush.AmbientSoundLevelsForPoint = NULL;
4882 mod->brush.RoundUpToHullSize = NULL;
4883 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
4884 mod->Draw = R_Q1BSP_Draw;
4885 mod->DrawDepth = R_Q1BSP_DrawDepth;
4886 mod->DrawDebug = R_Q1BSP_DrawDebug;
4887 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
4888 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
4889 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
4890 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
4891 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
4892 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
4893 mod->DrawLight = R_Q1BSP_DrawLight;
4897 mod->brush.qw_md4sum = 0;
4898 mod->brush.qw_md4sum2 = 0;
4899 for (i = 0;i < Q2HEADER_LUMPS;i++)
4902 if (i == Q2LUMP_ENTITIES)
4904 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4905 mod->brush.qw_md4sum ^= LittleLong(temp);
4906 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4908 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4911 // many of these functions are identical to Q1 loaders, so we use those where possible
4912 Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4913 Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4914 Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4915 Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4916 Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4917 Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4918 Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4919 Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4920 Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4921 Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4922 Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4923 Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4924 Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4925 Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4926 Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4927 Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4928 Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4929 Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4930 Mod_Q2BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS]);
4932 for (i = 0; i < Q2HEADER_LUMPS; i++)
4933 if (lumpsb[i].readcount != lumpsb[i].cursize)
4934 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4936 // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4937 // doesn't enable the cvar, just indicates that transparent water is OK
4938 loadmodel->brush.supportwateralpha = true;
4940 // we don't need the compressed pvs data anymore
4941 if (mod->brushq1.data_compressedpvs)
4942 Mem_Free(mod->brushq1.data_compressedpvs);
4943 mod->brushq1.data_compressedpvs = NULL;
4944 mod->brushq1.num_compressedpvs = 0;
4946 // the MakePortals code works fine on the q2bsp data as well
4947 if (mod_bsp_portalize.integer)
4948 Mod_Q1BSP_MakePortals();
4950 mod->numframes = 0; // q2bsp animations are kind of special, frame is unbounded...
4953 // make a single combined shadow mesh to allow optimized shadow volume creation
4954 Mod_Q1BSP_CreateShadowMesh(loadmodel);
4956 if (loadmodel->brush.numsubmodels)
4957 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
4959 totalstylesurfaces = 0;
4961 for (i = 0;i < mod->brush.numsubmodels;i++)
4963 memset(stylecounts, 0, sizeof(stylecounts));
4964 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4966 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4967 for (j = 0;j < MAXLIGHTMAPS;j++)
4968 stylecounts[surface->lightmapinfo->styles[j]]++;
4970 for (k = 0;k < 255;k++)
4974 totalstylesurfaces += stylecounts[k];
4977 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4978 // set up the world model, then on each submodel copy from the world model
4979 // and set up the submodel with the respective model info.
4981 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
4983 mnode_t *rootnode = NULL;
4984 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
4988 // duplicate the basic information
4989 dpsnprintf(name, sizeof(name), "*%i", i);
4990 mod = Mod_FindName(name, loadmodel->name);
4991 // copy the base model to this one
4993 // rename the clone back to its proper name
4994 strlcpy(mod->name, name, sizeof(mod->name));
4995 mod->brush.parentmodel = loadmodel;
4996 // textures and memory belong to the main model
4997 mod->texturepool = NULL;
4998 mod->mempool = NULL;
4999 mod->brush.GetPVS = NULL;
5000 mod->brush.FatPVS = NULL;
5001 mod->brush.BoxTouchingPVS = NULL;
5002 mod->brush.BoxTouchingLeafPVS = NULL;
5003 mod->brush.BoxTouchingVisibleLeafs = NULL;
5004 mod->brush.FindBoxClusters = NULL;
5005 mod->brush.LightPoint = NULL;
5006 mod->brush.AmbientSoundLevelsForPoint = NULL;
5008 mod->brush.submodel = i;
5009 if (loadmodel->brush.submodels)
5010 loadmodel->brush.submodels[i] = mod;
5012 bm = &mod->brushq1.submodels[i];
5014 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5015 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5017 mod->firstmodelsurface = bm->firstface;
5018 mod->nummodelsurfaces = bm->numfaces;
5020 // set node/leaf parents for this submodel
5021 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5022 // (this happens in base3.bsp)
5023 if (bm->headnode[0] >= 0)
5024 rootnode = mod->brush.data_nodes + bm->headnode[0];
5026 rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5027 Mod_Q1BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5029 // make the model surface list (used by shadowing/lighting)
5030 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
5031 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5032 if (firstbrush <= lastbrush)
5034 mod->firstmodelbrush = firstbrush;
5035 mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5039 mod->firstmodelbrush = 0;
5040 mod->nummodelbrushes = 0;
5042 Mod_MakeSortedSurfaces(mod);
5044 VectorCopy(bm->mins, mod->normalmins);
5045 VectorCopy(bm->maxs, mod->normalmaxs);
5046 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5047 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5048 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5049 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5050 modelradius = modelyawradius + modelradius * modelradius;
5051 modelyawradius = sqrt(modelyawradius);
5052 modelradius = sqrt(modelradius);
5053 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5054 mod->yawmins[2] = mod->normalmins[2];
5055 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
5056 mod->yawmaxs[2] = mod->normalmaxs[2];
5057 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5058 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5059 mod->radius = modelradius;
5060 mod->radius2 = modelradius * modelradius;
5062 // this gets altered below if sky or water is used
5063 mod->DrawSky = NULL;
5064 mod->DrawAddWaterPlanes = NULL;
5066 // scan surfaces for sky and water and flag the submodel as possessing these features or not
5067 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5068 if (mod->nummodelsurfaces)
5070 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5071 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
5073 if (j < mod->nummodelsurfaces)
5074 mod->DrawSky = R_Q1BSP_DrawSky;
5076 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5077 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
5079 if (j < mod->nummodelsurfaces)
5080 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
5082 // build lightstyle update chains
5083 // (used to rapidly mark lightmapupdateflags on many surfaces
5084 // when d_lightstylevalue changes)
5085 memset(stylecounts, 0, sizeof(stylecounts));
5086 for (k = 0;k < mod->nummodelsurfaces;k++)
5088 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5089 for (j = 0;j < MAXLIGHTMAPS;j++)
5090 stylecounts[surface->lightmapinfo->styles[j]]++;
5092 mod->brushq1.num_lightstyles = 0;
5093 for (k = 0;k < 255;k++)
5097 styleinfo[mod->brushq1.num_lightstyles].style = k;
5098 styleinfo[mod->brushq1.num_lightstyles].value = 0;
5099 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5100 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
5101 remapstyles[k] = mod->brushq1.num_lightstyles;
5102 mod->brushq1.num_lightstyles++;
5105 for (k = 0;k < mod->nummodelsurfaces;k++)
5107 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5108 for (j = 0;j < MAXLIGHTMAPS;j++)
5110 if (surface->lightmapinfo->styles[j] != 255)
5112 int r = remapstyles[surface->lightmapinfo->styles[j]];
5113 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
5117 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
5118 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5122 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5124 //mod->brushq1.num_visleafs = bm->visleafs;
5126 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5127 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5129 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5130 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5132 // generate VBOs and other shared data before cloning submodels
5138 Con_DPrintf("Stats for q2bsp 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);
5141 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
5142 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
5144 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5147 char key[128], value[MAX_INPUTLINE];
5149 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5150 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5151 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5154 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5155 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5156 loadmodel->brush.entities[l->filelen] = 0;
5157 data = loadmodel->brush.entities;
5158 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5159 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5160 loadmodel->brushq3.deluxemapping = false;
5161 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5165 if (!COM_ParseToken_Simple(&data, false, false, true))
5167 if (com_token[0] == '}')
5168 break; // end of worldspawn
5169 if (com_token[0] == '_')
5170 strlcpy(key, com_token + 1, sizeof(key));
5172 strlcpy(key, com_token, sizeof(key));
5173 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5174 key[strlen(key)-1] = 0;
5175 if (!COM_ParseToken_Simple(&data, false, false, true))
5177 strlcpy(value, com_token, sizeof(value));
5178 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5180 #if _MSC_VER >= 1400
5181 #define sscanf sscanf_s
5184 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5185 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5187 VectorSet(v, 64, 64, 128);
5188 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5189 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]);
5190 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5191 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5194 else if (!strcmp("deluxeMaps", key))
5196 if (!strcmp(com_token, "1"))
5198 loadmodel->brushq3.deluxemapping = true;
5199 loadmodel->brushq3.deluxemapping_modelspace = true;
5201 else if (!strcmp(com_token, "2"))
5203 loadmodel->brushq3.deluxemapping = true;
5204 loadmodel->brushq3.deluxemapping_modelspace = false;
5211 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5217 in = (q3dtexture_t *)(mod_base + l->fileofs);
5218 if (l->filelen % sizeof(*in))
5219 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5220 count = l->filelen / sizeof(*in);
5221 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5223 loadmodel->data_textures = out;
5224 loadmodel->num_textures = count;
5225 loadmodel->num_texturesperskin = loadmodel->num_textures;
5227 for (i = 0;i < count;i++)
5229 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5230 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
5231 Mod_LoadTextureFromQ3Shader(out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
5232 // restore the surfaceflags and supercontents
5233 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5234 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
5238 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5244 in = (q3dplane_t *)(mod_base + l->fileofs);
5245 if (l->filelen % sizeof(*in))
5246 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5247 count = l->filelen / sizeof(*in);
5248 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5250 loadmodel->brush.data_planes = out;
5251 loadmodel->brush.num_planes = count;
5253 for (i = 0;i < count;i++, in++, out++)
5255 out->normal[0] = LittleFloat(in->normal[0]);
5256 out->normal[1] = LittleFloat(in->normal[1]);
5257 out->normal[2] = LittleFloat(in->normal[2]);
5258 out->dist = LittleFloat(in->dist);
5263 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5266 q3mbrushside_t *out;
5269 in = (q3dbrushside_t *)(mod_base + l->fileofs);
5270 if (l->filelen % sizeof(*in))
5271 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5272 count = l->filelen / sizeof(*in);
5273 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5275 loadmodel->brush.data_brushsides = out;
5276 loadmodel->brush.num_brushsides = count;
5278 for (i = 0;i < count;i++, in++, out++)
5280 n = LittleLong(in->planeindex);
5281 if (n < 0 || n >= loadmodel->brush.num_planes)
5282 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5283 out->plane = loadmodel->brush.data_planes + n;
5284 n = LittleLong(in->textureindex);
5285 if (n < 0 || n >= loadmodel->num_textures)
5286 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5287 out->texture = loadmodel->data_textures + n;
5291 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5293 q3dbrushside_ig_t *in;
5294 q3mbrushside_t *out;
5297 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5298 if (l->filelen % sizeof(*in))
5299 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5300 count = l->filelen / sizeof(*in);
5301 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5303 loadmodel->brush.data_brushsides = out;
5304 loadmodel->brush.num_brushsides = count;
5306 for (i = 0;i < count;i++, in++, out++)
5308 n = LittleLong(in->planeindex);
5309 if (n < 0 || n >= loadmodel->brush.num_planes)
5310 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5311 out->plane = loadmodel->brush.data_planes + n;
5312 n = LittleLong(in->textureindex);
5313 if (n < 0 || n >= loadmodel->num_textures)
5314 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5315 out->texture = loadmodel->data_textures + n;
5319 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5323 int i, j, n, c, count, maxplanes, q3surfaceflags;
5324 colplanef_t *planes;
5326 in = (q3dbrush_t *)(mod_base + l->fileofs);
5327 if (l->filelen % sizeof(*in))
5328 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5329 count = l->filelen / sizeof(*in);
5330 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5332 loadmodel->brush.data_brushes = out;
5333 loadmodel->brush.num_brushes = count;
5338 for (i = 0;i < count;i++, in++, out++)
5340 n = LittleLong(in->firstbrushside);
5341 c = LittleLong(in->numbrushsides);
5342 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5343 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5344 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5345 out->numbrushsides = c;
5346 n = LittleLong(in->textureindex);
5347 if (n < 0 || n >= loadmodel->num_textures)
5348 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5349 out->texture = loadmodel->data_textures + n;
5351 // make a list of mplane_t structs to construct a colbrush from
5352 if (maxplanes < out->numbrushsides)
5354 maxplanes = out->numbrushsides;
5357 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5360 for (j = 0;j < out->numbrushsides;j++)
5362 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5363 planes[j].dist = out->firstbrushside[j].plane->dist;
5364 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5365 planes[j].texture = out->firstbrushside[j].texture;
5366 q3surfaceflags |= planes[j].q3surfaceflags;
5368 // make the colbrush from the planes
5369 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5371 // this whole loop can take a while (e.g. on redstarrepublic4)
5372 CL_KeepaliveMessage(false);
5378 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5384 in = (q3deffect_t *)(mod_base + l->fileofs);
5385 if (l->filelen % sizeof(*in))
5386 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5387 count = l->filelen / sizeof(*in);
5388 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5390 loadmodel->brushq3.data_effects = out;
5391 loadmodel->brushq3.num_effects = count;
5393 for (i = 0;i < count;i++, in++, out++)
5395 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5396 n = LittleLong(in->brushindex);
5397 if (n >= loadmodel->brush.num_brushes)
5399 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5402 out->brushindex = n;
5403 out->unknown = LittleLong(in->unknown);
5407 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5412 in = (q3dvertex_t *)(mod_base + l->fileofs);
5413 if (l->filelen % sizeof(*in))
5414 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5415 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5416 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5417 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5418 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5419 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5420 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5422 for (i = 0;i < count;i++, in++)
5424 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5425 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5426 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5427 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5428 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5429 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5430 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5431 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5432 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5433 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5434 // svector/tvector are calculated later in face loading
5435 if(mod_q3bsp_sRGBlightmaps.integer)
5437 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5438 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5439 // working like this may be odd, but matches q3map2 -gamma 2.2
5440 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5442 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5443 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5444 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5445 // we fix the brightness consistently via lightmapscale
5449 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5450 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5451 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5456 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5458 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5459 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5460 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5464 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5465 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5466 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5469 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5470 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5471 loadmodel->lit = true;
5475 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5481 in = (int *)(mod_base + l->fileofs);
5482 if (l->filelen % sizeof(int[3]))
5483 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5484 count = l->filelen / sizeof(*in);
5486 if(!loadmodel->brushq3.num_vertices)
5489 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5490 loadmodel->brushq3.num_triangles = 0;
5494 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5495 loadmodel->brushq3.num_triangles = count / 3;
5496 loadmodel->brushq3.data_element3i = out;
5498 for (i = 0;i < count;i++, in++, out++)
5500 *out = LittleLong(*in);
5501 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5503 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5509 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5511 q3dlightmap_t *input_pointer;
5529 int mergedrowsxcolumns;
5534 unsigned char *mergedpixels;
5535 unsigned char *mergeddeluxepixels;
5536 unsigned char *mergebuf;
5537 char mapname[MAX_QPATH];
5539 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5542 // defaults for q3bsp
5549 loadmodel->brushq3.lightmapsize = 128;
5551 if (cls.state == ca_dedicated)
5554 if(mod_q3bsp_nolightmaps.integer)
5560 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5561 if (developer_loading.integer)
5562 Con_Printf("Using internal lightmaps\n");
5563 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5564 if (l->filelen % sizeof(*input_pointer))
5565 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5566 count = l->filelen / sizeof(*input_pointer);
5567 for(i = 0; i < count; ++i)
5568 inpixels[i] = input_pointer[i].rgb;
5572 // no internal lightmaps
5573 // try external lightmaps
5574 if (developer_loading.integer)
5575 Con_Printf("Using external lightmaps\n");
5576 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5577 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5581 // using EXTERNAL lightmaps instead
5582 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5584 Mem_Free(inpixels[0]);
5585 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5595 for(count = 1; ; ++count)
5597 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5598 if(!inpixels[count])
5599 break; // we got all of them
5600 if(image_width != size || image_height != size)
5602 Mem_Free(inpixels[count]);
5603 inpixels[count] = NULL;
5604 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);
5610 loadmodel->brushq3.lightmapsize = size;
5611 loadmodel->brushq3.num_originallightmaps = count;
5613 // now check the surfaces to see if any of them index an odd numbered
5614 // lightmap, if so this is not a deluxemapped bsp file
5616 // also check what lightmaps are actually used, because q3map2 sometimes
5617 // (always?) makes an unused one at the end, which
5618 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5619 // reason when only one lightmap is used, which can throw off the
5620 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5621 // to see if the second lightmap is blank, if so it is not deluxemapped.
5622 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5623 // in Mod_Q3BSP_LoadEntities was failed
5624 if (!loadmodel->brushq3.deluxemapping)
5626 loadmodel->brushq3.deluxemapping = !(count & 1);
5627 loadmodel->brushq3.deluxemapping_modelspace = true;
5629 if (loadmodel->brushq3.deluxemapping)
5631 int facecount = faceslump->filelen / sizeof(q3dface_t);
5632 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5633 for (i = 0;i < facecount;i++)
5635 j = LittleLong(faces[i].lightmapindex);
5638 endlightmap = max(endlightmap, j + 1);
5639 if ((j & 1) || j + 1 >= count)
5641 loadmodel->brushq3.deluxemapping = false;
5648 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5649 // reason when only one lightmap is used, which can throw off the
5650 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5651 // to see if the second lightmap is blank, if so it is not deluxemapped.
5653 // further research has shown q3map2 sometimes creates a deluxemap and two
5654 // blank lightmaps, which must be handled properly as well
5655 if (endlightmap == 1 && count > 1)
5658 for (i = 0;i < size*size;i++)
5660 if (c[bytesperpixel*i + rgbmap[0]])
5662 if (c[bytesperpixel*i + rgbmap[1]])
5664 if (c[bytesperpixel*i + rgbmap[2]])
5669 // all pixels in the unused lightmap were black...
5670 loadmodel->brushq3.deluxemapping = false;
5675 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5677 // figure out what the most reasonable merge power is within limits
5679 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5680 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5682 // figure out how big the merged texture has to be
5683 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5684 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5685 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5687 mergedwidth = mergegoal;
5688 mergedheight = mergegoal;
5689 // choose non-square size (2x1 aspect) if only half the space is used;
5690 // this really only happens when the entire set fits in one texture, if
5691 // there are multiple textures, we don't worry about shrinking the last
5692 // one to fit, because the driver prefers the same texture size on
5693 // consecutive draw calls...
5694 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5697 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5698 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5699 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5700 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5701 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5702 loadmodel->brushq3.num_lightmapmergedheightpower++;
5703 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5705 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5706 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5707 powerxy = powerx+powery;
5708 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5710 mergedcolumns = 1 << powerx;
5711 mergedrows = 1 << powery;
5712 mergedrowsxcolumns = 1 << powerxy;
5714 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5715 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5716 if (loadmodel->brushq3.deluxemapping)
5717 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5719 // allocate a texture pool if we need it
5720 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5721 loadmodel->texturepool = R_AllocTexturePool();
5723 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5724 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5725 for (i = 0;i < count;i++)
5727 // figure out which merged lightmap texture this fits into
5728 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5729 lightmapindex = i >> powerdxy;
5731 // choose the destination address
5732 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5733 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5734 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5735 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);
5737 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5738 for (j = 0;j < size;j++)
5739 for (k = 0;k < size;k++)
5741 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5742 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5743 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5744 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5747 // upload texture if this was the last tile being written to the texture
5748 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5750 if (loadmodel->brushq3.deluxemapping && (i & 1))
5751 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%04i", lightmapindex), mergedwidth, mergedheight, mergeddeluxepixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5754 if(mod_q3bsp_sRGBlightmaps.integer)
5757 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5759 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5760 // we fix the brightness consistently via lightmapscale
5763 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5764 loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, t, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5768 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5769 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5770 loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5776 if (mergeddeluxepixels)
5777 Mem_Free(mergeddeluxepixels);
5778 Mem_Free(mergedpixels);
5781 for(i = 0; i < count; ++i)
5782 Mem_Free(inpixels[i]);
5786 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5791 *collisionstride = stride;
5794 cnt = (num_triangles + stride - 1) / stride;
5795 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5796 for(j = 0; j < cnt; ++j)
5798 mins = &((*collisionbbox6f)[6 * j + 0]);
5799 maxs = &((*collisionbbox6f)[6 * j + 3]);
5800 for(k = 0; k < stride; ++k)
5802 tri = j * stride + k;
5803 if(tri >= num_triangles)
5805 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5806 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5807 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5808 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5809 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5810 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5811 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5812 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5813 if(vert[0] < mins[0]) mins[0] = vert[0];
5814 if(vert[1] < mins[1]) mins[1] = vert[1];
5815 if(vert[2] < mins[2]) mins[2] = vert[2];
5816 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5817 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5818 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5819 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5820 if(vert[0] < mins[0]) mins[0] = vert[0];
5821 if(vert[1] < mins[1]) mins[1] = vert[1];
5822 if(vert[2] < mins[2]) mins[2] = vert[2];
5823 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5824 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5825 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5830 *collisionbbox6f = NULL;
5833 typedef struct patchtess_s
5837 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5840 float *originalvertex3f;
5843 #define PATCHTESS_SAME_LODGROUP(a,b) \
5845 (a).lodgroup[0] == (b).lodgroup[0] && \
5846 (a).lodgroup[1] == (b).lodgroup[1] && \
5847 (a).lodgroup[2] == (b).lodgroup[2] && \
5848 (a).lodgroup[3] == (b).lodgroup[3] && \
5849 (a).lodgroup[4] == (b).lodgroup[4] && \
5850 (a).lodgroup[5] == (b).lodgroup[5] \
5853 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5855 q3dface_t *in, *oldin;
5856 msurface_t *out, *oldout;
5857 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;
5858 float lightmaptcbase[2], lightmaptcscale[2];
5859 //int *originalelement3i;
5860 //int *originalneighbor3i;
5861 float *originalvertex3f;
5862 //float *originalsvector3f;
5863 //float *originaltvector3f;
5864 float *originalnormal3f;
5865 float *originalcolor4f;
5866 float *originaltexcoordtexture2f;
5867 float *originaltexcoordlightmap2f;
5868 float *surfacecollisionvertex3f;
5869 int *surfacecollisionelement3i;
5871 patchtess_t *patchtess = NULL;
5872 int patchtesscount = 0;
5875 in = (q3dface_t *)(mod_base + l->fileofs);
5876 if (l->filelen % sizeof(*in))
5877 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5878 count = l->filelen / sizeof(*in);
5879 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5881 loadmodel->data_surfaces = out;
5882 loadmodel->num_surfaces = count;
5885 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5893 for (;i < count;i++, in++, out++)
5895 // check face type first
5896 type = LittleLong(in->type);
5897 if (type != Q3FACETYPE_FLAT
5898 && type != Q3FACETYPE_PATCH
5899 && type != Q3FACETYPE_MESH
5900 && type != Q3FACETYPE_FLARE)
5902 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5906 n = LittleLong(in->textureindex);
5907 if (n < 0 || n >= loadmodel->num_textures)
5909 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5912 out->texture = loadmodel->data_textures + n;
5913 n = LittleLong(in->effectindex);
5914 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5916 if (developer_extra.integer)
5917 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5923 out->effect = loadmodel->brushq3.data_effects + n;
5925 if (cls.state != ca_dedicated)
5927 out->lightmaptexture = NULL;
5928 out->deluxemaptexture = r_texture_blanknormalmap;
5929 n = LittleLong(in->lightmapindex);
5932 else if (n >= loadmodel->brushq3.num_originallightmaps)
5934 if(loadmodel->brushq3.num_originallightmaps != 0)
5935 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5940 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5941 if (loadmodel->brushq3.deluxemapping)
5942 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5943 loadmodel->lit = true;
5947 firstvertex = LittleLong(in->firstvertex);
5948 numvertices = LittleLong(in->numvertices);
5949 firstelement = LittleLong(in->firstelement);
5950 numtriangles = LittleLong(in->numelements) / 3;
5951 if (numtriangles * 3 != LittleLong(in->numelements))
5953 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));
5956 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5958 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);
5961 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5963 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);
5968 case Q3FACETYPE_FLAT:
5969 case Q3FACETYPE_MESH:
5970 // no processing necessary
5972 case Q3FACETYPE_PATCH:
5973 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5974 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5975 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))
5977 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5980 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5982 // convert patch to Q3FACETYPE_MESH
5983 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5984 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5985 // bound to user settings
5986 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5987 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5988 // bound to sanity settings
5989 xtess = bound(0, xtess, 1024);
5990 ytess = bound(0, ytess, 1024);
5992 // lower quality collision patches! Same procedure as before, but different cvars
5993 // convert patch to Q3FACETYPE_MESH
5994 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5995 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5996 // bound to user settings
5997 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5998 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5999 // bound to sanity settings
6000 cxtess = bound(0, cxtess, 1024);
6001 cytess = bound(0, cytess, 1024);
6003 // store it for the LOD grouping step
6004 patchtess[patchtesscount].info.xsize = patchsize[0];
6005 patchtess[patchtesscount].info.ysize = patchsize[1];
6006 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
6007 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
6008 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
6009 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
6011 patchtess[patchtesscount].surface_id = i;
6012 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
6013 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
6014 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
6015 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
6016 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
6017 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
6018 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
6021 case Q3FACETYPE_FLARE:
6022 if (developer_extra.integer)
6023 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
6027 out->num_vertices = numvertices;
6028 out->num_triangles = numtriangles;
6029 meshvertices += out->num_vertices;
6030 meshtriangles += out->num_triangles;
6033 // Fix patches tesselations so that they make no seams
6037 for(i = 0; i < patchtesscount; ++i)
6039 for(j = i+1; j < patchtesscount; ++j)
6041 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
6044 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
6051 // Calculate resulting number of triangles
6052 collisionvertices = 0;
6053 collisiontriangles = 0;
6054 for(i = 0; i < patchtesscount; ++i)
6056 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
6057 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
6058 numvertices = finalwidth * finalheight;
6059 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6061 oldout[patchtess[i].surface_id].num_vertices = numvertices;
6062 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
6063 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
6064 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
6066 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
6067 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
6068 numvertices = finalwidth * finalheight;
6069 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6071 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
6072 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
6073 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
6074 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
6080 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
6081 if (collisiontriangles)
6083 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6084 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6088 collisionvertices = 0;
6089 collisiontriangles = 0;
6090 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6092 if (out->num_vertices < 3 || out->num_triangles < 1)
6095 type = LittleLong(in->type);
6096 firstvertex = LittleLong(in->firstvertex);
6097 firstelement = LittleLong(in->firstelement);
6098 out->num_firstvertex = meshvertices;
6099 out->num_firsttriangle = meshtriangles;
6100 out->num_firstcollisiontriangle = collisiontriangles;
6103 case Q3FACETYPE_FLAT:
6104 case Q3FACETYPE_MESH:
6105 // no processing necessary, except for lightmap merging
6106 for (j = 0;j < out->num_vertices;j++)
6108 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6109 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6110 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6111 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6112 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6113 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6114 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6115 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6116 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6117 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6118 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6119 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6120 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6121 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6123 for (j = 0;j < out->num_triangles*3;j++)
6124 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6126 case Q3FACETYPE_PATCH:
6127 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6128 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6129 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6130 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6131 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6132 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6133 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6135 xtess = ytess = cxtess = cytess = -1;
6136 for(j = 0; j < patchtesscount; ++j)
6137 if(patchtess[j].surface_id == i)
6139 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6140 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6141 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6142 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6147 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
6148 xtess = ytess = cxtess = cytess = 0;
6151 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6152 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6153 finalvertices = finalwidth * finalheight;
6154 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6155 type = Q3FACETYPE_MESH;
6156 // generate geometry
6157 // (note: normals are skipped because they get recalculated)
6158 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6159 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6160 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6161 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6162 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6163 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6165 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);
6167 if (developer_extra.integer)
6169 if (out->num_triangles < finaltriangles)
6170 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);
6172 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);
6174 // q3map does not put in collision brushes for curves... ugh
6175 // build the lower quality collision geometry
6176 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6177 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6178 finalvertices = finalwidth * finalheight;
6179 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6181 // legacy collision geometry implementation
6182 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
6183 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
6184 out->num_collisionvertices = finalvertices;
6185 out->num_collisiontriangles = finaltriangles;
6186 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6187 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
6189 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
6190 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
6192 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
6194 // now optimize the collision mesh by finding triangle bboxes...
6195 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
6196 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);
6198 // store collision geometry for BIH collision tree
6199 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6200 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6201 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6202 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6203 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6205 // remove this once the legacy code is removed
6207 int nc = out->num_collisiontriangles;
6209 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6211 if(nc != out->num_collisiontriangles)
6213 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
6218 if (developer_extra.integer)
6219 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);
6221 collisionvertices += finalvertices;
6222 collisiontriangles += out->num_collisiontriangles;
6227 meshvertices += out->num_vertices;
6228 meshtriangles += out->num_triangles;
6229 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6230 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)
6232 if (invalidelements)
6234 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);
6235 for (j = 0;j < out->num_triangles * 3;j++)
6237 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6238 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)
6239 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6243 // calculate a bounding box
6244 VectorClear(out->mins);
6245 VectorClear(out->maxs);
6246 if (out->num_vertices)
6248 if (cls.state != ca_dedicated && out->lightmaptexture)
6250 // figure out which part of the merged lightmap this fits into
6251 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6252 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6253 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6254 lightmapindex &= mergewidth * mergeheight - 1;
6255 lightmaptcscale[0] = 1.0f / mergewidth;
6256 lightmaptcscale[1] = 1.0f / mergeheight;
6257 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6258 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6259 // modify the lightmap texcoords to match this region of the merged lightmap
6260 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6262 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6263 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6266 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6267 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6268 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6270 out->mins[0] = min(out->mins[0], v[0]);
6271 out->maxs[0] = max(out->maxs[0], v[0]);
6272 out->mins[1] = min(out->mins[1], v[1]);
6273 out->maxs[1] = max(out->maxs[1], v[1]);
6274 out->mins[2] = min(out->mins[2], v[2]);
6275 out->maxs[2] = max(out->maxs[2], v[2]);
6277 out->mins[0] -= 1.0f;
6278 out->mins[1] -= 1.0f;
6279 out->mins[2] -= 1.0f;
6280 out->maxs[0] += 1.0f;
6281 out->maxs[1] += 1.0f;
6282 out->maxs[2] += 1.0f;
6284 // set lightmap styles for consistency with q1bsp
6285 //out->lightmapinfo->styles[0] = 0;
6286 //out->lightmapinfo->styles[1] = 255;
6287 //out->lightmapinfo->styles[2] = 255;
6288 //out->lightmapinfo->styles[3] = 255;
6293 for (;i < count;i++, out++)
6295 if(out->num_vertices && out->num_triangles)
6297 if(out->num_vertices == 0)
6299 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6300 if(out->num_triangles == 0)
6301 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6303 else if(out->num_triangles == 0)
6304 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)",
6305 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6306 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6307 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6310 // for per pixel lighting
6311 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);
6313 // generate ushort elements array if possible
6314 if (loadmodel->surfmesh.data_element3s)
6315 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6316 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6318 // free the no longer needed vertex data
6319 loadmodel->brushq3.num_vertices = 0;
6320 if (loadmodel->brushq3.data_vertex3f)
6321 Mem_Free(loadmodel->brushq3.data_vertex3f);
6322 loadmodel->brushq3.data_vertex3f = NULL;
6323 loadmodel->brushq3.data_normal3f = NULL;
6324 loadmodel->brushq3.data_texcoordtexture2f = NULL;
6325 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6326 loadmodel->brushq3.data_color4f = NULL;
6327 // free the no longer needed triangle data
6328 loadmodel->brushq3.num_triangles = 0;
6329 if (loadmodel->brushq3.data_element3i)
6330 Mem_Free(loadmodel->brushq3.data_element3i);
6331 loadmodel->brushq3.data_element3i = NULL;
6334 Mem_Free(patchtess);
6337 static void Mod_Q3BSP_LoadModels(lump_t *l)
6341 int i, j, n, c, count;
6343 in = (q3dmodel_t *)(mod_base + l->fileofs);
6344 if (l->filelen % sizeof(*in))
6345 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6346 count = l->filelen / sizeof(*in);
6347 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6349 loadmodel->brushq3.data_models = out;
6350 loadmodel->brushq3.num_models = count;
6352 for (i = 0;i < count;i++, in++, out++)
6354 for (j = 0;j < 3;j++)
6356 out->mins[j] = LittleFloat(in->mins[j]);
6357 out->maxs[j] = LittleFloat(in->maxs[j]);
6359 n = LittleLong(in->firstface);
6360 c = LittleLong(in->numfaces);
6361 if (n < 0 || n + c > loadmodel->num_surfaces)
6362 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6365 n = LittleLong(in->firstbrush);
6366 c = LittleLong(in->numbrushes);
6367 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6368 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6369 out->firstbrush = n;
6370 out->numbrushes = c;
6374 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6380 in = (int *)(mod_base + l->fileofs);
6381 if (l->filelen % sizeof(*in))
6382 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6383 count = l->filelen / sizeof(*in);
6384 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6386 loadmodel->brush.data_leafbrushes = out;
6387 loadmodel->brush.num_leafbrushes = count;
6389 for (i = 0;i < count;i++, in++, out++)
6391 n = LittleLong(*in);
6392 if (n < 0 || n >= loadmodel->brush.num_brushes)
6393 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6398 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6404 in = (int *)(mod_base + l->fileofs);
6405 if (l->filelen % sizeof(*in))
6406 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6407 count = l->filelen / sizeof(*in);
6408 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6410 loadmodel->brush.data_leafsurfaces = out;
6411 loadmodel->brush.num_leafsurfaces = count;
6413 for (i = 0;i < count;i++, in++, out++)
6415 n = LittleLong(*in);
6416 if (n < 0 || n >= loadmodel->num_surfaces)
6417 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6422 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6426 int i, j, n, c, count;
6428 in = (q3dleaf_t *)(mod_base + l->fileofs);
6429 if (l->filelen % sizeof(*in))
6430 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6431 count = l->filelen / sizeof(*in);
6432 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6434 loadmodel->brush.data_leafs = out;
6435 loadmodel->brush.num_leafs = count;
6437 for (i = 0;i < count;i++, in++, out++)
6441 out->clusterindex = LittleLong(in->clusterindex);
6442 out->areaindex = LittleLong(in->areaindex);
6443 for (j = 0;j < 3;j++)
6445 // yes the mins/maxs are ints
6446 out->mins[j] = LittleLong(in->mins[j]) - 1;
6447 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6449 n = LittleLong(in->firstleafface);
6450 c = LittleLong(in->numleaffaces);
6451 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6452 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6453 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6454 out->numleafsurfaces = c;
6455 n = LittleLong(in->firstleafbrush);
6456 c = LittleLong(in->numleafbrushes);
6457 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6458 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6459 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6460 out->numleafbrushes = c;
6464 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6470 in = (q3dnode_t *)(mod_base + l->fileofs);
6471 if (l->filelen % sizeof(*in))
6472 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6473 count = l->filelen / sizeof(*in);
6475 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6476 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6478 loadmodel->brush.data_nodes = out;
6479 loadmodel->brush.num_nodes = count;
6481 for (i = 0;i < count;i++, in++, out++)
6484 n = LittleLong(in->planeindex);
6485 if (n < 0 || n >= loadmodel->brush.num_planes)
6486 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6487 out->plane = loadmodel->brush.data_planes + n;
6488 for (j = 0;j < 2;j++)
6490 n = LittleLong(in->childrenindex[j]);
6493 if (n >= loadmodel->brush.num_nodes)
6494 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6495 out->children[j] = loadmodel->brush.data_nodes + n;
6500 if (n >= loadmodel->brush.num_leafs)
6501 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6502 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6505 for (j = 0;j < 3;j++)
6507 // yes the mins/maxs are ints
6508 out->mins[j] = LittleLong(in->mins[j]) - 1;
6509 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6513 // set the parent pointers
6514 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6517 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6520 q3dlightgrid_t *out;
6524 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6525 if (l->filelen % sizeof(*in))
6526 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6527 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6528 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6529 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6530 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6531 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6532 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6533 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6534 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6535 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6536 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6537 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6538 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6539 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6540 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]);
6541 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]);
6543 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6546 if (l->filelen < count * (int)sizeof(*in))
6548 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]);
6549 return; // ignore the grid if we cannot understand it
6551 if (l->filelen != count * (int)sizeof(*in))
6552 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
6553 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6554 loadmodel->brushq3.data_lightgrid = out;
6555 loadmodel->brushq3.num_lightgrid = count;
6556 // no swapping or validation necessary
6557 memcpy(out, in, count * (int)sizeof(*out));
6559 if(mod_q3bsp_sRGBlightmaps.integer)
6561 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6563 // we fix the brightness consistently via lightmapscale
6567 for(i = 0; i < count; ++i)
6569 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6570 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6571 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6572 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6573 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6574 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6580 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6582 for(i = 0; i < count; ++i)
6584 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6585 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6586 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6587 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6588 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6589 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6600 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6605 if (l->filelen == 0)
6608 // unvised maps often have cluster indices even without pvs, so check
6609 // leafs to find real number of clusters
6610 loadmodel->brush.num_pvsclusters = 1;
6611 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6612 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6615 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6616 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6617 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6618 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6622 in = (q3dpvs_t *)(mod_base + l->fileofs);
6624 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6626 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6627 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6628 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6629 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6630 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6631 if (l->filelen < totalchains + (int)sizeof(*in))
6632 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);
6634 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6635 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6638 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6640 int i, j, k, index[3];
6641 float transformed[3], blend1, blend2, blend, stylescale = 1;
6642 q3dlightgrid_t *a, *s;
6644 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6645 switch(vid.renderpath)
6647 case RENDERPATH_GL20:
6648 case RENDERPATH_D3D9:
6649 case RENDERPATH_D3D10:
6650 case RENDERPATH_D3D11:
6651 case RENDERPATH_SOFT:
6652 case RENDERPATH_GLES2:
6653 // LordHavoc: FIXME: is this true?
6654 stylescale = 1; // added while render
6656 case RENDERPATH_GL11:
6657 case RENDERPATH_GL13:
6658 case RENDERPATH_GLES1:
6659 stylescale = r_refdef.scene.rtlightstylevalue[0];
6663 if (!model->brushq3.num_lightgrid)
6665 ambientcolor[0] = stylescale;
6666 ambientcolor[1] = stylescale;
6667 ambientcolor[2] = stylescale;
6671 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6672 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6673 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6674 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6675 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6676 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6677 index[0] = (int)floor(transformed[0]);
6678 index[1] = (int)floor(transformed[1]);
6679 index[2] = (int)floor(transformed[2]);
6680 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6682 // now lerp the values
6683 VectorClear(diffusenormal);
6684 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6685 for (k = 0;k < 2;k++)
6687 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6688 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6690 for (j = 0;j < 2;j++)
6692 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6693 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6695 for (i = 0;i < 2;i++)
6697 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6698 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6700 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6701 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6702 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6703 // this uses the mod_md3_sin table because the values are
6704 // already in the 0-255 range, the 64+ bias fetches a cosine
6705 // instead of a sine value
6706 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6707 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6708 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6709 //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)));
6714 // normalize the light direction before turning
6715 VectorNormalize(diffusenormal);
6716 //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]);
6719 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6722 double midf, mid[3];
6728 // find the point distances
6729 mplane_t *plane = node->plane;
6730 if (plane->type < 3)
6732 t1 = p1[plane->type] - plane->dist;
6733 t2 = p2[plane->type] - plane->dist;
6737 t1 = DotProduct (plane->normal, p1) - plane->dist;
6738 t2 = DotProduct (plane->normal, p2) - plane->dist;
6745 node = node->children[1];
6754 node = node->children[0];
6760 midf = t1 / (t1 - t2);
6761 VectorLerp(p1, midf, p2, mid);
6763 // recurse both sides, front side first
6764 // return 2 if empty is followed by solid (hit something)
6765 // do not return 2 if both are solid or both empty,
6766 // or if start is solid and end is empty
6767 // as these degenerate cases usually indicate the eye is in solid and
6768 // should see the target point anyway
6769 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6772 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6777 return ((mleaf_t *)node)->clusterindex < 0;
6780 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6782 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6785 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0);
6786 return trace.fraction == 1;
6790 double tracestart[3], traceend[3];
6791 VectorCopy(start, tracestart);
6792 VectorCopy(end, traceend);
6793 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6797 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, int skipsupercontentsmask)
6800 const bih_leaf_t *leaf;
6801 const bih_node_t *node;
6802 const colbrushf_t *brush;
6805 int nodestackpos = 0;
6806 int nodestack[1024];
6808 memset(trace, 0, sizeof(*trace));
6809 trace->fraction = 1;
6810 trace->hitsupercontentsmask = hitsupercontentsmask;
6811 trace->skipsupercontentsmask = skipsupercontentsmask;
6813 bih = &model->collision_bih;
6817 nodenum = bih->rootnode;
6818 nodestack[nodestackpos++] = nodenum;
6819 while (nodestackpos)
6821 nodenum = nodestack[--nodestackpos];
6822 node = bih->nodes + nodenum;
6824 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6827 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6829 axis = node->type - BIH_SPLITX;
6830 if (start[axis] >= node->frontmin)
6831 nodestack[nodestackpos++] = node->front;
6832 if (start[axis] <= node->backmax)
6833 nodestack[nodestackpos++] = node->back;
6835 else if (node->type == BIH_UNORDERED)
6837 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6839 leaf = bih->leafs + node->children[axis];
6841 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6847 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6848 Collision_TracePointBrushFloat(trace, start, brush);
6850 case BIH_COLLISIONTRIANGLE:
6851 // collision triangle - skipped because they have no volume
6853 case BIH_RENDERTRIANGLE:
6854 // render triangle - skipped because they have no volume
6862 static 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, int skipsupercontentsmask, const bih_t *bih)
6864 const bih_leaf_t *leaf;
6865 const bih_node_t *node;
6866 const colbrushf_t *brush;
6868 const texture_t *texture;
6869 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6870 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6871 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6876 if (VectorCompare(start, end))
6878 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
6882 nodenum = bih->rootnode;
6884 memset(trace, 0, sizeof(*trace));
6885 trace->fraction = 1;
6886 trace->hitsupercontentsmask = hitsupercontentsmask;
6887 trace->skipsupercontentsmask = skipsupercontentsmask;
6890 nodestackline[nodestackpos][0] = start[0];
6891 nodestackline[nodestackpos][1] = start[1];
6892 nodestackline[nodestackpos][2] = start[2];
6893 nodestackline[nodestackpos][3] = end[0];
6894 nodestackline[nodestackpos][4] = end[1];
6895 nodestackline[nodestackpos][5] = end[2];
6896 nodestack[nodestackpos++] = nodenum;
6897 while (nodestackpos)
6899 nodenum = nodestack[--nodestackpos];
6900 node = bih->nodes + nodenum;
6901 VectorCopy(nodestackline[nodestackpos], nodestart);
6902 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6903 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6904 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6905 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6906 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6907 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6908 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6909 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6911 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6913 // recurse children of the split
6914 axis = node->type - BIH_SPLITX;
6915 d1 = node->backmax - nodestart[axis];
6916 d2 = node->backmax - nodeend[axis];
6917 d3 = nodestart[axis] - node->frontmin;
6918 d4 = nodeend[axis] - node->frontmin;
6919 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6921 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;
6922 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;
6923 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;
6924 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6925 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;
6926 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;
6927 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;
6928 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6929 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;
6930 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;
6931 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;
6932 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6933 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6934 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6935 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6936 case 15: /* <<<< */ break;
6939 else if (node->type == BIH_UNORDERED)
6941 // calculate sweep bounds for this node
6942 // copy node bounds into local variables
6943 VectorCopy(node->mins, nodebigmins);
6944 VectorCopy(node->maxs, nodebigmaxs);
6945 // clip line to this node bounds
6946 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); }
6947 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); }
6948 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); }
6949 // some of the line intersected the enlarged node box
6950 // calculate sweep bounds for this node
6951 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6952 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6953 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6954 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6955 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6956 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6957 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6959 leaf = bih->leafs + node->children[axis];
6960 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6965 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6966 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6968 case BIH_COLLISIONTRIANGLE:
6969 if (!mod_q3bsp_curves_collisions.integer)
6971 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6972 texture = model->data_textures + leaf->textureindex;
6973 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);
6975 case BIH_RENDERTRIANGLE:
6976 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6977 texture = model->data_textures + leaf->textureindex;
6978 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);
6986 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, int skipsupercontentsmask)
6988 if (VectorCompare(start, end))
6990 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
6993 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, &model->collision_bih);
6996 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, int skipsupercontentsmask)
6999 const bih_leaf_t *leaf;
7000 const bih_node_t *node;
7001 const colbrushf_t *brush;
7003 const texture_t *texture;
7004 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
7005 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
7006 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
7007 int axis, nodenum, nodestackpos = 0, nodestack[1024];
7009 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
7011 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
7012 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask);
7014 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask);
7018 bih = &model->collision_bih;
7021 nodenum = bih->rootnode;
7023 // box trace, performed as brush trace
7024 memset(trace, 0, sizeof(*trace));
7025 trace->fraction = 1;
7026 trace->hitsupercontentsmask = hitsupercontentsmask;
7027 trace->skipsupercontentsmask = skipsupercontentsmask;
7029 // calculate tracebox-like parameters for efficient culling
7030 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
7031 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
7032 VectorSubtract(thisbrush_start->mins, start, startmins);
7033 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
7034 VectorSubtract(thisbrush_end->mins, end, endmins);
7035 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7036 mins[0] = min(startmins[0], endmins[0]);
7037 mins[1] = min(startmins[1], endmins[1]);
7038 mins[2] = min(startmins[2], endmins[2]);
7039 maxs[0] = max(startmaxs[0], endmaxs[0]);
7040 maxs[1] = max(startmaxs[1], endmaxs[1]);
7041 maxs[2] = max(startmaxs[2], endmaxs[2]);
7044 nodestackline[nodestackpos][0] = start[0];
7045 nodestackline[nodestackpos][1] = start[1];
7046 nodestackline[nodestackpos][2] = start[2];
7047 nodestackline[nodestackpos][3] = end[0];
7048 nodestackline[nodestackpos][4] = end[1];
7049 nodestackline[nodestackpos][5] = end[2];
7050 nodestack[nodestackpos++] = nodenum;
7051 while (nodestackpos)
7053 nodenum = nodestack[--nodestackpos];
7054 node = bih->nodes + nodenum;
7055 VectorCopy(nodestackline[nodestackpos], nodestart);
7056 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7057 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7058 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7059 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7060 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7061 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7062 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7063 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7065 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7067 // recurse children of the split
7068 axis = node->type - BIH_SPLITX;
7069 d1 = node->backmax - nodestart[axis] - mins[axis];
7070 d2 = node->backmax - nodeend[axis] - mins[axis];
7071 d3 = nodestart[axis] - node->frontmin + maxs[axis];
7072 d4 = nodeend[axis] - node->frontmin + maxs[axis];
7073 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7075 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;
7076 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;
7077 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;
7078 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7079 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;
7080 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;
7081 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;
7082 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7083 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;
7084 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;
7085 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;
7086 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7087 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7088 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7089 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7090 case 15: /* <<<< */ break;
7093 else if (node->type == BIH_UNORDERED)
7095 // calculate sweep bounds for this node
7096 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7097 VectorSubtract(node->mins, maxs, nodebigmins);
7098 VectorSubtract(node->maxs, mins, nodebigmaxs);
7099 // clip line to this node bounds
7100 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); }
7101 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); }
7102 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); }
7103 // some of the line intersected the enlarged node box
7104 // calculate sweep bounds for this node
7105 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7106 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7107 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7108 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7109 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7110 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7111 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7113 leaf = bih->leafs + node->children[axis];
7114 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7119 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7120 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7122 case BIH_COLLISIONTRIANGLE:
7123 if (!mod_q3bsp_curves_collisions.integer)
7125 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7126 texture = model->data_textures + leaf->textureindex;
7127 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);
7129 case BIH_RENDERTRIANGLE:
7130 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7131 texture = model->data_textures + leaf->textureindex;
7132 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);
7140 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, int skipsupercontentsmask)
7142 colboxbrushf_t thisbrush_start, thisbrush_end;
7143 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7145 // box trace, performed as brush trace
7146 VectorAdd(start, boxmins, boxstartmins);
7147 VectorAdd(start, boxmaxs, boxstartmaxs);
7148 VectorAdd(end, boxmins, boxendmins);
7149 VectorAdd(end, boxmaxs, boxendmaxs);
7150 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7151 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7152 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask);
7156 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7159 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0);
7160 return trace.startsupercontents;
7163 qboolean Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
7166 Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0);
7167 return trace.fraction == 1;
7170 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, int skipsupercontentsmask)
7173 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7175 int hitsupercontents;
7176 VectorSet(end, start[0], start[1], model->normalmins[2]);
7178 memset(trace, 0, sizeof(*trace));
7179 trace->fraction = 1;
7180 trace->hitsupercontentsmask = hitsupercontentsmask;
7181 trace->skipsupercontentsmask = skipsupercontentsmask;
7183 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7184 hitsupercontents = trace->hitsupercontents;
7185 memset(trace, 0, sizeof(*trace));
7186 trace->fraction = 1;
7187 trace->hitsupercontentsmask = hitsupercontentsmask;
7188 trace->skipsupercontentsmask = skipsupercontentsmask;
7189 trace->startsupercontents = hitsupercontents;
7193 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7196 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7199 VectorSet(end, start[0], start[1], model->normalmins[2]);
7200 memset(&trace, 0, sizeof(trace));
7202 trace.hitsupercontentsmask = hitsupercontentsmask;
7203 trace.skipsupercontentsmask = skipsupercontentsmask;
7204 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7205 return trace.hitsupercontents;
7211 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
7216 // find which leaf the point is in
7218 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7219 // point trace the brushes
7220 leaf = (mleaf_t *)node;
7221 for (i = 0;i < leaf->numleafbrushes;i++)
7223 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7224 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
7226 brush->markframe = markframe;
7227 Collision_TracePointBrushFloat(trace, point, brush);
7230 // can't do point traces on curves (they have no thickness)
7233 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)
7235 int i, startside, endside;
7236 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
7238 msurface_t *surface;
7241 // walk the tree until we hit a leaf, recursing for any split cases
7245 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7247 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7248 node = node->children[1];
7250 // abort if this part of the bsp tree can not be hit by this trace
7251 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7253 plane = node->plane;
7254 // axial planes are much more common than non-axial, so an optimized
7255 // axial case pays off here
7256 if (plane->type < 3)
7258 dist1 = start[plane->type] - plane->dist;
7259 dist2 = end[plane->type] - plane->dist;
7263 dist1 = DotProduct(start, plane->normal) - plane->dist;
7264 dist2 = DotProduct(end, plane->normal) - plane->dist;
7266 startside = dist1 < 0;
7267 endside = dist2 < 0;
7268 if (startside == endside)
7270 // most of the time the line fragment is on one side of the plane
7271 node = node->children[startside];
7275 // line crosses node plane, split the line
7276 dist1 = PlaneDiff(linestart, plane);
7277 dist2 = PlaneDiff(lineend, plane);
7278 midfrac = dist1 / (dist1 - dist2);
7279 VectorLerp(linestart, midfrac, lineend, mid);
7280 // take the near side first
7281 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7282 // if we found an impact on the front side, don't waste time
7283 // exploring the far side
7284 if (midfrac <= trace->fraction)
7285 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7290 // abort if this part of the bsp tree can not be hit by this trace
7291 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7294 nodesegmentmins[0] = min(start[0], end[0]) - 1;
7295 nodesegmentmins[1] = min(start[1], end[1]) - 1;
7296 nodesegmentmins[2] = min(start[2], end[2]) - 1;
7297 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
7298 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
7299 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
7300 // line trace the brushes
7301 leaf = (mleaf_t *)node;
7303 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7306 for (i = 0;i < leaf->numleafbrushes;i++)
7308 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7309 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7311 brush->markframe = markframe;
7312 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
7315 // can't do point traces on curves (they have no thickness)
7316 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
7318 // line trace the curves
7319 for (i = 0;i < leaf->numleafsurfaces;i++)
7321 surface = model->data_surfaces + leaf->firstleafsurface[i];
7322 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7324 surface->deprecatedq3collisionmarkframe = markframe;
7325 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);
7331 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)
7337 msurface_t *surface;
7339 float nodesegmentmins[3], nodesegmentmaxs[3];
7340 // walk the tree until we hit a leaf, recursing for any split cases
7344 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7346 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7347 node = node->children[1];
7349 // abort if this part of the bsp tree can not be hit by this trace
7350 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7352 plane = node->plane;
7353 // axial planes are much more common than non-axial, so an optimized
7354 // axial case pays off here
7355 if (plane->type < 3)
7357 // this is an axial plane, compare bounding box directly to it and
7358 // recurse sides accordingly
7359 // recurse down node sides
7360 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
7361 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
7362 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
7363 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
7367 // this is a non-axial plane, so check if the start and end boxes
7368 // are both on one side of the plane to handle 'diagonal' cases
7369 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
7373 // segment crosses plane
7374 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7377 // if sides == 0 then the trace itself is bogus (Not A Number values),
7378 // in this case we simply pretend the trace hit nothing
7380 return; // ERROR: NAN bounding box!
7381 // take whichever side the segment box is on
7382 node = node->children[sides - 1];
7385 // abort if this part of the bsp tree can not be hit by this trace
7386 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7388 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
7389 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
7390 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
7391 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
7392 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
7393 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
7395 leaf = (mleaf_t *)node;
7397 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7400 for (i = 0;i < leaf->numleafbrushes;i++)
7402 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7403 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7405 brush->markframe = markframe;
7406 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7409 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
7411 for (i = 0;i < leaf->numleafsurfaces;i++)
7413 surface = model->data_surfaces + leaf->firstleafsurface[i];
7414 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7416 surface->deprecatedq3collisionmarkframe = markframe;
7417 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);
7424 static int markframe = 0;
7426 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, int skipsupercontentsmask)
7430 memset(trace, 0, sizeof(*trace));
7431 trace->fraction = 1;
7432 trace->hitsupercontentsmask = hitsupercontentsmask;
7433 trace->skipsupercontentsmask = skipsupercontentsmask;
7434 if (mod_collision_bih.integer)
7435 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
7436 else if (model->brush.submodel)
7438 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7439 if (brush->colbrushf)
7440 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
7443 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
7446 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, int skipsupercontentsmask)
7449 float segmentmins[3], segmentmaxs[3];
7450 msurface_t *surface;
7453 if (VectorCompare(start, end))
7455 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
7459 memset(trace, 0, sizeof(*trace));
7460 trace->fraction = 1;
7461 trace->hitsupercontentsmask = hitsupercontentsmask;
7462 trace->skipsupercontentsmask = skipsupercontentsmask;
7463 segmentmins[0] = min(start[0], end[0]) - 1;
7464 segmentmins[1] = min(start[1], end[1]) - 1;
7465 segmentmins[2] = min(start[2], end[2]) - 1;
7466 segmentmaxs[0] = max(start[0], end[0]) + 1;
7467 segmentmaxs[1] = max(start[1], end[1]) + 1;
7468 segmentmaxs[2] = max(start[2], end[2]) + 1;
7469 if (mod_collision_bih.integer)
7470 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7471 else if (model->brush.submodel)
7473 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7474 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7475 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7476 if (mod_q3bsp_curves_collisions.integer)
7477 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7478 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7479 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);
7482 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
7485 static 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, int skipsupercontentsmask)
7487 float segmentmins[3], segmentmaxs[3];
7489 msurface_t *surface;
7492 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
7494 if (VectorCompare(start->mins, end->mins))
7495 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask, skipsupercontentsmask);
7497 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask, skipsupercontentsmask);
7501 // box trace, performed as brush trace
7502 memset(trace, 0, sizeof(*trace));
7503 trace->fraction = 1;
7504 trace->hitsupercontentsmask = hitsupercontentsmask;
7505 trace->skipsupercontentsmask = skipsupercontentsmask;
7506 segmentmins[0] = min(start->mins[0], end->mins[0]) - 1;
7507 segmentmins[1] = min(start->mins[1], end->mins[1]) - 1;
7508 segmentmins[2] = min(start->mins[2], end->mins[2]) - 1;
7509 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]) + 1;
7510 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]) + 1;
7511 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]) + 1;
7512 if (mod_collision_bih.integer)
7513 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7514 else if (model->brush.submodel)
7516 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7517 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7518 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7519 if (mod_q3bsp_curves_collisions.integer)
7520 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7521 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7522 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);
7525 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
7528 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, int skipsupercontentsmask)
7530 colboxbrushf_t thisbrush_start, thisbrush_end;
7531 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7533 // box trace, performed as brush trace
7534 VectorAdd(start, boxmins, boxstartmins);
7535 VectorAdd(start, boxmaxs, boxstartmaxs);
7536 VectorAdd(end, boxmins, boxendmins);
7537 VectorAdd(end, boxmaxs, boxendmaxs);
7538 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7539 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7540 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask);
7543 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7546 int supercontents = 0;
7548 if (mod_collision_bih.integer)
7550 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
7552 // test if the point is inside each brush
7553 else if (model->brush.submodel)
7555 // submodels are effectively one leaf
7556 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7557 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7558 supercontents |= brush->colbrushf->supercontents;
7562 mnode_t *node = model->brush.data_nodes;
7564 // find which leaf the point is in
7566 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7567 leaf = (mleaf_t *)node;
7568 // now check the brushes in the leaf
7569 for (i = 0;i < leaf->numleafbrushes;i++)
7571 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
7572 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7573 supercontents |= brush->colbrushf->supercontents;
7576 return supercontents;
7579 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, int skipsupercontentsmask)
7581 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, &model->render_bih);
7585 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
7593 int nummodelbrushes = model->nummodelbrushes;
7594 int nummodelsurfaces = model->nummodelsurfaces;
7596 const int *collisionelement3i;
7597 const float *collisionvertex3f;
7598 const int *renderelement3i;
7599 const float *rendervertex3f;
7600 bih_leaf_t *bihleafs;
7601 bih_node_t *bihnodes;
7603 int *temp_leafsortscratch;
7604 const msurface_t *surface;
7605 const q3mbrush_t *brush;
7607 // find out how many BIH leaf nodes we need
7609 if (userendersurfaces)
7611 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7612 bihnumleafs += surface->num_triangles;
7616 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7617 if (brush->colbrushf)
7619 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7621 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7622 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7624 bihnumleafs += surface->num_collisiontriangles;
7631 // allocate the memory for the BIH leaf nodes
7632 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7634 // now populate the BIH leaf nodes
7637 // add render surfaces
7638 renderelement3i = model->surfmesh.data_element3i;
7639 rendervertex3f = model->surfmesh.data_vertex3f;
7640 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7642 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7644 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7646 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7647 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7648 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7649 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7650 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7651 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7652 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7653 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7654 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7655 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7660 if (!userendersurfaces)
7662 // add collision brushes
7663 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7665 if (!brush->colbrushf)
7667 bihleafs[bihleafindex].type = BIH_BRUSH;
7668 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7669 bihleafs[bihleafindex].surfaceindex = -1;
7670 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7671 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7672 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7676 // add collision surfaces
7677 collisionelement3i = model->brush.data_collisionelement3i;
7678 collisionvertex3f = model->brush.data_collisionvertex3f;
7679 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7681 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7683 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7684 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7685 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7686 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7687 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7688 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7689 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7690 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7691 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7692 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7698 // allocate buffers for the produced and temporary data
7699 bihmaxnodes = bihnumleafs + 1;
7700 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7701 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7702 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7705 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7707 // we're done with the temporary data
7708 Mem_Free(temp_leafsort);
7710 // resize the BIH nodes array if it over-allocated
7711 if (out->maxnodes > out->numnodes)
7713 out->maxnodes = out->numnodes;
7714 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7720 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7722 int supercontents = 0;
7723 if (nativecontents & CONTENTSQ3_SOLID)
7724 supercontents |= SUPERCONTENTS_SOLID;
7725 if (nativecontents & CONTENTSQ3_WATER)
7726 supercontents |= SUPERCONTENTS_WATER;
7727 if (nativecontents & CONTENTSQ3_SLIME)
7728 supercontents |= SUPERCONTENTS_SLIME;
7729 if (nativecontents & CONTENTSQ3_LAVA)
7730 supercontents |= SUPERCONTENTS_LAVA;
7731 if (nativecontents & CONTENTSQ3_BODY)
7732 supercontents |= SUPERCONTENTS_BODY;
7733 if (nativecontents & CONTENTSQ3_CORPSE)
7734 supercontents |= SUPERCONTENTS_CORPSE;
7735 if (nativecontents & CONTENTSQ3_NODROP)
7736 supercontents |= SUPERCONTENTS_NODROP;
7737 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7738 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7739 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7740 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7741 if (nativecontents & CONTENTSQ3_DONOTENTER)
7742 supercontents |= SUPERCONTENTS_DONOTENTER;
7743 if (nativecontents & CONTENTSQ3_BOTCLIP)
7744 supercontents |= SUPERCONTENTS_BOTCLIP;
7745 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7746 supercontents |= SUPERCONTENTS_OPAQUE;
7747 return supercontents;
7750 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7752 int nativecontents = 0;
7753 if (supercontents & SUPERCONTENTS_SOLID)
7754 nativecontents |= CONTENTSQ3_SOLID;
7755 if (supercontents & SUPERCONTENTS_WATER)
7756 nativecontents |= CONTENTSQ3_WATER;
7757 if (supercontents & SUPERCONTENTS_SLIME)
7758 nativecontents |= CONTENTSQ3_SLIME;
7759 if (supercontents & SUPERCONTENTS_LAVA)
7760 nativecontents |= CONTENTSQ3_LAVA;
7761 if (supercontents & SUPERCONTENTS_BODY)
7762 nativecontents |= CONTENTSQ3_BODY;
7763 if (supercontents & SUPERCONTENTS_CORPSE)
7764 nativecontents |= CONTENTSQ3_CORPSE;
7765 if (supercontents & SUPERCONTENTS_NODROP)
7766 nativecontents |= CONTENTSQ3_NODROP;
7767 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7768 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7769 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7770 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7771 if (supercontents & SUPERCONTENTS_DONOTENTER)
7772 nativecontents |= CONTENTSQ3_DONOTENTER;
7773 if (supercontents & SUPERCONTENTS_BOTCLIP)
7774 nativecontents |= CONTENTSQ3_BOTCLIP;
7775 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7776 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7777 return nativecontents;
7780 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7785 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7786 node = node->children[1];
7788 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7789 if (loadmodel->brush.num_leafs < numleafs)
7790 loadmodel->brush.num_leafs = numleafs;
7793 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7796 q3dheader_t *header;
7797 float corner[3], yawradius, modelradius;
7799 mod->modeldatatypestring = "Q3BSP";
7801 mod->type = mod_brushq3;
7802 mod->brush.ishlbsp = false;
7803 mod->brush.isbsp2rmqe = false;
7804 mod->brush.isbsp2 = false;
7805 mod->brush.isq2bsp = false;
7806 mod->brush.isq3bsp = true;
7807 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7810 header = (q3dheader_t *)buffer;
7811 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7812 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7814 i = LittleLong(header->version);
7815 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7816 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7818 mod->soundfromcenter = true;
7819 mod->TraceBox = Mod_Q3BSP_TraceBox;
7820 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7821 mod->TraceLine = Mod_Q3BSP_TraceLine;
7822 mod->TracePoint = Mod_Q3BSP_TracePoint;
7823 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7824 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7825 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7826 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7827 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7828 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7829 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7830 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7831 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7832 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7833 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7834 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7835 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7836 mod->brush.AmbientSoundLevelsForPoint = NULL;
7837 mod->brush.RoundUpToHullSize = NULL;
7838 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7839 mod->Draw = R_Q1BSP_Draw;
7840 mod->DrawDepth = R_Q1BSP_DrawDepth;
7841 mod->DrawDebug = R_Q1BSP_DrawDebug;
7842 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7843 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7844 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7845 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7846 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7847 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7848 mod->DrawLight = R_Q1BSP_DrawLight;
7850 mod_base = (unsigned char *)header;
7852 // swap all the lumps
7853 header->ident = LittleLong(header->ident);
7854 header->version = LittleLong(header->version);
7855 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7856 for (i = 0;i < lumps;i++)
7858 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7859 if((char *) bufferend < (char *) buffer + j)
7860 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7861 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7862 if((char *) bufferend < (char *) buffer + j)
7863 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7866 * NO, do NOT clear them!
7867 * they contain actual data referenced by other stuff.
7868 * Instead, before using the advertisements lump, check header->versio
7870 * Sorry, but otherwise it breaks memory of the first lump.
7871 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7873 header->lumps[i].fileofs = 0;
7874 header->lumps[i].filelen = 0;
7878 mod->brush.qw_md4sum = 0;
7879 mod->brush.qw_md4sum2 = 0;
7880 for (i = 0;i < lumps;i++)
7882 if (i == Q3LUMP_ENTITIES)
7884 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7885 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7887 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7889 // all this checksumming can take a while, so let's send keepalives here too
7890 CL_KeepaliveMessage(false);
7893 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7894 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7895 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7896 if (header->version == Q3BSPVERSION_IG)
7897 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7899 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7900 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7901 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7902 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7903 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7904 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7905 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7906 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7907 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7908 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7909 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7910 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7911 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7912 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7913 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7915 // the MakePortals code works fine on the q3bsp data as well
7916 if (mod_bsp_portalize.integer)
7917 Mod_Q1BSP_MakePortals();
7919 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7920 loadmodel->brush.supportwateralpha = true;
7922 // make a single combined shadow mesh to allow optimized shadow volume creation
7923 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7925 loadmodel->brush.num_leafs = 0;
7926 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7928 if (loadmodel->brush.numsubmodels)
7929 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7932 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7937 // duplicate the basic information
7938 dpsnprintf(name, sizeof(name), "*%i", i);
7939 mod = Mod_FindName(name, loadmodel->name);
7940 // copy the base model to this one
7942 // rename the clone back to its proper name
7943 strlcpy(mod->name, name, sizeof(mod->name));
7944 mod->brush.parentmodel = loadmodel;
7945 // textures and memory belong to the main model
7946 mod->texturepool = NULL;
7947 mod->mempool = NULL;
7948 mod->brush.GetPVS = NULL;
7949 mod->brush.FatPVS = NULL;
7950 mod->brush.BoxTouchingPVS = NULL;
7951 mod->brush.BoxTouchingLeafPVS = NULL;
7952 mod->brush.BoxTouchingVisibleLeafs = NULL;
7953 mod->brush.FindBoxClusters = NULL;
7954 mod->brush.LightPoint = NULL;
7955 mod->brush.AmbientSoundLevelsForPoint = NULL;
7957 mod->brush.submodel = i;
7958 if (loadmodel->brush.submodels)
7959 loadmodel->brush.submodels[i] = mod;
7961 // make the model surface list (used by shadowing/lighting)
7962 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7963 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7964 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7965 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7966 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7967 Mod_MakeSortedSurfaces(mod);
7969 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7970 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7971 // enlarge the bounding box to enclose all geometry of this model,
7972 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7973 // which can in turn mess up the farclip (as well as culling when
7974 // outside the level - an unimportant concern)
7976 //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]);
7977 for (j = 0;j < mod->nummodelsurfaces;j++)
7979 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7980 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7982 if (!surface->num_vertices)
7984 for (k = 0;k < surface->num_vertices;k++, v += 3)
7986 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7987 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7988 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7989 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7990 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7991 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7994 //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]);
7995 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7996 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7997 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7998 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7999 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8000 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8001 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8002 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8003 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8004 mod->yawmins[2] = mod->normalmins[2];
8005 mod->yawmaxs[2] = mod->normalmaxs[2];
8006 mod->radius = modelradius;
8007 mod->radius2 = modelradius * modelradius;
8009 // this gets altered below if sky or water is used
8010 mod->DrawSky = NULL;
8011 mod->DrawAddWaterPlanes = NULL;
8013 for (j = 0;j < mod->nummodelsurfaces;j++)
8014 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8016 if (j < mod->nummodelsurfaces)
8017 mod->DrawSky = R_Q1BSP_DrawSky;
8019 for (j = 0;j < mod->nummodelsurfaces;j++)
8020 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8022 if (j < mod->nummodelsurfaces)
8023 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8025 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
8026 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
8028 // generate VBOs and other shared data before cloning submodels
8033 if (mod_q3bsp_sRGBlightmaps.integer)
8035 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
8037 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
8038 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
8039 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
8040 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
8041 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
8043 else // if this is NOT set, regular rendering looks right by this requirement anyway
8046 // we want color 1 to do the same as without sRGB
8047 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
8048 loadmodel->lightmapscale *= 2.476923f; // fixes max level
8051 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
8052 // we need to undo that
8053 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
8057 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);
8060 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
8062 int i = LittleLong(((int *)buffer)[1]);
8063 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
8064 Mod_Q3BSP_Load(mod,buffer, bufferend);
8065 else if (i == Q2BSPVERSION)
8066 Mod_Q2BSP_Load(mod,buffer, bufferend);
8068 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
8071 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
8073 Host_Error("Mod_MAP_Load: not yet implemented");
8076 typedef struct objvertex_s
8087 static unsigned char nobsp_pvs[1] = {1};
8089 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
8091 const char *textbase = (char *)buffer, *text = textbase;
8095 char materialname[MAX_QPATH];
8096 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
8097 int index1, index2, index3;
8098 objvertex_t vfirst, vprev, vcurrent;
8101 int numtriangles = 0;
8102 int maxtriangles = 0;
8103 objvertex_t *vertices = NULL;
8105 int maxtextures = 0, numtextures = 0, textureindex = 0;
8106 int maxv = 0, numv = 1;
8107 int maxvt = 0, numvt = 1;
8108 int maxvn = 0, numvn = 1;
8109 char *texturenames = NULL;
8110 float dist, modelradius, modelyawradius, yawradius;
8111 float *obj_v = NULL;
8112 float *obj_vt = NULL;
8113 float *obj_vn = NULL;
8117 objvertex_t *thisvertex = NULL;
8118 int vertexhashindex;
8119 int *vertexhashtable = NULL;
8120 objvertex_t *vertexhashdata = NULL;
8121 objvertex_t *vdata = NULL;
8122 int vertexhashsize = 0;
8123 int vertexhashcount = 0;
8124 skinfile_t *skinfiles = NULL;
8125 unsigned char *data = NULL;
8126 int *submodelfirstsurface;
8127 msurface_t *tempsurface;
8128 msurface_t *tempsurfaces;
8130 memset(&vfirst, 0, sizeof(vfirst));
8131 memset(&vprev, 0, sizeof(vprev));
8132 memset(&vcurrent, 0, sizeof(vcurrent));
8134 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8136 loadmodel->modeldatatypestring = "OBJ";
8138 loadmodel->type = mod_obj;
8139 loadmodel->soundfromcenter = true;
8140 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
8141 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
8142 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
8143 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
8144 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8145 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
8146 loadmodel->brush.TraceLineOfSight = NULL;
8147 loadmodel->brush.SuperContentsFromNativeContents = NULL;
8148 loadmodel->brush.NativeContentsFromSuperContents = NULL;
8149 loadmodel->brush.GetPVS = NULL;
8150 loadmodel->brush.FatPVS = NULL;
8151 loadmodel->brush.BoxTouchingPVS = NULL;
8152 loadmodel->brush.BoxTouchingLeafPVS = NULL;
8153 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
8154 loadmodel->brush.FindBoxClusters = NULL;
8155 loadmodel->brush.LightPoint = NULL;
8156 loadmodel->brush.FindNonSolidLocation = NULL;
8157 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8158 loadmodel->brush.RoundUpToHullSize = NULL;
8159 loadmodel->brush.PointInLeaf = NULL;
8160 loadmodel->Draw = R_Q1BSP_Draw;
8161 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
8162 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
8163 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
8164 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
8165 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
8166 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
8167 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
8168 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
8169 loadmodel->DrawLight = R_Q1BSP_DrawLight;
8171 skinfiles = Mod_LoadSkinFiles();
8172 if (loadmodel->numskins < 1)
8173 loadmodel->numskins = 1;
8175 // make skinscenes for the skins (no groups)
8176 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8177 for (i = 0;i < loadmodel->numskins;i++)
8179 loadmodel->skinscenes[i].firstframe = i;
8180 loadmodel->skinscenes[i].framecount = 1;
8181 loadmodel->skinscenes[i].loop = true;
8182 loadmodel->skinscenes[i].framerate = 10;
8188 // we always have model 0, i.e. the first "submodel"
8189 loadmodel->brush.numsubmodels = 1;
8191 // parse the OBJ text now
8194 static char emptyarg[1] = "";
8199 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8200 line[linelen] = text[linelen];
8202 for (argc = 0;argc < 4;argc++)
8203 argv[argc] = emptyarg;
8206 while (*s == ' ' || *s == '\t')
8216 while (*s == ' ' || *s == '\t')
8226 if (argv[0][0] == '#')
8228 if (!strcmp(argv[0], "v"))
8232 maxv = max(maxv * 2, 1024);
8233 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
8235 if(mod_obj_orientation.integer)
8237 obj_v[numv*3+0] = atof(argv[1]);
8238 obj_v[numv*3+2] = atof(argv[2]);
8239 obj_v[numv*3+1] = atof(argv[3]);
8243 obj_v[numv*3+0] = atof(argv[1]);
8244 obj_v[numv*3+1] = atof(argv[2]);
8245 obj_v[numv*3+2] = atof(argv[3]);
8249 else if (!strcmp(argv[0], "vt"))
8253 maxvt = max(maxvt * 2, 1024);
8254 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
8256 obj_vt[numvt*2+0] = atof(argv[1]);
8257 obj_vt[numvt*2+1] = 1-atof(argv[2]);
8260 else if (!strcmp(argv[0], "vn"))
8264 maxvn = max(maxvn * 2, 1024);
8265 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
8267 if(mod_obj_orientation.integer)
8269 obj_vn[numvn*3+0] = atof(argv[1]);
8270 obj_vn[numvn*3+2] = atof(argv[2]);
8271 obj_vn[numvn*3+1] = atof(argv[3]);
8275 obj_vn[numvn*3+0] = atof(argv[1]);
8276 obj_vn[numvn*3+1] = atof(argv[2]);
8277 obj_vn[numvn*3+2] = atof(argv[3]);
8281 else if (!strcmp(argv[0], "f"))
8285 if (maxtextures <= numtextures)
8287 maxtextures = max(maxtextures * 2, 256);
8288 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8290 textureindex = numtextures++;
8291 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
8293 for (j = 1;j < argc;j++)
8295 index1 = atoi(argv[j]);
8296 while(argv[j][0] && argv[j][0] != '/')
8300 index2 = atoi(argv[j]);
8301 while(argv[j][0] && argv[j][0] != '/')
8305 index3 = atoi(argv[j]);
8306 // negative refers to a recent vertex
8307 // zero means not specified
8308 // positive means an absolute vertex index
8310 index1 = numv - index1;
8312 index2 = numvt - index2;
8314 index3 = numvn - index3;
8315 vcurrent.nextindex = -1;
8316 vcurrent.textureindex = textureindex;
8317 vcurrent.submodelindex = submodelindex;
8318 if (obj_v && index1 >= 0 && index1 < numv)
8319 VectorCopy(obj_v + 3*index1, vcurrent.v);
8320 if (obj_vt && index2 >= 0 && index2 < numvt)
8321 Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
8322 if (obj_vn && index3 >= 0 && index3 < numvn)
8323 VectorCopy(obj_vn + 3*index3, vcurrent.vn);
8324 if (numtriangles == 0)
8326 VectorCopy(vcurrent.v, mins);
8327 VectorCopy(vcurrent.v, maxs);
8331 mins[0] = min(mins[0], vcurrent.v[0]);
8332 mins[1] = min(mins[1], vcurrent.v[1]);
8333 mins[2] = min(mins[2], vcurrent.v[2]);
8334 maxs[0] = max(maxs[0], vcurrent.v[0]);
8335 maxs[1] = max(maxs[1], vcurrent.v[1]);
8336 maxs[2] = max(maxs[2], vcurrent.v[2]);
8342 if (maxtriangles <= numtriangles)
8344 maxtriangles = max(maxtriangles * 2, 32768);
8345 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8347 if(mod_obj_orientation.integer)
8349 vertices[numtriangles*3+0] = vfirst;
8350 vertices[numtriangles*3+1] = vprev;
8351 vertices[numtriangles*3+2] = vcurrent;
8355 vertices[numtriangles*3+0] = vfirst;
8356 vertices[numtriangles*3+2] = vprev;
8357 vertices[numtriangles*3+1] = vcurrent;
8364 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8366 submodelindex = atof(argv[1]);
8367 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8369 else if (!strcmp(argv[0], "usemtl"))
8371 for (i = 0;i < numtextures;i++)
8372 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8374 if (i < numtextures)
8378 if (maxtextures <= numtextures)
8380 maxtextures = max(maxtextures * 2, 256);
8381 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8383 textureindex = numtextures++;
8384 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8389 // now that we have the OBJ data loaded as-is, we can convert it
8391 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8392 VectorCopy(mins, loadmodel->normalmins);
8393 VectorCopy(maxs, loadmodel->normalmaxs);
8394 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8395 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8396 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8397 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8398 modelradius = modelyawradius + modelradius * modelradius;
8399 modelyawradius = sqrt(modelyawradius);
8400 modelradius = sqrt(modelradius);
8401 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8402 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8403 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8404 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8405 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8406 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8407 loadmodel->radius = modelradius;
8408 loadmodel->radius2 = modelradius * modelradius;
8410 // allocate storage for triangles
8411 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8412 // allocate vertex hash structures to build an optimal vertex subset
8413 vertexhashsize = numtriangles*2;
8414 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8415 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8416 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8417 vertexhashcount = 0;
8419 // gather surface stats for assigning vertex/triangle ranges
8423 loadmodel->num_surfaces = 0;
8424 // allocate storage for the worst case number of surfaces, later we resize
8425 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8426 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8427 tempsurface = tempsurfaces;
8428 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8430 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8431 for (textureindex = 0;textureindex < numtextures;textureindex++)
8433 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8435 thisvertex = vertices + vertexindex;
8436 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8439 // skip the surface creation if there are no triangles for it
8440 if (vertexindex == numtriangles*3)
8442 // create a surface for these vertices
8443 surfacevertices = 0;
8444 surfaceelements = 0;
8445 // we hack in a texture index in the surface to be fixed up later...
8446 tempsurface->texture = (texture_t *)((size_t)textureindex);
8447 // calculate bounds as we go
8448 VectorCopy(thisvertex->v, tempsurface->mins);
8449 VectorCopy(thisvertex->v, tempsurface->maxs);
8450 for (;vertexindex < numtriangles*3;vertexindex++)
8452 thisvertex = vertices + vertexindex;
8453 if (thisvertex->submodelindex != submodelindex)
8455 if (thisvertex->textureindex != textureindex)
8457 // add vertex to surface bounds
8458 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8459 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8460 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8461 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8462 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8463 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8464 // add the vertex if it is not found in the merged set, and
8465 // get its index (triangle element) for the surface
8466 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8467 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8469 vdata = vertexhashdata + i;
8470 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8475 i = vertexhashcount++;
8476 vdata = vertexhashdata + i;
8477 *vdata = *thisvertex;
8478 vdata->nextindex = vertexhashtable[vertexhashindex];
8479 vertexhashtable[vertexhashindex] = i;
8482 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8485 surfacetriangles = surfaceelements / 3;
8486 tempsurface->num_vertices = surfacevertices;
8487 tempsurface->num_triangles = surfacetriangles;
8488 tempsurface->num_firstvertex = firstvertex;
8489 tempsurface->num_firsttriangle = firsttriangle;
8490 firstvertex += tempsurface->num_vertices;
8491 firsttriangle += tempsurface->num_triangles;
8493 loadmodel->num_surfaces++;
8496 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8497 numvertices = firstvertex;
8498 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8499 tempsurfaces = NULL;
8501 // allocate storage for final mesh data
8502 loadmodel->num_textures = numtextures * loadmodel->numskins;
8503 loadmodel->num_texturesperskin = numtextures;
8504 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 *));
8505 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
8506 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8507 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8508 loadmodel->surfmesh.num_vertices = numvertices;
8509 loadmodel->surfmesh.num_triangles = numtriangles;
8510 if (r_enableshadowvolumes.integer)
8511 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
8512 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8513 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8514 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8515 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8516 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8517 if (loadmodel->surfmesh.num_vertices <= 65536)
8518 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8520 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8522 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8523 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8524 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8527 // load the textures
8528 for (textureindex = 0;textureindex < numtextures;textureindex++)
8529 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8530 Mod_FreeSkinFiles(skinfiles);
8532 // set the surface textures to their real values now that we loaded them...
8533 for (i = 0;i < loadmodel->num_surfaces;i++)
8534 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8538 Mem_Free(texturenames);
8542 Mem_Free(vertexhashtable);
8543 Mem_Free(vertexhashdata);
8545 // make a single combined shadow mesh to allow optimized shadow volume creation
8546 Mod_Q1BSP_CreateShadowMesh(loadmodel);
8548 // compute all the mesh information that was not loaded from the file
8549 if (loadmodel->surfmesh.data_element3s)
8550 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8551 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8552 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8553 // generate normals if the file did not have them
8554 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8555 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);
8556 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);
8557 if (loadmodel->surfmesh.data_neighbor3i)
8558 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8560 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8561 loadmodel->brush.num_visleafs = 1;
8562 loadmodel->brush.num_leafs = 1;
8563 loadmodel->brush.num_nodes = 0;
8564 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8565 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8566 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8567 loadmodel->brush.num_pvsclusters = 1;
8568 loadmodel->brush.num_pvsclusterbytes = 1;
8569 loadmodel->brush.data_pvsclusters = nobsp_pvs;
8570 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8571 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8572 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
8573 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8574 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8575 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8576 loadmodel->brush.data_leafs->clusterindex = 0;
8577 loadmodel->brush.data_leafs->areaindex = 0;
8578 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8579 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8580 loadmodel->brush.data_leafs->numleafbrushes = 0;
8581 loadmodel->brush.data_leafs->firstleafbrush = NULL;
8582 loadmodel->brush.supportwateralpha = true;
8584 if (loadmodel->brush.numsubmodels)
8585 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8588 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8593 // duplicate the basic information
8594 dpsnprintf(name, sizeof(name), "*%i", i);
8595 mod = Mod_FindName(name, loadmodel->name);
8596 // copy the base model to this one
8598 // rename the clone back to its proper name
8599 strlcpy(mod->name, name, sizeof(mod->name));
8600 mod->brush.parentmodel = loadmodel;
8601 // textures and memory belong to the main model
8602 mod->texturepool = NULL;
8603 mod->mempool = NULL;
8604 mod->brush.GetPVS = NULL;
8605 mod->brush.FatPVS = NULL;
8606 mod->brush.BoxTouchingPVS = NULL;
8607 mod->brush.BoxTouchingLeafPVS = NULL;
8608 mod->brush.BoxTouchingVisibleLeafs = NULL;
8609 mod->brush.FindBoxClusters = NULL;
8610 mod->brush.LightPoint = NULL;
8611 mod->brush.AmbientSoundLevelsForPoint = NULL;
8613 mod->brush.submodel = i;
8614 if (loadmodel->brush.submodels)
8615 loadmodel->brush.submodels[i] = mod;
8617 // make the model surface list (used by shadowing/lighting)
8618 mod->firstmodelsurface = submodelfirstsurface[i];
8619 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8620 mod->firstmodelbrush = 0;
8621 mod->nummodelbrushes = 0;
8622 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8623 Mod_MakeSortedSurfaces(mod);
8625 VectorClear(mod->normalmins);
8626 VectorClear(mod->normalmaxs);
8628 for (j = 0;j < mod->nummodelsurfaces;j++)
8630 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8631 const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8633 if (!surface->num_vertices)
8638 VectorCopy(v3f, mod->normalmins);
8639 VectorCopy(v3f, mod->normalmaxs);
8641 for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8643 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8644 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8645 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8646 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8647 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8648 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8651 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8652 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8653 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8654 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8655 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8656 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8657 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8658 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8659 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8660 mod->yawmins[2] = mod->normalmins[2];
8661 mod->yawmaxs[2] = mod->normalmaxs[2];
8662 mod->radius = modelradius;
8663 mod->radius2 = modelradius * modelradius;
8665 // this gets altered below if sky or water is used
8666 mod->DrawSky = NULL;
8667 mod->DrawAddWaterPlanes = NULL;
8669 for (j = 0;j < mod->nummodelsurfaces;j++)
8670 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8672 if (j < mod->nummodelsurfaces)
8673 mod->DrawSky = R_Q1BSP_DrawSky;
8675 for (j = 0;j < mod->nummodelsurfaces;j++)
8676 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8678 if (j < mod->nummodelsurfaces)
8679 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8681 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8682 mod->render_bih = mod->collision_bih;
8684 // generate VBOs and other shared data before cloning submodels
8689 Mem_Free(submodelfirstsurface);
8691 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);