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 skinframemissing = R_SkinFrame_LoadMissing();
1668 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1670 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1673 tx->basealpha = 1.0f;
1674 tx->materialshaderpass = tx->shaderpasses[0] = Mod_CreateShaderPass(skinframemissing);
1675 tx->materialshaderpass->skinframes[0] = skinframemissing;
1676 tx->currentskinframe = skinframemissing;
1677 tx->basematerialflags = MATERIALFLAG_WALL;
1678 if (i == loadmodel->num_textures - 1)
1680 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1681 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1682 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1686 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1687 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1689 tx->currentframe = tx;
1691 // clear water settings
1694 tx->refractfactor = 1;
1695 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1696 tx->reflectfactor = 1;
1697 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1698 tx->r_water_wateralpha = 1;
1699 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1700 tx->offsetscale = 1;
1702 tx->specularscalemod = 1;
1703 tx->specularpowermod = 1;
1704 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1705 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1706 // JUST GREP FOR "specularscalemod = 1".
1711 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1715 s = loadmodel->name;
1716 if (!strncasecmp(s, "maps/", 5))
1718 FS_StripExtension(s, mapname, sizeof(mapname));
1720 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1721 // LordHavoc: mostly rewritten map texture loader
1722 for (i = 0;i < nummiptex;i++)
1724 doffset = MSG_ReadLittleLong(sb);
1725 if (r_nosurftextures.integer)
1729 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1733 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1735 // copy name, but only up to 16 characters
1736 // (the output buffer can hold more than this, but the input buffer is
1738 for (j = 0;j < 16;j++)
1739 name[j] = MSG_ReadByte(&miptexsb);
1741 // pretty up the buffer (replacing any trailing garbage with 0)
1742 for (j = (int)strlen(name);j < 16;j++)
1747 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1748 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1751 mtwidth = MSG_ReadLittleLong(&miptexsb);
1752 mtheight = MSG_ReadLittleLong(&miptexsb);
1754 j = MSG_ReadLittleLong(&miptexsb);
1758 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1760 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1763 mtdata = miptexsb.data + j;
1766 if ((mtwidth & 15) || (mtheight & 15))
1767 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1769 // LordHavoc: force all names to lowercase
1770 for (j = 0;name[j];j++)
1771 if (name[j] >= 'A' && name[j] <= 'Z')
1772 name[j] += 'a' - 'A';
1774 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1775 backuptex = loadmodel->data_textures[i];
1776 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1778 loadmodel->data_textures[i] = backuptex;
1780 tx = loadmodel->data_textures + i;
1781 strlcpy(tx->name, name, sizeof(tx->name));
1782 tx->width = mtwidth;
1783 tx->height = mtheight;
1784 tx->basealpha = 1.0f;
1786 // start out with no animation
1787 tx->currentframe = tx;
1788 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
1790 if (tx->name[0] == '*')
1792 if (!strncmp(tx->name, "*lava", 5))
1794 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1795 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1797 else if (!strncmp(tx->name, "*slime", 6))
1799 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1800 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1804 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1805 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1808 else if (!strncmp(tx->name, "sky", 3))
1810 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1811 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1812 // for the surface traceline we need to hit this surface as a solid...
1813 tx->supercontents |= SUPERCONTENTS_SOLID;
1817 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1818 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1821 if (cls.state != ca_dedicated)
1823 // LordHavoc: HL sky textures are entirely different than quake
1824 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1826 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1828 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1829 if (data && image_width == image_height * 2)
1831 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1834 else if (mtdata != NULL)
1835 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1839 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);
1841 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);
1843 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1846 // did not find external texture, load it from the bsp or wad3
1847 if (loadmodel->brush.ishlbsp)
1849 // internal texture overrides wad
1850 unsigned char *pixels, *freepixels;
1851 pixels = freepixels = NULL;
1853 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1855 pixels = freepixels = W_GetTextureBGRA(tx->name);
1858 tx->width = image_width;
1859 tx->height = image_height;
1860 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1863 Mem_Free(freepixels);
1865 else if (mtdata) // texture included
1866 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1868 // if skinframe is still NULL the "missing" texture has already been assigned to this
1870 tx->materialshaderpass->skinframes[0] = skinframe;
1872 // LordHavoc: some Tenebrae textures get replaced by black
1873 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1874 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1875 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1876 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1877 tx->currentskinframe = tx->materialshaderpass->skinframes[0];
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->currentskinframe != NULL && tx->currentskinframe->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->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1909 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1910 tx->currentmaterialflags = tx->basematerialflags;
1913 // sequence the animations
1914 for (i = 0;i < nummiptex;i++)
1916 tx = loadmodel->data_textures + i;
1917 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1920 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1922 Con_Printf("Bad animating texture %s\n", tx->name);
1925 if (tx->anim_total[0] || tx->anim_total[1])
1926 continue; // already sequenced
1928 // find the number of frames in the animation
1929 memset(anims, 0, sizeof(anims));
1930 memset(altanims, 0, sizeof(altanims));
1932 for (j = i;j < nummiptex;j++)
1934 tx2 = loadmodel->data_textures + j;
1935 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1939 if (num >= '0' && num <= '9')
1940 anims[num - '0'] = tx2;
1941 else if (num >= 'a' && num <= 'j')
1942 altanims[num - 'a'] = tx2;
1943 // No need to warn otherwise - we already did above.
1947 for (j = 0;j < 10;j++)
1954 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1957 for (j = 0;j < max;j++)
1961 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1965 for (j = 0;j < altmax;j++)
1969 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1976 // If we have exactly one frame, something's wrong.
1977 if (max + altmax <= 1)
1979 Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
1984 // if there is no alternate animation, duplicate the primary
1985 // animation into the alternate
1987 for (k = 0;k < 10;k++)
1988 altanims[k] = anims[k];
1994 Con_Printf("Missing frame 0 of %s\n", tx->name);
1996 // however, we can handle this by duplicating the alternate animation into the primary
1998 for (k = 0;k < 10;k++)
1999 anims[k] = altanims[k];
2003 // link together the primary animation
2004 for (j = 0;j < max;j++)
2007 tx2->animated = 1; // q1bsp
2008 tx2->anim_total[0] = max;
2009 tx2->anim_total[1] = altmax;
2010 for (k = 0;k < 10;k++)
2012 tx2->anim_frames[0][k] = anims[k];
2013 tx2->anim_frames[1][k] = altanims[k];
2017 // if there really is an alternate anim...
2018 if (anims[0] != altanims[0])
2020 // link together the alternate animation
2021 for (j = 0;j < altmax;j++)
2024 tx2->animated = 1; // q1bsp
2025 // the primary/alternate are reversed here
2026 tx2->anim_total[0] = altmax;
2027 tx2->anim_total[1] = max;
2028 for (k = 0;k < 10;k++)
2030 tx2->anim_frames[0][k] = altanims[k];
2031 tx2->anim_frames[1][k] = anims[k];
2038 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2041 unsigned char *in, *out, *data, d;
2042 char litfilename[MAX_QPATH];
2043 char dlitfilename[MAX_QPATH];
2044 fs_offset_t filesize;
2045 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2047 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2048 for (i = 0;i < sb->cursize;i++)
2049 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2051 else // LordHavoc: bsp version 29 (normal white lighting)
2053 // LordHavoc: hope is not lost yet, check for a .lit file to load
2054 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2055 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2056 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2057 strlcat (litfilename, ".lit", sizeof (litfilename));
2058 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2059 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2062 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2064 i = LittleLong(((int *)data)[1]);
2067 if (developer_loading.integer)
2068 Con_Printf("loaded %s\n", litfilename);
2069 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2070 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2072 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2075 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2077 i = LittleLong(((int *)data)[1]);
2080 if (developer_loading.integer)
2081 Con_Printf("loaded %s\n", dlitfilename);
2082 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2083 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2084 loadmodel->brushq3.deluxemapping_modelspace = false;
2085 loadmodel->brushq3.deluxemapping = true;
2094 Con_Printf("Unknown .lit file version (%d)\n", i);
2096 else if (filesize == 8)
2097 Con_Print("Empty .lit file, ignoring\n");
2099 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2106 // LordHavoc: oh well, expand the white lighting data
2109 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2111 out = loadmodel->brushq1.lightdata;
2112 for (i = 0;i < sb->cursize;i++)
2122 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2124 loadmodel->brushq1.num_compressedpvs = 0;
2125 loadmodel->brushq1.data_compressedpvs = NULL;
2128 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2129 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2130 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2133 // used only for HalfLife maps
2134 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2136 char key[128], value[4096];
2140 if (!COM_ParseToken_Simple(&data, false, false, true))
2142 if (com_token[0] != '{')
2146 if (!COM_ParseToken_Simple(&data, false, false, true))
2148 if (com_token[0] == '}')
2149 break; // end of worldspawn
2150 if (com_token[0] == '_')
2151 strlcpy(key, com_token + 1, sizeof(key));
2153 strlcpy(key, com_token, sizeof(key));
2154 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2155 key[strlen(key)-1] = 0;
2156 if (!COM_ParseToken_Simple(&data, false, false, true))
2158 dpsnprintf(value, sizeof(value), "%s", com_token);
2159 if (!strcmp("wad", key)) // for HalfLife maps
2161 if (loadmodel->brush.ishlbsp)
2164 for (i = 0;i < (int)sizeof(value);i++)
2165 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2167 if (i < (int)sizeof(value) && value[i])
2169 for (;i < (int)sizeof(value);i++)
2171 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2172 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2174 else if (value[i] == ';' || value[i] == 0)
2178 W_LoadTextureWadFile(&value[j], false);
2190 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2192 loadmodel->brush.entities = NULL;
2195 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2196 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2197 loadmodel->brush.entities[sb->cursize] = 0;
2198 if (loadmodel->brush.ishlbsp)
2199 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2203 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2207 int structsize = 12;
2209 if (sb->cursize % structsize)
2210 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2211 count = sb->cursize / structsize;
2212 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2214 loadmodel->brushq1.vertexes = out;
2215 loadmodel->brushq1.numvertexes = count;
2217 for ( i=0 ; i<count ; i++, out++)
2219 out->position[0] = MSG_ReadLittleFloat(sb);
2220 out->position[1] = MSG_ReadLittleFloat(sb);
2221 out->position[2] = MSG_ReadLittleFloat(sb);
2225 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2229 int structsize = (48+4*hullinfo->filehulls);
2231 if (sb->cursize % structsize)
2232 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2234 count = sb->cursize / structsize;
2235 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2237 loadmodel->brushq1.submodels = out;
2238 loadmodel->brush.numsubmodels = count;
2240 for (i = 0; i < count; i++, out++)
2242 // spread out the mins / maxs by a pixel
2243 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2244 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2245 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2246 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2247 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2248 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2249 out->origin[0] = MSG_ReadLittleFloat(sb);
2250 out->origin[1] = MSG_ReadLittleFloat(sb);
2251 out->origin[2] = MSG_ReadLittleFloat(sb);
2252 for (j = 0; j < hullinfo->filehulls; j++)
2253 out->headnode[j] = MSG_ReadLittleLong(sb);
2254 out->visleafs = MSG_ReadLittleLong(sb);
2255 out->firstface = MSG_ReadLittleLong(sb);
2256 out->numfaces = MSG_ReadLittleLong(sb);
2260 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2264 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2266 if (sb->cursize % structsize)
2267 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2268 count = sb->cursize / structsize;
2269 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2271 loadmodel->brushq1.edges = out;
2272 loadmodel->brushq1.numedges = count;
2274 for ( i=0 ; i<count ; i++, out++)
2276 if (loadmodel->brush.isbsp2)
2278 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2279 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2283 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2284 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2286 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2288 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);
2289 if(!loadmodel->brushq1.numvertexes)
2290 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2298 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2301 int i, j, k, count, miptex;
2302 int structsize = 40;
2304 if (sb->cursize % structsize)
2305 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2306 count = sb->cursize / structsize;
2307 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2309 loadmodel->brushq1.texinfo = out;
2310 loadmodel->brushq1.numtexinfo = count;
2312 for (i = 0;i < count;i++, out++)
2314 for (k = 0;k < 2;k++)
2315 for (j = 0;j < 4;j++)
2316 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2318 miptex = MSG_ReadLittleLong(sb);
2319 out->q1flags = MSG_ReadLittleLong(sb);
2321 if (out->q1flags & TEX_SPECIAL)
2323 // if texture chosen is NULL or the shader needs a lightmap,
2324 // force to notexture water shader
2325 out->textureindex = loadmodel->num_textures - 1;
2329 // if texture chosen is NULL, force to notexture
2330 out->textureindex = loadmodel->num_textures - 2;
2332 // see if the specified miptex is valid and try to use it instead
2333 if (loadmodel->data_textures)
2335 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2336 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2338 out->textureindex = miptex;
2344 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2349 mins[0] = mins[1] = mins[2] = 9999;
2350 maxs[0] = maxs[1] = maxs[2] = -9999;
2352 for (i = 0;i < numverts;i++)
2354 for (j = 0;j < 3;j++, v++)
2364 #define MAX_SUBDIVPOLYTRIANGLES 4096
2365 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2367 static int subdivpolyverts, subdivpolytriangles;
2368 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2369 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2371 static int subdivpolylookupvert(vec3_t v)
2374 for (i = 0;i < subdivpolyverts;i++)
2375 if (subdivpolyvert[i][0] == v[0]
2376 && subdivpolyvert[i][1] == v[1]
2377 && subdivpolyvert[i][2] == v[2])
2379 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2380 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2381 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2382 return subdivpolyverts++;
2385 static void SubdividePolygon(int numverts, float *verts)
2387 int i, i1, i2, i3, f, b, c, p;
2388 vec3_t mins, maxs, front[256], back[256];
2389 float m, *pv, *cv, dist[256], frac;
2392 Host_Error("SubdividePolygon: ran out of verts in buffer");
2394 BoundPoly(numverts, verts, mins, maxs);
2396 for (i = 0;i < 3;i++)
2398 m = (mins[i] + maxs[i]) * 0.5;
2399 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2400 if (maxs[i] - m < 8)
2402 if (m - mins[i] < 8)
2406 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2407 dist[c] = cv[i] - m;
2410 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2414 VectorCopy(pv, front[f]);
2419 VectorCopy(pv, back[b]);
2422 if (dist[p] == 0 || dist[c] == 0)
2424 if ((dist[p] > 0) != (dist[c] > 0) )
2427 frac = dist[p] / (dist[p] - dist[c]);
2428 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2429 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2430 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2436 SubdividePolygon(f, front[0]);
2437 SubdividePolygon(b, back[0]);
2441 i1 = subdivpolylookupvert(verts);
2442 i2 = subdivpolylookupvert(verts + 3);
2443 for (i = 2;i < numverts;i++)
2445 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2447 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2451 i3 = subdivpolylookupvert(verts + i * 3);
2452 subdivpolyindex[subdivpolytriangles][0] = i1;
2453 subdivpolyindex[subdivpolytriangles][1] = i2;
2454 subdivpolyindex[subdivpolytriangles][2] = i3;
2456 subdivpolytriangles++;
2460 //Breaks a polygon up along axial 64 unit
2461 //boundaries so that turbulent and sky warps
2462 //can be done reasonably.
2463 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2469 subdivpolytriangles = 0;
2470 subdivpolyverts = 0;
2471 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2472 if (subdivpolytriangles < 1)
2473 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2475 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2476 mesh->num_vertices = subdivpolyverts;
2477 mesh->num_triangles = subdivpolytriangles;
2478 mesh->vertex = (surfvertex_t *)(mesh + 1);
2479 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2480 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2482 for (i = 0;i < mesh->num_triangles;i++)
2483 for (j = 0;j < 3;j++)
2484 mesh->index[i*3+j] = subdivpolyindex[i][j];
2486 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2488 VectorCopy(subdivpolyvert[i], v->v);
2489 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2490 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2495 extern cvar_t gl_max_lightmapsize;
2496 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2498 msurface_t *surface;
2499 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2500 float texmins[2], texmaxs[2], val;
2501 rtexture_t *lightmaptexture, *deluxemaptexture;
2503 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2505 if (sb->cursize % structsize)
2506 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2507 count = sb->cursize / structsize;
2508 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2509 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2511 loadmodel->num_surfaces = count;
2513 loadmodel->brushq1.firstrender = true;
2514 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2518 for (surfacenum = 0;surfacenum < count;surfacenum++)
2520 if (loadmodel->brush.isbsp2)
2521 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2523 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2524 totalverts += numedges;
2525 totaltris += numedges - 2;
2528 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2530 lightmaptexture = NULL;
2531 deluxemaptexture = r_texture_blanknormalmap;
2533 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2534 totallightmapsamples = 0;
2538 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2540 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2541 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2542 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2543 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2544 firstedge = MSG_ReadLittleLong(sb);
2545 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2546 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2547 for (i = 0;i < MAXLIGHTMAPS;i++)
2548 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2549 lightmapoffset = MSG_ReadLittleLong(sb);
2551 // FIXME: validate edges, texinfo, etc?
2552 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)
2553 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2554 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2555 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2556 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2557 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2559 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2560 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2562 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2563 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2564 lightmapoffset = -1;
2566 //surface->flags = surface->texture->flags;
2567 //if (LittleShort(in->side))
2568 // surface->flags |= SURF_PLANEBACK;
2569 //surface->plane = loadmodel->brush.data_planes + planenum;
2571 surface->num_firstvertex = totalverts;
2572 surface->num_vertices = numedges;
2573 surface->num_firsttriangle = totaltris;
2574 surface->num_triangles = numedges - 2;
2575 totalverts += numedges;
2576 totaltris += numedges - 2;
2578 // convert edges back to a normal polygon
2579 for (i = 0;i < surface->num_vertices;i++)
2581 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2583 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2585 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2587 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2588 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2589 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2590 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2591 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2592 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2593 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2594 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2597 for (i = 0;i < surface->num_triangles;i++)
2599 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2600 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2601 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2604 // compile additional data about the surface geometry
2605 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);
2606 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);
2607 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2609 // generate surface extents information
2610 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2611 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2612 for (i = 1;i < surface->num_vertices;i++)
2614 for (j = 0;j < 2;j++)
2616 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2617 texmins[j] = min(texmins[j], val);
2618 texmaxs[j] = max(texmaxs[j], val);
2621 for (i = 0;i < 2;i++)
2623 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2624 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2627 smax = surface->lightmapinfo->extents[0] >> 4;
2628 tmax = surface->lightmapinfo->extents[1] >> 4;
2629 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2630 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2633 surface->lightmaptexture = NULL;
2634 surface->deluxemaptexture = r_texture_blanknormalmap;
2635 if (lightmapoffset == -1)
2637 surface->lightmapinfo->samples = NULL;
2639 // give non-lightmapped water a 1x white lightmap
2640 if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2642 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2643 surface->lightmapinfo->styles[0] = 0;
2644 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2648 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LordHavoc: HalfLife map (bsp version 30)
2649 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2650 else // LordHavoc: white lighting (bsp version 29)
2652 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2653 if (loadmodel->brushq1.nmaplightdata)
2654 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2657 // check if we should apply a lightmap to this
2658 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2660 if (ssize > 256 || tsize > 256)
2661 Host_Error("Bad surface extents");
2663 if (lightmapsize < ssize)
2664 lightmapsize = ssize;
2665 if (lightmapsize < tsize)
2666 lightmapsize = tsize;
2668 totallightmapsamples += ssize*tsize;
2670 // force lightmap upload on first time seeing the surface
2672 // additionally this is used by the later code to see if a
2673 // lightmap is needed on this surface (rather than duplicating the
2675 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2676 loadmodel->lit = true;
2680 // small maps (such as ammo boxes especially) don't need big lightmap
2681 // textures, so this code tries to guess a good size based on
2682 // totallightmapsamples (size of the lightmaps lump basically), as well as
2683 // trying to max out the size if there is a lot of lightmap data to store
2684 // additionally, never choose a lightmapsize that is smaller than the
2685 // largest surface encountered (as it would fail)
2687 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2690 // now that we've decided the lightmap texture size, we can do the rest
2691 if (cls.state != ca_dedicated)
2693 int stainmapsize = 0;
2694 mod_alloclightmap_state_t allocState;
2696 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2697 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2699 int iu, iv, lightmapx = 0, lightmapy = 0;
2700 float u, v, ubase, vbase, uscale, vscale;
2702 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2705 smax = surface->lightmapinfo->extents[0] >> 4;
2706 tmax = surface->lightmapinfo->extents[1] >> 4;
2707 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2708 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2709 stainmapsize += ssize * tsize * 3;
2711 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2713 // allocate a texture pool if we need it
2714 if (loadmodel->texturepool == NULL)
2715 loadmodel->texturepool = R_AllocTexturePool();
2716 // could not find room, make a new lightmap
2717 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2718 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2719 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2720 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);
2721 if (loadmodel->brushq1.nmaplightdata)
2722 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);
2724 Mod_AllocLightmap_Reset(&allocState);
2725 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2727 surface->lightmaptexture = lightmaptexture;
2728 surface->deluxemaptexture = deluxemaptexture;
2729 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2730 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2732 uscale = 1.0f / (float)lightmapsize;
2733 vscale = 1.0f / (float)lightmapsize;
2734 ubase = lightmapx * uscale;
2735 vbase = lightmapy * vscale;
2737 for (i = 0;i < surface->num_vertices;i++)
2739 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);
2740 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);
2741 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2742 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2743 // LordHavoc: calc lightmap data offset for vertex lighting to use
2746 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2750 if (cl_stainmaps.integer)
2752 // allocate stainmaps for permanent marks on walls and clear white
2753 unsigned char *stainsamples = NULL;
2754 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2755 memset(stainsamples, 255, stainmapsize);
2757 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2759 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2761 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2762 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2763 surface->lightmapinfo->stainsamples = stainsamples;
2764 stainsamples += ssize * tsize * 3;
2769 // generate ushort elements array if possible
2770 if (loadmodel->surfmesh.data_element3s)
2771 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2772 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2775 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2778 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2779 node->parent = parent;
2782 // this is a node, recurse to children
2783 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2784 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2785 // combine supercontents of children
2786 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2791 mleaf_t *leaf = (mleaf_t *)node;
2792 // if this is a leaf, calculate supercontents mask from all collidable
2793 // primitives in the leaf (brushes and collision surfaces)
2794 // also flag if the leaf contains any collision surfaces
2795 leaf->combinedsupercontents = 0;
2796 // combine the supercontents values of all brushes in this leaf
2797 for (j = 0;j < leaf->numleafbrushes;j++)
2798 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2799 // check if this leaf contains any collision surfaces (q3 patches)
2800 for (j = 0;j < leaf->numleafsurfaces;j++)
2802 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2803 if (surface->num_collisiontriangles)
2805 leaf->containscollisionsurfaces = true;
2806 leaf->combinedsupercontents |= surface->texture->supercontents;
2812 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2814 int i, j, count, p, child[2];
2816 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2818 if (sb->cursize % structsize)
2819 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2820 count = sb->cursize / structsize;
2822 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2823 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2825 loadmodel->brush.data_nodes = out;
2826 loadmodel->brush.num_nodes = count;
2828 for ( i=0 ; i<count ; i++, out++)
2830 p = MSG_ReadLittleLong(sb);
2831 out->plane = loadmodel->brush.data_planes + p;
2833 if (loadmodel->brush.isbsp2rmqe)
2835 child[0] = MSG_ReadLittleLong(sb);
2836 child[1] = MSG_ReadLittleLong(sb);
2837 out->mins[0] = MSG_ReadLittleShort(sb);
2838 out->mins[1] = MSG_ReadLittleShort(sb);
2839 out->mins[2] = MSG_ReadLittleShort(sb);
2840 out->maxs[0] = MSG_ReadLittleShort(sb);
2841 out->maxs[1] = MSG_ReadLittleShort(sb);
2842 out->maxs[2] = MSG_ReadLittleShort(sb);
2843 out->firstsurface = MSG_ReadLittleLong(sb);
2844 out->numsurfaces = MSG_ReadLittleLong(sb);
2846 else if (loadmodel->brush.isbsp2)
2848 child[0] = MSG_ReadLittleLong(sb);
2849 child[1] = MSG_ReadLittleLong(sb);
2850 out->mins[0] = MSG_ReadLittleFloat(sb);
2851 out->mins[1] = MSG_ReadLittleFloat(sb);
2852 out->mins[2] = MSG_ReadLittleFloat(sb);
2853 out->maxs[0] = MSG_ReadLittleFloat(sb);
2854 out->maxs[1] = MSG_ReadLittleFloat(sb);
2855 out->maxs[2] = MSG_ReadLittleFloat(sb);
2856 out->firstsurface = MSG_ReadLittleLong(sb);
2857 out->numsurfaces = MSG_ReadLittleLong(sb);
2861 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2862 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2863 if (child[0] >= count)
2865 if (child[1] >= count)
2868 out->mins[0] = MSG_ReadLittleShort(sb);
2869 out->mins[1] = MSG_ReadLittleShort(sb);
2870 out->mins[2] = MSG_ReadLittleShort(sb);
2871 out->maxs[0] = MSG_ReadLittleShort(sb);
2872 out->maxs[1] = MSG_ReadLittleShort(sb);
2873 out->maxs[2] = MSG_ReadLittleShort(sb);
2875 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2876 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2879 for (j=0 ; j<2 ; j++)
2881 // LordHavoc: this code supports broken bsp files produced by
2882 // arguire qbsp which can produce more than 32768 nodes, any value
2883 // below count is assumed to be a node number, any other value is
2884 // assumed to be a leaf number
2888 if (p < loadmodel->brush.num_nodes)
2889 out->children[j] = loadmodel->brush.data_nodes + p;
2892 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2893 // map it to the solid leaf
2894 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2899 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2901 if (p < loadmodel->brush.num_leafs)
2902 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2905 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2906 // map it to the solid leaf
2907 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2913 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2916 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2919 int i, j, count, p, firstmarksurface, nummarksurfaces;
2920 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2922 if (sb->cursize % structsize)
2923 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2924 count = sb->cursize / structsize;
2925 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2927 loadmodel->brush.data_leafs = out;
2928 loadmodel->brush.num_leafs = count;
2929 // get visleafs from the submodel data
2930 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2931 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2932 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2933 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2935 // FIXME: this function could really benefit from some error checking
2936 for ( i=0 ; i<count ; i++, out++)
2938 out->contents = MSG_ReadLittleLong(sb);
2940 out->clusterindex = i - 1;
2941 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2942 out->clusterindex = -1;
2944 p = MSG_ReadLittleLong(sb);
2945 // ignore visofs errors on leaf 0 (solid)
2946 if (p >= 0 && out->clusterindex >= 0)
2948 if (p >= loadmodel->brushq1.num_compressedpvs)
2949 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2951 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);
2954 if (loadmodel->brush.isbsp2rmqe)
2956 out->mins[0] = MSG_ReadLittleShort(sb);
2957 out->mins[1] = MSG_ReadLittleShort(sb);
2958 out->mins[2] = MSG_ReadLittleShort(sb);
2959 out->maxs[0] = MSG_ReadLittleShort(sb);
2960 out->maxs[1] = MSG_ReadLittleShort(sb);
2961 out->maxs[2] = MSG_ReadLittleShort(sb);
2963 firstmarksurface = MSG_ReadLittleLong(sb);
2964 nummarksurfaces = MSG_ReadLittleLong(sb);
2966 else if (loadmodel->brush.isbsp2)
2968 out->mins[0] = MSG_ReadLittleFloat(sb);
2969 out->mins[1] = MSG_ReadLittleFloat(sb);
2970 out->mins[2] = MSG_ReadLittleFloat(sb);
2971 out->maxs[0] = MSG_ReadLittleFloat(sb);
2972 out->maxs[1] = MSG_ReadLittleFloat(sb);
2973 out->maxs[2] = MSG_ReadLittleFloat(sb);
2975 firstmarksurface = MSG_ReadLittleLong(sb);
2976 nummarksurfaces = MSG_ReadLittleLong(sb);
2980 out->mins[0] = MSG_ReadLittleShort(sb);
2981 out->mins[1] = MSG_ReadLittleShort(sb);
2982 out->mins[2] = MSG_ReadLittleShort(sb);
2983 out->maxs[0] = MSG_ReadLittleShort(sb);
2984 out->maxs[1] = MSG_ReadLittleShort(sb);
2985 out->maxs[2] = MSG_ReadLittleShort(sb);
2987 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2988 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2991 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2993 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2994 out->numleafsurfaces = nummarksurfaces;
2998 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2999 out->firstleafsurface = NULL;
3000 out->numleafsurfaces = 0;
3003 for (j = 0;j < 4;j++)
3004 out->ambient_sound_level[j] = MSG_ReadByte(sb);
3008 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
3012 const unsigned char *pvs;
3013 // if there's no vis data, assume supported (because everything is visible all the time)
3014 if (!loadmodel->brush.data_pvsclusters)
3016 // check all liquid leafs to see if they can see into empty leafs, if any
3017 // can we can assume this map supports r_wateralpha
3018 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3020 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3022 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3023 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3024 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3031 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3036 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3038 if (sb->cursize % structsize)
3039 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3040 count = sb->cursize / structsize;
3041 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3043 loadmodel->brushq1.clipnodes = out;
3044 loadmodel->brushq1.numclipnodes = count;
3046 for (i = 1; i < MAX_MAP_HULLS; i++)
3048 hull = &loadmodel->brushq1.hulls[i];
3049 hull->clipnodes = out;
3050 hull->firstclipnode = 0;
3051 hull->lastclipnode = count-1;
3052 hull->planes = loadmodel->brush.data_planes;
3053 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3054 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3055 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3056 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3057 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3058 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3059 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3062 for (i=0 ; i<count ; i++, out++)
3064 out->planenum = MSG_ReadLittleLong(sb);
3065 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3066 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3067 if (loadmodel->brush.isbsp2)
3069 out->children[0] = MSG_ReadLittleLong(sb);
3070 out->children[1] = MSG_ReadLittleLong(sb);
3071 if (out->children[0] >= count)
3072 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3073 if (out->children[1] >= count)
3074 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3078 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3079 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3080 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3081 if (out->children[0] >= count)
3082 out->children[0] -= 65536;
3083 if (out->children[1] >= count)
3084 out->children[1] -= 65536;
3089 //Duplicate the drawing hull structure as a clipping hull
3090 static void Mod_Q1BSP_MakeHull0(void)
3097 hull = &loadmodel->brushq1.hulls[0];
3099 in = loadmodel->brush.data_nodes;
3100 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3102 hull->clipnodes = out;
3103 hull->firstclipnode = 0;
3104 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3105 hull->planes = loadmodel->brush.data_planes;
3107 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3109 out->planenum = in->plane - loadmodel->brush.data_planes;
3110 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3111 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3115 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3118 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3120 if (sb->cursize % structsize)
3121 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3122 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3123 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3125 if (loadmodel->brush.isbsp2)
3127 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3129 j = MSG_ReadLittleLong(sb);
3130 if (j < 0 || j >= loadmodel->num_surfaces)
3131 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3132 loadmodel->brush.data_leafsurfaces[i] = j;
3137 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3139 j = (unsigned short) MSG_ReadLittleShort(sb);
3140 if (j >= loadmodel->num_surfaces)
3141 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3142 loadmodel->brush.data_leafsurfaces[i] = j;
3147 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3152 if (sb->cursize % structsize)
3153 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3154 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3155 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3157 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3158 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3162 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3166 int structsize = 20;
3168 if (sb->cursize % structsize)
3169 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3170 loadmodel->brush.num_planes = sb->cursize / structsize;
3171 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3173 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3175 out->normal[0] = MSG_ReadLittleFloat(sb);
3176 out->normal[1] = MSG_ReadLittleFloat(sb);
3177 out->normal[2] = MSG_ReadLittleFloat(sb);
3178 out->dist = MSG_ReadLittleFloat(sb);
3179 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3184 static void Mod_Q1BSP_LoadMapBrushes(void)
3188 int submodel, numbrushes;
3189 qboolean firstbrush;
3190 char *text, *maptext;
3191 char mapfilename[MAX_QPATH];
3192 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3193 strlcat (mapfilename, ".map", sizeof (mapfilename));
3194 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3198 if (!COM_ParseToken_Simple(&data, false, false, true))
3203 if (!COM_ParseToken_Simple(&data, false, false, true))
3205 if (com_token[0] != '{')
3211 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3214 if (!COM_ParseToken_Simple(&data, false, false, true))
3216 if (com_token[0] == '}')
3217 break; // end of entity
3218 if (com_token[0] == '{')
3225 if (submodel > loadmodel->brush.numsubmodels)
3227 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3231 model = loadmodel->brush.submodels[submodel];
3238 if (!COM_ParseToken_Simple(&data, false, false, true))
3240 if (com_token[0] == '}')
3241 break; // end of brush
3242 // each brush face should be this format:
3243 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3244 // FIXME: support hl .map format
3245 for (pointnum = 0;pointnum < 3;pointnum++)
3247 COM_ParseToken_Simple(&data, false, false, true);
3248 for (componentnum = 0;componentnum < 3;componentnum++)
3250 COM_ParseToken_Simple(&data, false, false, true);
3251 point[pointnum][componentnum] = atof(com_token);
3253 COM_ParseToken_Simple(&data, false, false, true);
3255 COM_ParseToken_Simple(&data, false, false, true);
3256 strlcpy(facetexture, com_token, sizeof(facetexture));
3257 COM_ParseToken_Simple(&data, false, false, true);
3258 //scroll_s = atof(com_token);
3259 COM_ParseToken_Simple(&data, false, false, true);
3260 //scroll_t = atof(com_token);
3261 COM_ParseToken_Simple(&data, false, false, true);
3262 //rotate = atof(com_token);
3263 COM_ParseToken_Simple(&data, false, false, true);
3264 //scale_s = atof(com_token);
3265 COM_ParseToken_Simple(&data, false, false, true);
3266 //scale_t = atof(com_token);
3267 TriangleNormal(point[0], point[1], point[2], planenormal);
3268 VectorNormalizeDouble(planenormal);
3269 planedist = DotProduct(point[0], planenormal);
3270 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3280 #define MAX_PORTALPOINTS 64
3282 typedef struct portal_s
3285 mnode_t *nodes[2]; // [0] = front side of plane
3286 struct portal_s *next[2];
3288 double points[3*MAX_PORTALPOINTS];
3289 struct portal_s *chain; // all portals are linked into a list
3293 static memexpandablearray_t portalarray;
3295 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3297 // process only nodes (leafs already had their box calculated)
3301 // calculate children first
3302 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3303 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3305 // make combined bounding box from children
3306 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3307 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3308 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3309 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3310 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3311 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3314 static void Mod_Q1BSP_FinalizePortals(void)
3316 int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3320 mleaf_t *leaf, *endleaf;
3322 // tally up portal and point counts and recalculate bounding boxes for all
3323 // leafs (because qbsp is very sloppy)
3324 leaf = loadmodel->brush.data_leafs;
3325 endleaf = leaf + loadmodel->brush.num_leafs;
3326 if (mod_recalculatenodeboxes.integer)
3328 for (;leaf < endleaf;leaf++)
3330 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3331 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3336 for (portalindex = 0;portalindex < portalrange;portalindex++)
3338 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3341 // note: this check must match the one below or it will usually corrupt memory
3342 // 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
3343 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3346 numpoints += p->numpoints * 2;
3349 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3350 loadmodel->brush.num_portals = numportals;
3351 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3352 loadmodel->brush.num_portalpoints = numpoints;
3353 // clear all leaf portal chains
3354 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3355 loadmodel->brush.data_leafs[i].portals = NULL;
3356 // process all portals in the global portal chain, while freeing them
3357 portal = loadmodel->brush.data_portals;
3358 point = loadmodel->brush.data_portalpoints;
3359 for (portalindex = 0;portalindex < portalrange;portalindex++)
3361 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3364 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3366 // note: this check must match the one above or it will usually corrupt memory
3367 // 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
3368 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3370 // first make the back to front portal(forward portal)
3371 portal->points = point;
3372 portal->numpoints = p->numpoints;
3373 portal->plane.dist = p->plane.dist;
3374 VectorCopy(p->plane.normal, portal->plane.normal);
3375 portal->here = (mleaf_t *)p->nodes[1];
3376 portal->past = (mleaf_t *)p->nodes[0];
3378 for (j = 0;j < portal->numpoints;j++)
3380 VectorCopy(p->points + j*3, point->position);
3383 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3384 PlaneClassify(&portal->plane);
3386 // link into leaf's portal chain
3387 portal->next = portal->here->portals;
3388 portal->here->portals = portal;
3390 // advance to next portal
3393 // then make the front to back portal(backward portal)
3394 portal->points = point;
3395 portal->numpoints = p->numpoints;
3396 portal->plane.dist = -p->plane.dist;
3397 VectorNegate(p->plane.normal, portal->plane.normal);
3398 portal->here = (mleaf_t *)p->nodes[0];
3399 portal->past = (mleaf_t *)p->nodes[1];
3401 for (j = portal->numpoints - 1;j >= 0;j--)
3403 VectorCopy(p->points + j*3, point->position);
3406 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3407 PlaneClassify(&portal->plane);
3409 // link into leaf's portal chain
3410 portal->next = portal->here->portals;
3411 portal->here->portals = portal;
3413 // advance to next portal
3416 // add the portal's polygon points to the leaf bounding boxes
3417 if (mod_recalculatenodeboxes.integer)
3419 for (i = 0;i < 2;i++)
3421 leaf = (mleaf_t *)p->nodes[i];
3422 for (j = 0;j < p->numpoints;j++)
3424 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3425 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3426 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3427 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3428 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3429 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3435 // now recalculate the node bounding boxes from the leafs
3436 if (mod_recalculatenodeboxes.integer)
3437 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3445 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3448 Host_Error("AddPortalToNodes: NULL front node");
3450 Host_Error("AddPortalToNodes: NULL back node");
3451 if (p->nodes[0] || p->nodes[1])
3452 Host_Error("AddPortalToNodes: already included");
3453 // 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
3455 p->nodes[0] = front;
3456 p->next[0] = (portal_t *)front->portals;
3457 front->portals = (mportal_t *)p;
3460 p->next[1] = (portal_t *)back->portals;
3461 back->portals = (mportal_t *)p;
3466 RemovePortalFromNode
3469 static void RemovePortalFromNodes(portal_t *portal)
3473 void **portalpointer;
3475 for (i = 0;i < 2;i++)
3477 node = portal->nodes[i];
3479 portalpointer = (void **) &node->portals;
3482 t = (portal_t *)*portalpointer;
3484 Host_Error("RemovePortalFromNodes: portal not in leaf");
3488 if (portal->nodes[0] == node)
3490 *portalpointer = portal->next[0];
3491 portal->nodes[0] = NULL;
3493 else if (portal->nodes[1] == node)
3495 *portalpointer = portal->next[1];
3496 portal->nodes[1] = NULL;
3499 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3503 if (t->nodes[0] == node)
3504 portalpointer = (void **) &t->next[0];
3505 else if (t->nodes[1] == node)
3506 portalpointer = (void **) &t->next[1];
3508 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3513 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3514 static double *portalpointsbuffer;
3515 static int portalpointsbufferoffset;
3516 static int portalpointsbuffersize;
3517 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3520 mnode_t *front, *back, *other_node;
3521 mplane_t clipplane, *plane;
3522 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3523 int numfrontpoints, numbackpoints;
3524 double *frontpoints, *backpoints;
3526 // if a leaf, we're done
3530 // get some space for our clipping operations to use
3531 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3533 portalpointsbuffersize = portalpointsbufferoffset * 2;
3534 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3536 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3537 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3538 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3539 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3541 plane = node->plane;
3543 front = node->children[0];
3544 back = node->children[1];
3546 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3548 // create the new portal by generating a polygon for the node plane,
3549 // and clipping it by all of the other portals(which came from nodes above this one)
3550 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3551 nodeportal->plane = *plane;
3553 // 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)
3554 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);
3555 nodeportal->numpoints = 4;
3556 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3557 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3559 clipplane = portal->plane;
3560 if (portal->nodes[0] == portal->nodes[1])
3561 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3562 if (portal->nodes[0] == node)
3564 else if (portal->nodes[1] == node)
3566 clipplane.dist = -clipplane.dist;
3567 VectorNegate(clipplane.normal, clipplane.normal);
3572 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3573 side = 0; // hush warning
3576 for (i = 0;i < nodeportal->numpoints*3;i++)
3577 frontpoints[i] = nodeportal->points[i];
3578 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);
3579 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3583 if (nodeportal->numpoints < 3)
3585 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3586 nodeportal->numpoints = 0;
3588 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3590 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3591 nodeportal->numpoints = 0;
3594 AddPortalToNodes(nodeportal, front, back);
3596 // split the portals of this node along this node's plane and assign them to the children of this node
3597 // (migrating the portals downward through the tree)
3598 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3600 if (portal->nodes[0] == portal->nodes[1])
3601 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3602 if (portal->nodes[0] == node)
3604 else if (portal->nodes[1] == node)
3608 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3609 side = 0; // hush warning
3611 nextportal = portal->next[side];
3612 if (!portal->numpoints)
3615 other_node = portal->nodes[!side];
3616 RemovePortalFromNodes(portal);
3618 // cut the portal into two portals, one on each side of the node plane
3619 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);
3621 if (!numfrontpoints)
3624 AddPortalToNodes(portal, back, other_node);
3626 AddPortalToNodes(portal, other_node, back);
3632 AddPortalToNodes(portal, front, other_node);
3634 AddPortalToNodes(portal, other_node, front);
3638 // the portal is split
3639 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3640 temp = splitportal->chain;
3641 *splitportal = *portal;
3642 splitportal->chain = temp;
3643 for (i = 0;i < numbackpoints*3;i++)
3644 splitportal->points[i] = backpoints[i];
3645 splitportal->numpoints = numbackpoints;
3646 for (i = 0;i < numfrontpoints*3;i++)
3647 portal->points[i] = frontpoints[i];
3648 portal->numpoints = numfrontpoints;
3652 AddPortalToNodes(portal, front, other_node);
3653 AddPortalToNodes(splitportal, back, other_node);
3657 AddPortalToNodes(portal, other_node, front);
3658 AddPortalToNodes(splitportal, other_node, back);
3662 Mod_Q1BSP_RecursiveNodePortals(front);
3663 Mod_Q1BSP_RecursiveNodePortals(back);
3665 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3668 static void Mod_Q1BSP_MakePortals(void)
3670 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3671 portalpointsbufferoffset = 0;
3672 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3673 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3674 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3675 Mem_Free(portalpointsbuffer);
3676 portalpointsbuffer = NULL;
3677 portalpointsbufferoffset = 0;
3678 portalpointsbuffersize = 0;
3679 Mod_Q1BSP_FinalizePortals();
3680 Mem_ExpandableArray_FreeArray(&portalarray);
3683 //Returns PVS data for a given point
3684 //(note: can return NULL)
3685 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3688 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3690 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3691 if (((mleaf_t *)node)->clusterindex >= 0)
3692 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3697 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)
3701 float d = PlaneDiff(org, node->plane);
3703 node = node->children[0];
3704 else if (d < -radius)
3705 node = node->children[1];
3708 // go down both sides
3709 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3710 node = node->children[1];
3713 // if this leaf is in a cluster, accumulate the pvs bits
3714 if (((mleaf_t *)node)->clusterindex >= 0)
3717 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3718 for (i = 0;i < pvsbytes;i++)
3719 pvsbuffer[i] |= pvs[i];
3723 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3724 //of the given point.
3725 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3727 int bytes = model->brush.num_pvsclusterbytes;
3728 bytes = min(bytes, pvsbufferlength);
3729 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3731 memset(pvsbuffer, 0xFF, bytes);
3735 memset(pvsbuffer, 0, bytes);
3736 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3740 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3745 VectorSubtract(inmaxs, inmins, size);
3746 if (cmodel->brush.ishlbsp)
3749 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3750 else if (size[0] <= 32)
3752 if (size[2] < 54) // pick the nearest of 36 or 72
3753 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3755 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3758 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3763 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3764 else if (size[0] <= 32)
3765 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3767 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3769 VectorCopy(inmins, outmins);
3770 VectorAdd(inmins, hull->clip_size, outmaxs);
3773 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3776 int numshadowmeshtriangles = 0;
3777 msurface_t *surface;
3778 if (cls.state == ca_dedicated)
3780 // make a single combined shadow mesh to allow optimized shadow volume creation
3782 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3784 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3785 numshadowmeshtriangles += surface->num_triangles;
3787 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3788 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3789 if (surface->num_triangles > 0)
3790 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));
3791 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3792 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3793 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3795 return numshadowmeshtriangles;
3798 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);
3800 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3803 sizebuf_t lumpsb[HEADER_LUMPS];
3805 float dist, modelyawradius, modelradius;
3806 msurface_t *surface;
3807 hullinfo_t hullinfo;
3808 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3809 model_brush_lightstyleinfo_t styleinfo[256];
3810 unsigned char *datapointer;
3813 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3815 mod->type = mod_brushq1;
3817 mod->brush.ishlbsp = false;
3818 mod->brush.isbsp2rmqe = false;
3819 mod->brush.isbsp2 = false;
3820 mod->brush.isq2bsp = false;
3821 mod->brush.isq3bsp = false;
3822 mod->brush.skymasking = true;
3823 i = MSG_ReadLittleLong(&sb);
3827 mod->modeldatatypestring = "Q1BSP";
3830 mod->brush.ishlbsp = true;
3831 mod->modeldatatypestring = "HLBSP";
3833 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3834 mod->brush.isbsp2 = true;
3835 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3836 mod->modeldatatypestring = "Q1BSP2rmqe";
3838 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3839 mod->brush.isbsp2 = true;
3840 mod->modeldatatypestring = "Q1BSP2";
3843 mod->modeldatatypestring = "Unknown BSP";
3844 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);
3848 // fill in hull info
3849 VectorClear (hullinfo.hullsizes[0][0]);
3850 VectorClear (hullinfo.hullsizes[0][1]);
3851 if (mod->brush.ishlbsp)
3853 hullinfo.filehulls = 4;
3854 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3855 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3856 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3857 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3858 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3859 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3863 hullinfo.filehulls = 4;
3864 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3865 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3866 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3867 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3871 for (i = 0; i < HEADER_LUMPS; i++)
3873 int offset = MSG_ReadLittleLong(&sb);
3874 int size = MSG_ReadLittleLong(&sb);
3875 if (offset < 0 || offset + size > sb.cursize)
3876 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);
3877 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3880 mod->soundfromcenter = true;
3881 mod->TraceBox = Mod_Q1BSP_TraceBox;
3882 mod->TraceLine = Mod_Q1BSP_TraceLine;
3883 mod->TracePoint = Mod_Q1BSP_TracePoint;
3884 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3885 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3886 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3887 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3888 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3889 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3890 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3891 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3892 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3893 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3894 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3895 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3896 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3897 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3898 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3899 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3900 mod->Draw = R_Q1BSP_Draw;
3901 mod->DrawDepth = R_Q1BSP_DrawDepth;
3902 mod->DrawDebug = R_Q1BSP_DrawDebug;
3903 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3904 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3905 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3906 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3907 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3908 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3909 mod->DrawLight = R_Q1BSP_DrawLight;
3913 mod->brush.qw_md4sum = 0;
3914 mod->brush.qw_md4sum2 = 0;
3915 for (i = 0;i < HEADER_LUMPS;i++)
3918 if (i == LUMP_ENTITIES)
3920 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3921 mod->brush.qw_md4sum ^= LittleLong(temp);
3922 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3924 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3927 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3928 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3929 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3930 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3931 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3932 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3933 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3934 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3935 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3936 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3937 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3938 // load submodels before leafs because they contain the number of vis leafs
3939 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3940 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3941 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3942 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3944 for (i = 0; i < HEADER_LUMPS; i++)
3945 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3946 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3948 // check if the map supports transparent water rendering
3949 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3951 // we don't need the compressed pvs data anymore
3952 if (mod->brushq1.data_compressedpvs)
3953 Mem_Free(mod->brushq1.data_compressedpvs);
3954 mod->brushq1.data_compressedpvs = NULL;
3955 mod->brushq1.num_compressedpvs = 0;
3957 Mod_Q1BSP_MakeHull0();
3958 if (mod_bsp_portalize.integer)
3959 Mod_Q1BSP_MakePortals();
3961 mod->numframes = 2; // regular and alternate animation
3964 // make a single combined shadow mesh to allow optimized shadow volume creation
3965 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3967 if (loadmodel->brush.numsubmodels)
3968 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3970 // LordHavoc: to clear the fog around the original quake submodel code, I
3972 // first of all, some background info on the submodels:
3973 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3974 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3975 // now the weird for loop itself:
3976 // the loop functions in an odd way, on each iteration it sets up the
3977 // current 'mod' model (which despite the confusing code IS the model of
3978 // the number i), at the end of the loop it duplicates the model to become
3979 // the next submodel, and loops back to set up the new submodel.
3981 // LordHavoc: now the explanation of my sane way (which works identically):
3982 // set up the world model, then on each submodel copy from the world model
3983 // and set up the submodel with the respective model info.
3984 totalstylesurfaces = 0;
3986 for (i = 0;i < mod->brush.numsubmodels;i++)
3988 memset(stylecounts, 0, sizeof(stylecounts));
3989 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3991 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3992 for (j = 0;j < MAXLIGHTMAPS;j++)
3993 stylecounts[surface->lightmapinfo->styles[j]]++;
3995 for (k = 0;k < 255;k++)
3999 totalstylesurfaces += stylecounts[k];
4002 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4003 for (i = 0;i < mod->brush.numsubmodels;i++)
4005 // LordHavoc: this code was originally at the end of this loop, but
4006 // has been transformed to something more readable at the start here.
4011 // duplicate the basic information
4012 dpsnprintf(name, sizeof(name), "*%i", i);
4013 mod = Mod_FindName(name, loadmodel->name);
4014 // copy the base model to this one
4016 // rename the clone back to its proper name
4017 strlcpy(mod->name, name, sizeof(mod->name));
4018 mod->brush.parentmodel = loadmodel;
4019 // textures and memory belong to the main model
4020 mod->texturepool = NULL;
4021 mod->mempool = NULL;
4022 mod->brush.GetPVS = NULL;
4023 mod->brush.FatPVS = NULL;
4024 mod->brush.BoxTouchingPVS = NULL;
4025 mod->brush.BoxTouchingLeafPVS = NULL;
4026 mod->brush.BoxTouchingVisibleLeafs = NULL;
4027 mod->brush.FindBoxClusters = NULL;
4028 mod->brush.LightPoint = NULL;
4029 mod->brush.AmbientSoundLevelsForPoint = NULL;
4032 mod->brush.submodel = i;
4034 if (loadmodel->brush.submodels)
4035 loadmodel->brush.submodels[i] = mod;
4037 bm = &mod->brushq1.submodels[i];
4039 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4040 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4042 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4043 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4046 mod->firstmodelsurface = bm->firstface;
4047 mod->nummodelsurfaces = bm->numfaces;
4049 // set node/leaf parents for this submodel
4050 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4052 // make the model surface list (used by shadowing/lighting)
4053 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4054 Mod_MakeSortedSurfaces(mod);
4056 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4057 // (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)
4058 VectorCopy(bm->mins, mod->normalmins);
4059 VectorCopy(bm->maxs, mod->normalmaxs);
4060 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4061 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4062 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4063 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4064 modelradius = modelyawradius + modelradius * modelradius;
4065 modelyawradius = sqrt(modelyawradius);
4066 modelradius = sqrt(modelradius);
4067 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4068 mod->yawmins[2] = mod->normalmins[2];
4069 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4070 mod->yawmaxs[2] = mod->normalmaxs[2];
4071 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4072 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4073 mod->radius = modelradius;
4074 mod->radius2 = modelradius * modelradius;
4076 // this gets altered below if sky or water is used
4077 mod->DrawSky = NULL;
4078 mod->DrawAddWaterPlanes = NULL;
4080 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4081 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4082 if (mod->nummodelsurfaces)
4084 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4085 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4087 if (j < mod->nummodelsurfaces)
4088 mod->DrawSky = R_Q1BSP_DrawSky;
4090 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4091 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4093 if (j < mod->nummodelsurfaces)
4094 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4096 // build lightstyle update chains
4097 // (used to rapidly mark lightmapupdateflags on many surfaces
4098 // when d_lightstylevalue changes)
4099 memset(stylecounts, 0, sizeof(stylecounts));
4100 for (k = 0;k < mod->nummodelsurfaces;k++)
4102 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4103 for (j = 0;j < MAXLIGHTMAPS;j++)
4104 stylecounts[surface->lightmapinfo->styles[j]]++;
4106 mod->brushq1.num_lightstyles = 0;
4107 for (k = 0;k < 255;k++)
4111 styleinfo[mod->brushq1.num_lightstyles].style = k;
4112 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4113 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4114 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4115 remapstyles[k] = mod->brushq1.num_lightstyles;
4116 mod->brushq1.num_lightstyles++;
4119 for (k = 0;k < mod->nummodelsurfaces;k++)
4121 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4122 for (j = 0;j < MAXLIGHTMAPS;j++)
4124 if (surface->lightmapinfo->styles[j] != 255)
4126 int r = remapstyles[surface->lightmapinfo->styles[j]];
4127 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4131 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4132 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4136 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4137 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4139 //mod->brushq1.num_visleafs = bm->visleafs;
4141 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4142 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4144 if (mod_q1bsp_polygoncollisions.integer)
4146 mod->collision_bih = mod->render_bih;
4147 // point traces and contents checks still use the bsp tree
4148 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4149 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4150 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4151 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4154 // generate VBOs and other shared data before cloning submodels
4158 Mod_Q1BSP_LoadMapBrushes();
4159 //Mod_Q1BSP_ProcessLightList();
4163 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);
4166 int Mod_Q2BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
4168 int supercontents = 0;
4169 if (nativecontents & CONTENTSQ2_SOLID)
4170 supercontents |= SUPERCONTENTS_SOLID;
4171 if (nativecontents & CONTENTSQ2_WATER)
4172 supercontents |= SUPERCONTENTS_WATER;
4173 if (nativecontents & CONTENTSQ2_SLIME)
4174 supercontents |= SUPERCONTENTS_SLIME;
4175 if (nativecontents & CONTENTSQ2_LAVA)
4176 supercontents |= SUPERCONTENTS_LAVA;
4177 if (nativecontents & CONTENTSQ2_MONSTER)
4178 supercontents |= SUPERCONTENTS_BODY;
4179 if (nativecontents & CONTENTSQ2_DEADMONSTER)
4180 supercontents |= SUPERCONTENTS_CORPSE;
4181 if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4182 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4183 if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4184 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4185 if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4186 supercontents |= SUPERCONTENTS_OPAQUE;
4187 return supercontents;
4190 int Mod_Q2BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
4192 int nativecontents = 0;
4193 if (supercontents & SUPERCONTENTS_SOLID)
4194 nativecontents |= CONTENTSQ2_SOLID;
4195 if (supercontents & SUPERCONTENTS_WATER)
4196 nativecontents |= CONTENTSQ2_WATER;
4197 if (supercontents & SUPERCONTENTS_SLIME)
4198 nativecontents |= CONTENTSQ2_SLIME;
4199 if (supercontents & SUPERCONTENTS_LAVA)
4200 nativecontents |= CONTENTSQ2_LAVA;
4201 if (supercontents & SUPERCONTENTS_BODY)
4202 nativecontents |= CONTENTSQ2_MONSTER;
4203 if (supercontents & SUPERCONTENTS_CORPSE)
4204 nativecontents |= CONTENTSQ2_DEADMONSTER;
4205 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4206 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4207 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4208 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4209 if (!(supercontents & SUPERCONTENTS_OPAQUE))
4210 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4211 return nativecontents;
4214 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4217 loadmodel->brushq1.num_compressedpvs = 0;
4218 loadmodel->brushq1.data_compressedpvs = NULL;
4219 loadmodel->brush.num_pvsclusters = 0;
4220 loadmodel->brush.num_pvsclusterbytes = 0;
4221 loadmodel->brush.data_pvsclusters = NULL;
4226 count = MSG_ReadLittleLong(sb);
4227 loadmodel->brush.num_pvsclusters = count;
4228 loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4229 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4230 for (i = 0;i < count;i++)
4232 int pvsofs = MSG_ReadLittleLong(sb);
4233 /*int phsofs = */MSG_ReadLittleLong(sb);
4234 // decompress the vis data for this cluster
4235 // (note this accesses the underlying data store of sb, which is kind of evil)
4236 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);
4238 // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4239 sb->readcount = sb->cursize;
4242 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4244 int i, j, count, p, child[2];
4246 int structsize = 28;
4248 if (sb->cursize % structsize)
4249 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4250 count = sb->cursize / structsize;
4252 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4253 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4255 loadmodel->brush.data_nodes = out;
4256 loadmodel->brush.num_nodes = count;
4258 for ( i=0 ; i<count ; i++, out++)
4260 p = MSG_ReadLittleLong(sb);
4261 out->plane = loadmodel->brush.data_planes + p;
4262 child[0] = MSG_ReadLittleLong(sb);
4263 child[1] = MSG_ReadLittleLong(sb);
4264 out->mins[0] = MSG_ReadLittleShort(sb);
4265 out->mins[1] = MSG_ReadLittleShort(sb);
4266 out->mins[2] = MSG_ReadLittleShort(sb);
4267 out->maxs[0] = MSG_ReadLittleShort(sb);
4268 out->maxs[1] = MSG_ReadLittleShort(sb);
4269 out->maxs[2] = MSG_ReadLittleShort(sb);
4270 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4271 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4272 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4274 Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4275 out->firstsurface = 0;
4276 out->numsurfaces = 0;
4278 for (j=0 ; j<2 ; j++)
4283 if (p < loadmodel->brush.num_nodes)
4284 out->children[j] = loadmodel->brush.data_nodes + p;
4287 Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4288 // map it to the solid leaf
4289 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4294 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4296 if (p < loadmodel->brush.num_leafs)
4297 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4300 Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4301 // map it to the solid leaf
4302 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4308 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
4311 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4315 int structsize = 76;
4316 int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4317 char filename[MAX_QPATH];
4319 if (sb->cursize % structsize)
4320 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4321 count = sb->cursize / structsize;
4322 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4323 loadmodel->brushq1.texinfo = out;
4324 loadmodel->brushq1.numtexinfo = count;
4325 loadmodel->num_texturesperskin = 0;
4326 loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4328 for (i = 0;i < count;i++, out++)
4331 for (k = 0;k < 2;k++)
4332 for (j = 0;j < 4;j++)
4333 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4335 out->q2flags = MSG_ReadLittleLong(sb);
4336 out->q2value = MSG_ReadLittleLong(sb);
4337 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4338 out->q2texture[31] = 0; // make absolutely sure it is terminated
4339 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4341 // find an existing match for the texture if possible
4342 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4343 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4344 if (!strcmp(filename, loadmodel->data_textures[j].name)
4345 && out->q2flags == loadmodel->data_textures[j].q2flags
4346 && out->q2value == loadmodel->data_textures[j].q2value)
4348 // if we don't find the texture, store the new texture
4349 if (j == loadmodel->num_texturesperskin)
4351 if (loadmodel->num_texturesperskin < maxtextures)
4353 texture_t *tx = loadmodel->data_textures + j;
4354 int q2flags = out->q2flags;
4355 unsigned char *walfile = NULL;
4356 fs_offset_t walfilesize = 0;
4357 Mod_LoadTextureFromQ3Shader(tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4358 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4359 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4363 LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4373 tx->q2flags = out->q2flags;
4374 tx->q2value = out->q2value;
4375 // also modify the texture to have the correct contents and such based on flags
4376 // note that we create multiple texture_t structures if q2flags differs
4377 if (q2flags & Q2SURF_LIGHT)
4379 // doesn't mean anything to us
4381 if (q2flags & Q2SURF_SLICK)
4383 // would be nice to support...
4385 if (q2flags & Q2SURF_SKY)
4387 // sky is a rather specific thing
4388 q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4389 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
4390 tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4391 tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4393 if (q2flags & Q2SURF_WARP)
4395 // we use a scroll instead of a warp
4396 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4397 // if it's also transparent, we can enable the WATERSHADER
4398 // but we do not set the WATERALPHA flag because we don't
4399 // want to honor r_wateralpha in q2bsp
4400 // (it would go against the artistic intent)
4401 if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4402 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4404 if (q2flags & Q2SURF_TRANS33)
4406 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4407 tx->basealpha = 1.0f / 3.0f;
4408 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4409 if (tx->q2contents & Q2CONTENTS_SOLID)
4410 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4412 if (q2flags & Q2SURF_TRANS66)
4414 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4415 tx->basealpha = 2.0f / 3.0f;
4416 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4417 if (tx->q2contents & Q2CONTENTS_SOLID)
4418 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4420 if ((q2flags & Q2SURF_FLOWING) && tx->materialshaderpass != NULL)
4422 tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4423 if (q2flags & Q2SURF_WARP)
4424 tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
4426 tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
4427 tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
4429 if (q2flags & Q2SURF_ALPHATEST)
4431 // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4432 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4434 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4436 if (!mod_q2bsp_littransparentsurfaces.integer)
4437 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4439 if (q2flags & Q2SURF_NODRAW)
4441 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4443 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4444 tx->q2contents |= Q2CONTENTS_DETAIL;
4445 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4446 tx->q2contents |= Q2CONTENTS_SOLID;
4447 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4449 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(loadmodel, tx->q2contents);
4450 // set the current values to the base values
4451 tx->currentframe = tx;
4452 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
4453 tx->currentmaterialflags = tx->basematerialflags;
4454 loadmodel->num_texturesperskin++;
4455 loadmodel->num_textures = loadmodel->num_texturesperskin;
4459 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4460 j = 0; // use first texture and give up
4463 // store the index we found for this texture
4464 out->textureindex = j;
4467 // realloc the textures array now that we know how many we actually need
4468 loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4470 // now assemble the texture chains
4471 // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier
4472 for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4475 texture_t *t = loadmodel->data_textures + out->textureindex;
4476 t->currentframe = t; // fix the reallocated pointer
4478 // if this is not animated, skip it
4479 // if this is already processed, skip it (part of an existing sequence)
4480 if (out->q2nexttexinfo == 0 || t->animated)
4483 // store the array of frames to use
4484 t->animated = 2; // q2bsp animation
4485 t->anim_total[0] = 0;
4486 t->anim_total[1] = 0;
4487 // gather up to 10 frames (we don't support more)
4488 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)
4490 // detect looping and stop there
4491 if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4493 t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4495 // we could look for the +a sequence here if this is the +0 sequence,
4496 // but it seems that quake2 did not implement that (even though the
4497 // files exist in the baseq2 content)
4499 // write the frame sequence to all the textures involved (just like
4500 // in the q1bsp loader)
4502 // note that this can overwrite the rest of the sequence - so if the
4503 // start of a sequence is found later than the other parts of the
4504 // sequence, it will go back and rewrite them correctly.
4505 for (k = 0;k < t->anim_total[0];k++)
4507 texture_t *txk = t->anim_frames[0][k];
4508 txk->animated = t->animated;
4509 txk->anim_total[0] = t->anim_total[0];
4510 for (l = 0;l < t->anim_total[0];l++)
4511 txk->anim_frames[0][l] = t->anim_frames[0][l];
4516 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4518 // LordHavoc: this fits exactly the same format that we use in .lit files
4519 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4520 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4523 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4526 int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4527 int structsize = 28;
4529 if (sb->cursize % structsize)
4530 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4531 count = sb->cursize / structsize;
4532 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4534 loadmodel->brush.data_leafs = out;
4535 loadmodel->brush.num_leafs = count;
4537 // FIXME: this function could really benefit from some error checking
4538 for ( i=0 ; i<count ; i++, out++)
4540 out->contents = MSG_ReadLittleLong(sb);
4541 out->clusterindex = MSG_ReadLittleShort(sb);
4542 out->areaindex = MSG_ReadLittleShort(sb);
4543 out->mins[0] = MSG_ReadLittleShort(sb);
4544 out->mins[1] = MSG_ReadLittleShort(sb);
4545 out->mins[2] = MSG_ReadLittleShort(sb);
4546 out->maxs[0] = MSG_ReadLittleShort(sb);
4547 out->maxs[1] = MSG_ReadLittleShort(sb);
4548 out->maxs[2] = MSG_ReadLittleShort(sb);
4550 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4551 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4552 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4553 nummarkbrushes = (unsigned short)MSG_ReadLittleShort(sb);
4555 for (j = 0;j < 4;j++)
4556 out->ambient_sound_level[j] = 0;
4558 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4560 Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4561 out->clusterindex = -1;
4564 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4566 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4567 out->numleafsurfaces = nummarksurfaces;
4571 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4572 out->firstleafsurface = NULL;
4573 out->numleafsurfaces = 0;
4576 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4578 out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4579 out->numleafbrushes = nummarkbrushes;
4583 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4584 out->firstleafbrush = NULL;
4585 out->numleafbrushes = 0;
4590 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4595 if (sb->cursize % structsize)
4596 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4597 loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4598 loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4600 for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4602 j = (unsigned short) MSG_ReadLittleShort(sb);
4603 if (j >= loadmodel->brush.num_brushes)
4604 Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4605 loadmodel->brush.data_leafbrushes[i] = j;
4609 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4611 q3mbrushside_t *out;
4615 if (sb->cursize % structsize)
4616 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4617 count = sb->cursize / structsize;
4618 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4620 loadmodel->brush.data_brushsides = out;
4621 loadmodel->brush.num_brushsides = count;
4623 for (i = 0;i < count;i++, out++)
4625 n = (unsigned short)MSG_ReadLittleShort(sb);
4626 if (n < 0 || n >= loadmodel->brush.num_planes)
4627 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4628 out->plane = loadmodel->brush.data_planes + n;
4629 n = MSG_ReadLittleShort(sb);
4632 if (n >= loadmodel->brushq1.numtexinfo)
4633 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4634 out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4638 //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4639 out->texture = &mod_q1bsp_texture_solid;
4644 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4647 int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4648 colplanef_t *planes;
4649 int structsize = 12;
4650 qboolean brushmissingtextures;
4651 int numbrushesmissingtextures = 0;
4652 int numcreatedtextures = 0;
4654 if (sb->cursize % structsize)
4655 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4656 count = sb->cursize / structsize;
4657 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4659 loadmodel->brush.data_brushes = out;
4660 loadmodel->brush.num_brushes = count;
4665 for (i = 0; i < count; i++, out++)
4667 firstside = MSG_ReadLittleLong(sb);
4668 numsides = MSG_ReadLittleLong(sb);
4669 contents = MSG_ReadLittleLong(sb);
4670 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4671 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4673 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4674 out->numbrushsides = numsides;
4675 // convert the contents to our values
4676 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(loadmodel, contents);
4678 // problem: q2bsp brushes have contents but not a texture
4679 // problem: q2bsp brushsides *may* have a texture or may not
4680 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4681 // solution: nasty hacks
4682 brushmissingtextures = false;
4683 out->texture = NULL;
4684 for (j = 0; j < out->numbrushsides; j++)
4686 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4687 brushmissingtextures = true;
4690 // if we can find a matching texture on a brush side we can use it instead of creating one
4691 if (out->firstbrushside[j].texture->supercontents == supercontents)
4692 out->texture = out->firstbrushside[j].texture;
4695 if (brushmissingtextures || out->texture == NULL)
4697 numbrushesmissingtextures++;
4698 // if we didn't find any appropriate texture (matching contents), we'll have to create one
4699 // we could search earlier ones for a matching one but that can be slow
4700 if (out->texture == NULL)
4702 texture_t *validtexture;
4703 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4704 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4705 validtexture->surfaceflags = 0;
4706 validtexture->supercontents = supercontents;
4707 numcreatedtextures++;
4708 out->texture = validtexture;
4710 // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4711 for (j = 0; j < out->numbrushsides; j++)
4712 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4713 out->firstbrushside[j].texture = out->texture;
4716 // make a colbrush from the brush
4718 // make a list of mplane_t structs to construct a colbrush from
4719 if (maxplanes < out->numbrushsides)
4721 maxplanes = out->numbrushsides;
4724 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4726 for (j = 0;j < out->numbrushsides;j++)
4728 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4729 planes[j].dist = out->firstbrushside[j].plane->dist;
4730 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4731 planes[j].texture = out->firstbrushside[j].texture;
4732 q3surfaceflags |= planes[j].q3surfaceflags;
4734 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4736 // this whole loop can take a while (e.g. on redstarrepublic4)
4737 CL_KeepaliveMessage(false);
4741 if (numcreatedtextures)
4742 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);
4745 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4747 // 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)
4748 sb->readcount = sb->cursize;
4751 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4753 // we currently don't use areas, they represent closable doors as vis blockers
4754 sb->readcount = sb->cursize;
4757 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4759 // we currently don't use areas, they represent closable doors as vis blockers
4760 sb->readcount = sb->cursize;
4763 static void Mod_Q2BSP_LoadSubmodels(sizebuf_t *sb)
4767 int structsize = 48;
4769 if (sb->cursize % structsize)
4770 Host_Error ("Mod_Q2BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
4772 count = sb->cursize / structsize;
4773 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
4775 loadmodel->brushq1.submodels = out;
4776 loadmodel->brush.numsubmodels = count;
4778 // this is identical to the q1 submodel structure except for having 1 hull
4779 for (i = 0; i < count; i++, out++)
4781 // spread out the mins / maxs by a pixel
4782 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
4783 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
4784 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
4785 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
4786 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
4787 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
4788 out->origin[0] = MSG_ReadLittleFloat(sb);
4789 out->origin[1] = MSG_ReadLittleFloat(sb);
4790 out->origin[2] = MSG_ReadLittleFloat(sb);
4791 out->headnode[0] = MSG_ReadLittleLong(sb);
4792 out->firstface = MSG_ReadLittleLong(sb);
4793 out->numfaces = MSG_ReadLittleLong(sb);
4797 static void Mod_Q2BSP_FindSubmodelBrushRange_r(dp_model_t *mod, mnode_t *node, int *first, int *last)
4803 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4804 node = node->children[1];
4806 leaf = (mleaf_t*)node;
4807 for (i = 0;i < leaf->numleafbrushes;i++)
4809 int brushnum = leaf->firstleafbrush[i];
4810 if (*first > brushnum)
4812 if (*last < brushnum)
4817 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4820 sizebuf_t lumpsb[Q2HEADER_LUMPS];
4822 float dist, modelyawradius, modelradius;
4823 msurface_t *surface;
4824 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4825 model_brush_lightstyleinfo_t styleinfo[256];
4826 unsigned char *datapointer;
4829 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4831 mod->type = mod_brushq2;
4833 mod->brush.ishlbsp = false;
4834 mod->brush.isbsp2rmqe = false;
4835 mod->brush.isbsp2 = false;
4836 mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4837 mod->brush.isq3bsp = false;
4838 mod->brush.skymasking = true;
4839 mod->modeldatatypestring = "Q2BSP";
4841 i = MSG_ReadLittleLong(&sb);
4842 if (i != Q2BSPMAGIC)
4843 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4845 i = MSG_ReadLittleLong(&sb);
4846 if (i != Q2BSPVERSION)
4847 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4850 for (i = 0; i < Q2HEADER_LUMPS; i++)
4852 int offset = MSG_ReadLittleLong(&sb);
4853 int size = MSG_ReadLittleLong(&sb);
4854 if (offset < 0 || offset + size > sb.cursize)
4855 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);
4856 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4859 mod->soundfromcenter = true;
4860 mod->TracePoint = Mod_CollisionBIH_TracePoint;
4861 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4862 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4863 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4864 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4865 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4866 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4867 mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4868 mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4869 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
4870 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
4871 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
4872 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
4873 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
4874 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
4875 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
4876 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
4877 mod->brush.AmbientSoundLevelsForPoint = NULL;
4878 mod->brush.RoundUpToHullSize = NULL;
4879 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
4880 mod->Draw = R_Q1BSP_Draw;
4881 mod->DrawDepth = R_Q1BSP_DrawDepth;
4882 mod->DrawDebug = R_Q1BSP_DrawDebug;
4883 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
4884 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
4885 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
4886 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
4887 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
4888 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
4889 mod->DrawLight = R_Q1BSP_DrawLight;
4893 mod->brush.qw_md4sum = 0;
4894 mod->brush.qw_md4sum2 = 0;
4895 for (i = 0;i < Q2HEADER_LUMPS;i++)
4898 if (i == Q2LUMP_ENTITIES)
4900 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4901 mod->brush.qw_md4sum ^= LittleLong(temp);
4902 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4904 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4907 // many of these functions are identical to Q1 loaders, so we use those where possible
4908 Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4909 Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4910 Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4911 Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4912 Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4913 Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4914 Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4915 Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4916 Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4917 Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4918 Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4919 Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4920 Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4921 Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4922 Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4923 Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4924 Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4925 Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4926 Mod_Q2BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS]);
4928 for (i = 0; i < Q2HEADER_LUMPS; i++)
4929 if (lumpsb[i].readcount != lumpsb[i].cursize)
4930 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4932 // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4933 // doesn't enable the cvar, just indicates that transparent water is OK
4934 loadmodel->brush.supportwateralpha = true;
4936 // we don't need the compressed pvs data anymore
4937 if (mod->brushq1.data_compressedpvs)
4938 Mem_Free(mod->brushq1.data_compressedpvs);
4939 mod->brushq1.data_compressedpvs = NULL;
4940 mod->brushq1.num_compressedpvs = 0;
4942 // the MakePortals code works fine on the q2bsp data as well
4943 if (mod_bsp_portalize.integer)
4944 Mod_Q1BSP_MakePortals();
4946 mod->numframes = 0; // q2bsp animations are kind of special, frame is unbounded...
4949 // make a single combined shadow mesh to allow optimized shadow volume creation
4950 Mod_Q1BSP_CreateShadowMesh(loadmodel);
4952 if (loadmodel->brush.numsubmodels)
4953 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
4955 totalstylesurfaces = 0;
4957 for (i = 0;i < mod->brush.numsubmodels;i++)
4959 memset(stylecounts, 0, sizeof(stylecounts));
4960 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4962 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4963 for (j = 0;j < MAXLIGHTMAPS;j++)
4964 stylecounts[surface->lightmapinfo->styles[j]]++;
4966 for (k = 0;k < 255;k++)
4970 totalstylesurfaces += stylecounts[k];
4973 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4974 // set up the world model, then on each submodel copy from the world model
4975 // and set up the submodel with the respective model info.
4977 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
4979 mnode_t *rootnode = NULL;
4980 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
4984 // duplicate the basic information
4985 dpsnprintf(name, sizeof(name), "*%i", i);
4986 mod = Mod_FindName(name, loadmodel->name);
4987 // copy the base model to this one
4989 // rename the clone back to its proper name
4990 strlcpy(mod->name, name, sizeof(mod->name));
4991 mod->brush.parentmodel = loadmodel;
4992 // textures and memory belong to the main model
4993 mod->texturepool = NULL;
4994 mod->mempool = NULL;
4995 mod->brush.GetPVS = NULL;
4996 mod->brush.FatPVS = NULL;
4997 mod->brush.BoxTouchingPVS = NULL;
4998 mod->brush.BoxTouchingLeafPVS = NULL;
4999 mod->brush.BoxTouchingVisibleLeafs = NULL;
5000 mod->brush.FindBoxClusters = NULL;
5001 mod->brush.LightPoint = NULL;
5002 mod->brush.AmbientSoundLevelsForPoint = NULL;
5004 mod->brush.submodel = i;
5005 if (loadmodel->brush.submodels)
5006 loadmodel->brush.submodels[i] = mod;
5008 bm = &mod->brushq1.submodels[i];
5010 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5011 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5013 mod->firstmodelsurface = bm->firstface;
5014 mod->nummodelsurfaces = bm->numfaces;
5016 // set node/leaf parents for this submodel
5017 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5018 // (this happens in base3.bsp)
5019 if (bm->headnode[0] >= 0)
5020 rootnode = mod->brush.data_nodes + bm->headnode[0];
5022 rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5023 Mod_Q1BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5025 // make the model surface list (used by shadowing/lighting)
5026 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
5027 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5028 if (firstbrush <= lastbrush)
5030 mod->firstmodelbrush = firstbrush;
5031 mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5035 mod->firstmodelbrush = 0;
5036 mod->nummodelbrushes = 0;
5038 Mod_MakeSortedSurfaces(mod);
5040 VectorCopy(bm->mins, mod->normalmins);
5041 VectorCopy(bm->maxs, mod->normalmaxs);
5042 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5043 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5044 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5045 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5046 modelradius = modelyawradius + modelradius * modelradius;
5047 modelyawradius = sqrt(modelyawradius);
5048 modelradius = sqrt(modelradius);
5049 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5050 mod->yawmins[2] = mod->normalmins[2];
5051 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
5052 mod->yawmaxs[2] = mod->normalmaxs[2];
5053 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5054 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5055 mod->radius = modelradius;
5056 mod->radius2 = modelradius * modelradius;
5058 // this gets altered below if sky or water is used
5059 mod->DrawSky = NULL;
5060 mod->DrawAddWaterPlanes = NULL;
5062 // scan surfaces for sky and water and flag the submodel as possessing these features or not
5063 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5064 if (mod->nummodelsurfaces)
5066 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5067 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
5069 if (j < mod->nummodelsurfaces)
5070 mod->DrawSky = R_Q1BSP_DrawSky;
5072 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5073 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
5075 if (j < mod->nummodelsurfaces)
5076 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
5078 // build lightstyle update chains
5079 // (used to rapidly mark lightmapupdateflags on many surfaces
5080 // when d_lightstylevalue changes)
5081 memset(stylecounts, 0, sizeof(stylecounts));
5082 for (k = 0;k < mod->nummodelsurfaces;k++)
5084 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5085 for (j = 0;j < MAXLIGHTMAPS;j++)
5086 stylecounts[surface->lightmapinfo->styles[j]]++;
5088 mod->brushq1.num_lightstyles = 0;
5089 for (k = 0;k < 255;k++)
5093 styleinfo[mod->brushq1.num_lightstyles].style = k;
5094 styleinfo[mod->brushq1.num_lightstyles].value = 0;
5095 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5096 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
5097 remapstyles[k] = mod->brushq1.num_lightstyles;
5098 mod->brushq1.num_lightstyles++;
5101 for (k = 0;k < mod->nummodelsurfaces;k++)
5103 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5104 for (j = 0;j < MAXLIGHTMAPS;j++)
5106 if (surface->lightmapinfo->styles[j] != 255)
5108 int r = remapstyles[surface->lightmapinfo->styles[j]];
5109 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
5113 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
5114 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5118 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5120 //mod->brushq1.num_visleafs = bm->visleafs;
5122 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5123 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5125 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5126 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5128 // generate VBOs and other shared data before cloning submodels
5134 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);
5137 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
5138 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
5140 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5143 char key[128], value[MAX_INPUTLINE];
5145 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5146 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5147 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5150 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5151 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5152 loadmodel->brush.entities[l->filelen] = 0;
5153 data = loadmodel->brush.entities;
5154 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5155 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5156 loadmodel->brushq3.deluxemapping = false;
5157 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5161 if (!COM_ParseToken_Simple(&data, false, false, true))
5163 if (com_token[0] == '}')
5164 break; // end of worldspawn
5165 if (com_token[0] == '_')
5166 strlcpy(key, com_token + 1, sizeof(key));
5168 strlcpy(key, com_token, sizeof(key));
5169 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5170 key[strlen(key)-1] = 0;
5171 if (!COM_ParseToken_Simple(&data, false, false, true))
5173 strlcpy(value, com_token, sizeof(value));
5174 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5176 #if _MSC_VER >= 1400
5177 #define sscanf sscanf_s
5180 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5181 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5183 VectorSet(v, 64, 64, 128);
5184 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5185 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]);
5186 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5187 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5190 else if (!strcmp("deluxeMaps", key))
5192 if (!strcmp(com_token, "1"))
5194 loadmodel->brushq3.deluxemapping = true;
5195 loadmodel->brushq3.deluxemapping_modelspace = true;
5197 else if (!strcmp(com_token, "2"))
5199 loadmodel->brushq3.deluxemapping = true;
5200 loadmodel->brushq3.deluxemapping_modelspace = false;
5207 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5213 in = (q3dtexture_t *)(mod_base + l->fileofs);
5214 if (l->filelen % sizeof(*in))
5215 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5216 count = l->filelen / sizeof(*in);
5217 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5219 loadmodel->data_textures = out;
5220 loadmodel->num_textures = count;
5221 loadmodel->num_texturesperskin = loadmodel->num_textures;
5223 for (i = 0;i < count;i++)
5225 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5226 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
5227 Mod_LoadTextureFromQ3Shader(out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
5228 // restore the surfaceflags and supercontents
5229 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5230 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
5234 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5240 in = (q3dplane_t *)(mod_base + l->fileofs);
5241 if (l->filelen % sizeof(*in))
5242 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5243 count = l->filelen / sizeof(*in);
5244 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5246 loadmodel->brush.data_planes = out;
5247 loadmodel->brush.num_planes = count;
5249 for (i = 0;i < count;i++, in++, out++)
5251 out->normal[0] = LittleFloat(in->normal[0]);
5252 out->normal[1] = LittleFloat(in->normal[1]);
5253 out->normal[2] = LittleFloat(in->normal[2]);
5254 out->dist = LittleFloat(in->dist);
5259 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5262 q3mbrushside_t *out;
5265 in = (q3dbrushside_t *)(mod_base + l->fileofs);
5266 if (l->filelen % sizeof(*in))
5267 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5268 count = l->filelen / sizeof(*in);
5269 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5271 loadmodel->brush.data_brushsides = out;
5272 loadmodel->brush.num_brushsides = count;
5274 for (i = 0;i < count;i++, in++, out++)
5276 n = LittleLong(in->planeindex);
5277 if (n < 0 || n >= loadmodel->brush.num_planes)
5278 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5279 out->plane = loadmodel->brush.data_planes + n;
5280 n = LittleLong(in->textureindex);
5281 if (n < 0 || n >= loadmodel->num_textures)
5282 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5283 out->texture = loadmodel->data_textures + n;
5287 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5289 q3dbrushside_ig_t *in;
5290 q3mbrushside_t *out;
5293 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5294 if (l->filelen % sizeof(*in))
5295 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5296 count = l->filelen / sizeof(*in);
5297 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5299 loadmodel->brush.data_brushsides = out;
5300 loadmodel->brush.num_brushsides = count;
5302 for (i = 0;i < count;i++, in++, out++)
5304 n = LittleLong(in->planeindex);
5305 if (n < 0 || n >= loadmodel->brush.num_planes)
5306 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5307 out->plane = loadmodel->brush.data_planes + n;
5308 n = LittleLong(in->textureindex);
5309 if (n < 0 || n >= loadmodel->num_textures)
5310 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5311 out->texture = loadmodel->data_textures + n;
5315 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5319 int i, j, n, c, count, maxplanes, q3surfaceflags;
5320 colplanef_t *planes;
5322 in = (q3dbrush_t *)(mod_base + l->fileofs);
5323 if (l->filelen % sizeof(*in))
5324 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5325 count = l->filelen / sizeof(*in);
5326 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5328 loadmodel->brush.data_brushes = out;
5329 loadmodel->brush.num_brushes = count;
5334 for (i = 0;i < count;i++, in++, out++)
5336 n = LittleLong(in->firstbrushside);
5337 c = LittleLong(in->numbrushsides);
5338 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5339 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5340 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5341 out->numbrushsides = c;
5342 n = LittleLong(in->textureindex);
5343 if (n < 0 || n >= loadmodel->num_textures)
5344 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5345 out->texture = loadmodel->data_textures + n;
5347 // make a list of mplane_t structs to construct a colbrush from
5348 if (maxplanes < out->numbrushsides)
5350 maxplanes = out->numbrushsides;
5353 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5356 for (j = 0;j < out->numbrushsides;j++)
5358 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5359 planes[j].dist = out->firstbrushside[j].plane->dist;
5360 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5361 planes[j].texture = out->firstbrushside[j].texture;
5362 q3surfaceflags |= planes[j].q3surfaceflags;
5364 // make the colbrush from the planes
5365 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5367 // this whole loop can take a while (e.g. on redstarrepublic4)
5368 CL_KeepaliveMessage(false);
5374 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5380 in = (q3deffect_t *)(mod_base + l->fileofs);
5381 if (l->filelen % sizeof(*in))
5382 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5383 count = l->filelen / sizeof(*in);
5384 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5386 loadmodel->brushq3.data_effects = out;
5387 loadmodel->brushq3.num_effects = count;
5389 for (i = 0;i < count;i++, in++, out++)
5391 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5392 n = LittleLong(in->brushindex);
5393 if (n >= loadmodel->brush.num_brushes)
5395 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5398 out->brushindex = n;
5399 out->unknown = LittleLong(in->unknown);
5403 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5408 in = (q3dvertex_t *)(mod_base + l->fileofs);
5409 if (l->filelen % sizeof(*in))
5410 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5411 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5412 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5413 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5414 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5415 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5416 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5418 for (i = 0;i < count;i++, in++)
5420 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5421 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5422 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5423 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5424 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5425 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5426 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5427 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5428 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5429 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5430 // svector/tvector are calculated later in face loading
5431 if(mod_q3bsp_sRGBlightmaps.integer)
5433 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5434 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5435 // working like this may be odd, but matches q3map2 -gamma 2.2
5436 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5438 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5439 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5440 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5441 // we fix the brightness consistently via lightmapscale
5445 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5446 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5447 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5452 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5454 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5455 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5456 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5460 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5461 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5462 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5465 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5466 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5467 loadmodel->lit = true;
5471 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5477 in = (int *)(mod_base + l->fileofs);
5478 if (l->filelen % sizeof(int[3]))
5479 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5480 count = l->filelen / sizeof(*in);
5482 if(!loadmodel->brushq3.num_vertices)
5485 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5486 loadmodel->brushq3.num_triangles = 0;
5490 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5491 loadmodel->brushq3.num_triangles = count / 3;
5492 loadmodel->brushq3.data_element3i = out;
5494 for (i = 0;i < count;i++, in++, out++)
5496 *out = LittleLong(*in);
5497 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5499 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5505 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5507 q3dlightmap_t *input_pointer;
5525 int mergedrowsxcolumns;
5530 unsigned char *mergedpixels;
5531 unsigned char *mergeddeluxepixels;
5532 unsigned char *mergebuf;
5533 char mapname[MAX_QPATH];
5535 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5538 // defaults for q3bsp
5545 loadmodel->brushq3.lightmapsize = 128;
5547 if (cls.state == ca_dedicated)
5550 if(mod_q3bsp_nolightmaps.integer)
5556 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5557 if (developer_loading.integer)
5558 Con_Printf("Using internal lightmaps\n");
5559 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5560 if (l->filelen % sizeof(*input_pointer))
5561 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5562 count = l->filelen / sizeof(*input_pointer);
5563 for(i = 0; i < count; ++i)
5564 inpixels[i] = input_pointer[i].rgb;
5568 // no internal lightmaps
5569 // try external lightmaps
5570 if (developer_loading.integer)
5571 Con_Printf("Using external lightmaps\n");
5572 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5573 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5577 // using EXTERNAL lightmaps instead
5578 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5580 Mem_Free(inpixels[0]);
5581 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5591 for(count = 1; ; ++count)
5593 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5594 if(!inpixels[count])
5595 break; // we got all of them
5596 if(image_width != size || image_height != size)
5598 Mem_Free(inpixels[count]);
5599 inpixels[count] = NULL;
5600 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);
5606 loadmodel->brushq3.lightmapsize = size;
5607 loadmodel->brushq3.num_originallightmaps = count;
5609 // now check the surfaces to see if any of them index an odd numbered
5610 // lightmap, if so this is not a deluxemapped bsp file
5612 // also check what lightmaps are actually used, because q3map2 sometimes
5613 // (always?) makes an unused one at the end, which
5614 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5615 // reason when only one lightmap is used, which can throw off the
5616 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5617 // to see if the second lightmap is blank, if so it is not deluxemapped.
5618 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5619 // in Mod_Q3BSP_LoadEntities was failed
5620 if (!loadmodel->brushq3.deluxemapping)
5622 loadmodel->brushq3.deluxemapping = !(count & 1);
5623 loadmodel->brushq3.deluxemapping_modelspace = true;
5625 if (loadmodel->brushq3.deluxemapping)
5627 int facecount = faceslump->filelen / sizeof(q3dface_t);
5628 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5629 for (i = 0;i < facecount;i++)
5631 j = LittleLong(faces[i].lightmapindex);
5634 endlightmap = max(endlightmap, j + 1);
5635 if ((j & 1) || j + 1 >= count)
5637 loadmodel->brushq3.deluxemapping = false;
5644 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5645 // reason when only one lightmap is used, which can throw off the
5646 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5647 // to see if the second lightmap is blank, if so it is not deluxemapped.
5649 // further research has shown q3map2 sometimes creates a deluxemap and two
5650 // blank lightmaps, which must be handled properly as well
5651 if (endlightmap == 1 && count > 1)
5654 for (i = 0;i < size*size;i++)
5656 if (c[bytesperpixel*i + rgbmap[0]])
5658 if (c[bytesperpixel*i + rgbmap[1]])
5660 if (c[bytesperpixel*i + rgbmap[2]])
5665 // all pixels in the unused lightmap were black...
5666 loadmodel->brushq3.deluxemapping = false;
5671 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5673 // figure out what the most reasonable merge power is within limits
5675 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5676 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5678 // figure out how big the merged texture has to be
5679 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5680 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5681 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5683 mergedwidth = mergegoal;
5684 mergedheight = mergegoal;
5685 // choose non-square size (2x1 aspect) if only half the space is used;
5686 // this really only happens when the entire set fits in one texture, if
5687 // there are multiple textures, we don't worry about shrinking the last
5688 // one to fit, because the driver prefers the same texture size on
5689 // consecutive draw calls...
5690 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5693 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5694 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5695 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5696 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5697 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5698 loadmodel->brushq3.num_lightmapmergedheightpower++;
5699 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5701 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5702 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5703 powerxy = powerx+powery;
5704 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5706 mergedcolumns = 1 << powerx;
5707 mergedrows = 1 << powery;
5708 mergedrowsxcolumns = 1 << powerxy;
5710 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5711 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5712 if (loadmodel->brushq3.deluxemapping)
5713 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5715 // allocate a texture pool if we need it
5716 if (loadmodel->texturepool == NULL)
5717 loadmodel->texturepool = R_AllocTexturePool();
5719 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5720 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5721 for (i = 0;i < count;i++)
5723 // figure out which merged lightmap texture this fits into
5724 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5725 lightmapindex = i >> powerdxy;
5727 // choose the destination address
5728 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5729 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5730 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5731 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);
5733 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5734 for (j = 0;j < size;j++)
5735 for (k = 0;k < size;k++)
5737 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5738 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5739 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5740 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5743 // upload texture if this was the last tile being written to the texture
5744 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5746 if (loadmodel->brushq3.deluxemapping && (i & 1))
5747 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);
5750 if(mod_q3bsp_sRGBlightmaps.integer)
5753 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5755 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5756 // we fix the brightness consistently via lightmapscale
5759 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5760 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);
5764 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5765 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5766 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);
5772 if (mergeddeluxepixels)
5773 Mem_Free(mergeddeluxepixels);
5774 Mem_Free(mergedpixels);
5777 for(i = 0; i < count; ++i)
5778 Mem_Free(inpixels[i]);
5782 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5787 *collisionstride = stride;
5790 cnt = (num_triangles + stride - 1) / stride;
5791 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5792 for(j = 0; j < cnt; ++j)
5794 mins = &((*collisionbbox6f)[6 * j + 0]);
5795 maxs = &((*collisionbbox6f)[6 * j + 3]);
5796 for(k = 0; k < stride; ++k)
5798 tri = j * stride + k;
5799 if(tri >= num_triangles)
5801 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5802 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5803 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5804 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5805 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5806 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5807 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5808 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5809 if(vert[0] < mins[0]) mins[0] = vert[0];
5810 if(vert[1] < mins[1]) mins[1] = vert[1];
5811 if(vert[2] < mins[2]) mins[2] = vert[2];
5812 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5813 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5814 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5815 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5816 if(vert[0] < mins[0]) mins[0] = vert[0];
5817 if(vert[1] < mins[1]) mins[1] = vert[1];
5818 if(vert[2] < mins[2]) mins[2] = vert[2];
5819 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5820 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5821 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5826 *collisionbbox6f = NULL;
5829 typedef struct patchtess_s
5833 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5836 float *originalvertex3f;
5839 #define PATCHTESS_SAME_LODGROUP(a,b) \
5841 (a).lodgroup[0] == (b).lodgroup[0] && \
5842 (a).lodgroup[1] == (b).lodgroup[1] && \
5843 (a).lodgroup[2] == (b).lodgroup[2] && \
5844 (a).lodgroup[3] == (b).lodgroup[3] && \
5845 (a).lodgroup[4] == (b).lodgroup[4] && \
5846 (a).lodgroup[5] == (b).lodgroup[5] \
5849 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5851 q3dface_t *in, *oldin;
5852 msurface_t *out, *oldout;
5853 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;
5854 float lightmaptcbase[2], lightmaptcscale[2];
5855 //int *originalelement3i;
5856 //int *originalneighbor3i;
5857 float *originalvertex3f;
5858 //float *originalsvector3f;
5859 //float *originaltvector3f;
5860 float *originalnormal3f;
5861 float *originalcolor4f;
5862 float *originaltexcoordtexture2f;
5863 float *originaltexcoordlightmap2f;
5864 float *surfacecollisionvertex3f;
5865 int *surfacecollisionelement3i;
5867 patchtess_t *patchtess = NULL;
5868 int patchtesscount = 0;
5871 in = (q3dface_t *)(mod_base + l->fileofs);
5872 if (l->filelen % sizeof(*in))
5873 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5874 count = l->filelen / sizeof(*in);
5875 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5877 loadmodel->data_surfaces = out;
5878 loadmodel->num_surfaces = count;
5881 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5889 for (;i < count;i++, in++, out++)
5891 // check face type first
5892 type = LittleLong(in->type);
5893 if (type != Q3FACETYPE_FLAT
5894 && type != Q3FACETYPE_PATCH
5895 && type != Q3FACETYPE_MESH
5896 && type != Q3FACETYPE_FLARE)
5898 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5902 n = LittleLong(in->textureindex);
5903 if (n < 0 || n >= loadmodel->num_textures)
5905 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5908 out->texture = loadmodel->data_textures + n;
5909 n = LittleLong(in->effectindex);
5910 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5912 if (developer_extra.integer)
5913 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5919 out->effect = loadmodel->brushq3.data_effects + n;
5921 if (cls.state != ca_dedicated)
5923 out->lightmaptexture = NULL;
5924 out->deluxemaptexture = r_texture_blanknormalmap;
5925 n = LittleLong(in->lightmapindex);
5928 else if (n >= loadmodel->brushq3.num_originallightmaps)
5930 if(loadmodel->brushq3.num_originallightmaps != 0)
5931 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5936 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5937 if (loadmodel->brushq3.deluxemapping)
5938 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5939 loadmodel->lit = true;
5943 firstvertex = LittleLong(in->firstvertex);
5944 numvertices = LittleLong(in->numvertices);
5945 firstelement = LittleLong(in->firstelement);
5946 numtriangles = LittleLong(in->numelements) / 3;
5947 if (numtriangles * 3 != LittleLong(in->numelements))
5949 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));
5952 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5954 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);
5957 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5959 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);
5964 case Q3FACETYPE_FLAT:
5965 case Q3FACETYPE_MESH:
5966 // no processing necessary
5968 case Q3FACETYPE_PATCH:
5969 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5970 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5971 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))
5973 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5976 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5978 // convert patch to Q3FACETYPE_MESH
5979 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5980 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5981 // bound to user settings
5982 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5983 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5984 // bound to sanity settings
5985 xtess = bound(0, xtess, 1024);
5986 ytess = bound(0, ytess, 1024);
5988 // lower quality collision patches! Same procedure as before, but different cvars
5989 // convert patch to Q3FACETYPE_MESH
5990 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5991 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5992 // bound to user settings
5993 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5994 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5995 // bound to sanity settings
5996 cxtess = bound(0, cxtess, 1024);
5997 cytess = bound(0, cytess, 1024);
5999 // store it for the LOD grouping step
6000 patchtess[patchtesscount].info.xsize = patchsize[0];
6001 patchtess[patchtesscount].info.ysize = patchsize[1];
6002 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
6003 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
6004 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
6005 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
6007 patchtess[patchtesscount].surface_id = i;
6008 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
6009 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
6010 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
6011 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
6012 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
6013 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
6014 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
6017 case Q3FACETYPE_FLARE:
6018 if (developer_extra.integer)
6019 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
6023 out->num_vertices = numvertices;
6024 out->num_triangles = numtriangles;
6025 meshvertices += out->num_vertices;
6026 meshtriangles += out->num_triangles;
6029 // Fix patches tesselations so that they make no seams
6033 for(i = 0; i < patchtesscount; ++i)
6035 for(j = i+1; j < patchtesscount; ++j)
6037 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
6040 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
6047 // Calculate resulting number of triangles
6048 collisionvertices = 0;
6049 collisiontriangles = 0;
6050 for(i = 0; i < patchtesscount; ++i)
6052 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
6053 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
6054 numvertices = finalwidth * finalheight;
6055 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6057 oldout[patchtess[i].surface_id].num_vertices = numvertices;
6058 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
6059 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
6060 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
6062 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
6063 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
6064 numvertices = finalwidth * finalheight;
6065 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6067 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
6068 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
6069 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
6070 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
6076 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
6077 if (collisiontriangles)
6079 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6080 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6084 collisionvertices = 0;
6085 collisiontriangles = 0;
6086 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6088 if (out->num_vertices < 3 || out->num_triangles < 1)
6091 type = LittleLong(in->type);
6092 firstvertex = LittleLong(in->firstvertex);
6093 firstelement = LittleLong(in->firstelement);
6094 out->num_firstvertex = meshvertices;
6095 out->num_firsttriangle = meshtriangles;
6096 out->num_firstcollisiontriangle = collisiontriangles;
6099 case Q3FACETYPE_FLAT:
6100 case Q3FACETYPE_MESH:
6101 // no processing necessary, except for lightmap merging
6102 for (j = 0;j < out->num_vertices;j++)
6104 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6105 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6106 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6107 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6108 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6109 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6110 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6111 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6112 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6113 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6114 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6115 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6116 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6117 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6119 for (j = 0;j < out->num_triangles*3;j++)
6120 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6122 case Q3FACETYPE_PATCH:
6123 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6124 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6125 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6126 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6127 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6128 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6129 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6131 xtess = ytess = cxtess = cytess = -1;
6132 for(j = 0; j < patchtesscount; ++j)
6133 if(patchtess[j].surface_id == i)
6135 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6136 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6137 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6138 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6143 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
6144 xtess = ytess = cxtess = cytess = 0;
6147 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6148 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6149 finalvertices = finalwidth * finalheight;
6150 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6151 type = Q3FACETYPE_MESH;
6152 // generate geometry
6153 // (note: normals are skipped because they get recalculated)
6154 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6155 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6156 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6157 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6158 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6159 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6161 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);
6163 if (developer_extra.integer)
6165 if (out->num_triangles < finaltriangles)
6166 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);
6168 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);
6170 // q3map does not put in collision brushes for curves... ugh
6171 // build the lower quality collision geometry
6172 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6173 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6174 finalvertices = finalwidth * finalheight;
6175 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6177 // legacy collision geometry implementation
6178 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
6179 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
6180 out->num_collisionvertices = finalvertices;
6181 out->num_collisiontriangles = finaltriangles;
6182 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6183 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
6185 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
6186 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
6188 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
6190 // now optimize the collision mesh by finding triangle bboxes...
6191 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
6192 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);
6194 // store collision geometry for BIH collision tree
6195 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6196 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6197 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6198 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6199 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6201 // remove this once the legacy code is removed
6203 int nc = out->num_collisiontriangles;
6205 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6207 if(nc != out->num_collisiontriangles)
6209 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
6214 if (developer_extra.integer)
6215 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);
6217 collisionvertices += finalvertices;
6218 collisiontriangles += out->num_collisiontriangles;
6223 meshvertices += out->num_vertices;
6224 meshtriangles += out->num_triangles;
6225 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6226 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)
6228 if (invalidelements)
6230 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);
6231 for (j = 0;j < out->num_triangles * 3;j++)
6233 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6234 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)
6235 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6239 // calculate a bounding box
6240 VectorClear(out->mins);
6241 VectorClear(out->maxs);
6242 if (out->num_vertices)
6244 if (cls.state != ca_dedicated && out->lightmaptexture)
6246 // figure out which part of the merged lightmap this fits into
6247 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6248 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6249 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6250 lightmapindex &= mergewidth * mergeheight - 1;
6251 lightmaptcscale[0] = 1.0f / mergewidth;
6252 lightmaptcscale[1] = 1.0f / mergeheight;
6253 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6254 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6255 // modify the lightmap texcoords to match this region of the merged lightmap
6256 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6258 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6259 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6262 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6263 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6264 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6266 out->mins[0] = min(out->mins[0], v[0]);
6267 out->maxs[0] = max(out->maxs[0], v[0]);
6268 out->mins[1] = min(out->mins[1], v[1]);
6269 out->maxs[1] = max(out->maxs[1], v[1]);
6270 out->mins[2] = min(out->mins[2], v[2]);
6271 out->maxs[2] = max(out->maxs[2], v[2]);
6273 out->mins[0] -= 1.0f;
6274 out->mins[1] -= 1.0f;
6275 out->mins[2] -= 1.0f;
6276 out->maxs[0] += 1.0f;
6277 out->maxs[1] += 1.0f;
6278 out->maxs[2] += 1.0f;
6280 // set lightmap styles for consistency with q1bsp
6281 //out->lightmapinfo->styles[0] = 0;
6282 //out->lightmapinfo->styles[1] = 255;
6283 //out->lightmapinfo->styles[2] = 255;
6284 //out->lightmapinfo->styles[3] = 255;
6289 for (;i < count;i++, out++)
6291 if(out->num_vertices && out->num_triangles)
6293 if(out->num_vertices == 0)
6295 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6296 if(out->num_triangles == 0)
6297 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6299 else if(out->num_triangles == 0)
6300 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)",
6301 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6302 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6303 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6306 // for per pixel lighting
6307 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);
6309 // generate ushort elements array if possible
6310 if (loadmodel->surfmesh.data_element3s)
6311 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6312 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6314 // free the no longer needed vertex data
6315 loadmodel->brushq3.num_vertices = 0;
6316 if (loadmodel->brushq3.data_vertex3f)
6317 Mem_Free(loadmodel->brushq3.data_vertex3f);
6318 loadmodel->brushq3.data_vertex3f = NULL;
6319 loadmodel->brushq3.data_normal3f = NULL;
6320 loadmodel->brushq3.data_texcoordtexture2f = NULL;
6321 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6322 loadmodel->brushq3.data_color4f = NULL;
6323 // free the no longer needed triangle data
6324 loadmodel->brushq3.num_triangles = 0;
6325 if (loadmodel->brushq3.data_element3i)
6326 Mem_Free(loadmodel->brushq3.data_element3i);
6327 loadmodel->brushq3.data_element3i = NULL;
6330 Mem_Free(patchtess);
6333 static void Mod_Q3BSP_LoadModels(lump_t *l)
6337 int i, j, n, c, count;
6339 in = (q3dmodel_t *)(mod_base + l->fileofs);
6340 if (l->filelen % sizeof(*in))
6341 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6342 count = l->filelen / sizeof(*in);
6343 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6345 loadmodel->brushq3.data_models = out;
6346 loadmodel->brushq3.num_models = count;
6348 for (i = 0;i < count;i++, in++, out++)
6350 for (j = 0;j < 3;j++)
6352 out->mins[j] = LittleFloat(in->mins[j]);
6353 out->maxs[j] = LittleFloat(in->maxs[j]);
6355 n = LittleLong(in->firstface);
6356 c = LittleLong(in->numfaces);
6357 if (n < 0 || n + c > loadmodel->num_surfaces)
6358 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6361 n = LittleLong(in->firstbrush);
6362 c = LittleLong(in->numbrushes);
6363 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6364 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6365 out->firstbrush = n;
6366 out->numbrushes = c;
6370 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6376 in = (int *)(mod_base + l->fileofs);
6377 if (l->filelen % sizeof(*in))
6378 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6379 count = l->filelen / sizeof(*in);
6380 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6382 loadmodel->brush.data_leafbrushes = out;
6383 loadmodel->brush.num_leafbrushes = count;
6385 for (i = 0;i < count;i++, in++, out++)
6387 n = LittleLong(*in);
6388 if (n < 0 || n >= loadmodel->brush.num_brushes)
6389 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6394 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6400 in = (int *)(mod_base + l->fileofs);
6401 if (l->filelen % sizeof(*in))
6402 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6403 count = l->filelen / sizeof(*in);
6404 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6406 loadmodel->brush.data_leafsurfaces = out;
6407 loadmodel->brush.num_leafsurfaces = count;
6409 for (i = 0;i < count;i++, in++, out++)
6411 n = LittleLong(*in);
6412 if (n < 0 || n >= loadmodel->num_surfaces)
6413 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6418 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6422 int i, j, n, c, count;
6424 in = (q3dleaf_t *)(mod_base + l->fileofs);
6425 if (l->filelen % sizeof(*in))
6426 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6427 count = l->filelen / sizeof(*in);
6428 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6430 loadmodel->brush.data_leafs = out;
6431 loadmodel->brush.num_leafs = count;
6433 for (i = 0;i < count;i++, in++, out++)
6437 out->clusterindex = LittleLong(in->clusterindex);
6438 out->areaindex = LittleLong(in->areaindex);
6439 for (j = 0;j < 3;j++)
6441 // yes the mins/maxs are ints
6442 out->mins[j] = LittleLong(in->mins[j]) - 1;
6443 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6445 n = LittleLong(in->firstleafface);
6446 c = LittleLong(in->numleaffaces);
6447 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6448 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6449 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6450 out->numleafsurfaces = c;
6451 n = LittleLong(in->firstleafbrush);
6452 c = LittleLong(in->numleafbrushes);
6453 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6454 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6455 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6456 out->numleafbrushes = c;
6460 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6466 in = (q3dnode_t *)(mod_base + l->fileofs);
6467 if (l->filelen % sizeof(*in))
6468 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6469 count = l->filelen / sizeof(*in);
6471 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6472 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6474 loadmodel->brush.data_nodes = out;
6475 loadmodel->brush.num_nodes = count;
6477 for (i = 0;i < count;i++, in++, out++)
6480 n = LittleLong(in->planeindex);
6481 if (n < 0 || n >= loadmodel->brush.num_planes)
6482 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6483 out->plane = loadmodel->brush.data_planes + n;
6484 for (j = 0;j < 2;j++)
6486 n = LittleLong(in->childrenindex[j]);
6489 if (n >= loadmodel->brush.num_nodes)
6490 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6491 out->children[j] = loadmodel->brush.data_nodes + n;
6496 if (n >= loadmodel->brush.num_leafs)
6497 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6498 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6501 for (j = 0;j < 3;j++)
6503 // yes the mins/maxs are ints
6504 out->mins[j] = LittleLong(in->mins[j]) - 1;
6505 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6509 // set the parent pointers
6510 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6513 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6516 q3dlightgrid_t *out;
6520 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6521 if (l->filelen % sizeof(*in))
6522 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6523 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6524 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6525 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6526 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6527 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6528 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6529 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6530 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6531 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6532 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6533 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6534 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6535 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6536 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]);
6537 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]);
6539 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6542 if (l->filelen < count * (int)sizeof(*in))
6544 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]);
6545 return; // ignore the grid if we cannot understand it
6547 if (l->filelen != count * (int)sizeof(*in))
6548 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
6549 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6550 loadmodel->brushq3.data_lightgrid = out;
6551 loadmodel->brushq3.num_lightgrid = count;
6552 // no swapping or validation necessary
6553 memcpy(out, in, count * (int)sizeof(*out));
6555 if(mod_q3bsp_sRGBlightmaps.integer)
6557 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6559 // we fix the brightness consistently via lightmapscale
6563 for(i = 0; i < count; ++i)
6565 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6566 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6567 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6568 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6569 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6570 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6576 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6578 for(i = 0; i < count; ++i)
6580 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6581 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6582 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6583 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6584 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6585 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6596 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6601 if (l->filelen == 0)
6604 // unvised maps often have cluster indices even without pvs, so check
6605 // leafs to find real number of clusters
6606 loadmodel->brush.num_pvsclusters = 1;
6607 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6608 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6611 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6612 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6613 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6614 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6618 in = (q3dpvs_t *)(mod_base + l->fileofs);
6620 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6622 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6623 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6624 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6625 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6626 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6627 if (l->filelen < totalchains + (int)sizeof(*in))
6628 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);
6630 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6631 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6634 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6636 int i, j, k, index[3];
6637 float transformed[3], blend1, blend2, blend, stylescale = 1;
6638 q3dlightgrid_t *a, *s;
6640 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6641 switch(vid.renderpath)
6643 case RENDERPATH_GL20:
6644 case RENDERPATH_D3D9:
6645 case RENDERPATH_D3D10:
6646 case RENDERPATH_D3D11:
6647 case RENDERPATH_SOFT:
6648 case RENDERPATH_GLES2:
6649 // LordHavoc: FIXME: is this true?
6650 stylescale = 1; // added while render
6652 case RENDERPATH_GL11:
6653 case RENDERPATH_GL13:
6654 case RENDERPATH_GLES1:
6655 stylescale = r_refdef.scene.rtlightstylevalue[0];
6659 if (!model->brushq3.num_lightgrid)
6661 ambientcolor[0] = stylescale;
6662 ambientcolor[1] = stylescale;
6663 ambientcolor[2] = stylescale;
6667 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6668 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6669 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6670 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6671 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6672 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6673 index[0] = (int)floor(transformed[0]);
6674 index[1] = (int)floor(transformed[1]);
6675 index[2] = (int)floor(transformed[2]);
6676 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6678 // now lerp the values
6679 VectorClear(diffusenormal);
6680 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6681 for (k = 0;k < 2;k++)
6683 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6684 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6686 for (j = 0;j < 2;j++)
6688 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6689 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6691 for (i = 0;i < 2;i++)
6693 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6694 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6696 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6697 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6698 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6699 // this uses the mod_md3_sin table because the values are
6700 // already in the 0-255 range, the 64+ bias fetches a cosine
6701 // instead of a sine value
6702 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6703 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6704 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6705 //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)));
6710 // normalize the light direction before turning
6711 VectorNormalize(diffusenormal);
6712 //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]);
6715 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6718 double midf, mid[3];
6724 // find the point distances
6725 mplane_t *plane = node->plane;
6726 if (plane->type < 3)
6728 t1 = p1[plane->type] - plane->dist;
6729 t2 = p2[plane->type] - plane->dist;
6733 t1 = DotProduct (plane->normal, p1) - plane->dist;
6734 t2 = DotProduct (plane->normal, p2) - plane->dist;
6741 node = node->children[1];
6750 node = node->children[0];
6756 midf = t1 / (t1 - t2);
6757 VectorLerp(p1, midf, p2, mid);
6759 // recurse both sides, front side first
6760 // return 2 if empty is followed by solid (hit something)
6761 // do not return 2 if both are solid or both empty,
6762 // or if start is solid and end is empty
6763 // as these degenerate cases usually indicate the eye is in solid and
6764 // should see the target point anyway
6765 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6768 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6773 return ((mleaf_t *)node)->clusterindex < 0;
6776 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6778 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6781 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0);
6782 return trace.fraction == 1;
6786 double tracestart[3], traceend[3];
6787 VectorCopy(start, tracestart);
6788 VectorCopy(end, traceend);
6789 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6793 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)
6796 const bih_leaf_t *leaf;
6797 const bih_node_t *node;
6798 const colbrushf_t *brush;
6801 int nodestackpos = 0;
6802 int nodestack[1024];
6804 memset(trace, 0, sizeof(*trace));
6805 trace->fraction = 1;
6806 trace->hitsupercontentsmask = hitsupercontentsmask;
6807 trace->skipsupercontentsmask = skipsupercontentsmask;
6809 bih = &model->collision_bih;
6813 nodenum = bih->rootnode;
6814 nodestack[nodestackpos++] = nodenum;
6815 while (nodestackpos)
6817 nodenum = nodestack[--nodestackpos];
6818 node = bih->nodes + nodenum;
6820 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6823 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6825 axis = node->type - BIH_SPLITX;
6826 if (start[axis] >= node->frontmin)
6827 nodestack[nodestackpos++] = node->front;
6828 if (start[axis] <= node->backmax)
6829 nodestack[nodestackpos++] = node->back;
6831 else if (node->type == BIH_UNORDERED)
6833 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6835 leaf = bih->leafs + node->children[axis];
6837 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6843 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6844 Collision_TracePointBrushFloat(trace, start, brush);
6846 case BIH_COLLISIONTRIANGLE:
6847 // collision triangle - skipped because they have no volume
6849 case BIH_RENDERTRIANGLE:
6850 // render triangle - skipped because they have no volume
6858 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)
6860 const bih_leaf_t *leaf;
6861 const bih_node_t *node;
6862 const colbrushf_t *brush;
6864 const texture_t *texture;
6865 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6866 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6867 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6872 if (VectorCompare(start, end))
6874 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
6878 nodenum = bih->rootnode;
6880 memset(trace, 0, sizeof(*trace));
6881 trace->fraction = 1;
6882 trace->hitsupercontentsmask = hitsupercontentsmask;
6883 trace->skipsupercontentsmask = skipsupercontentsmask;
6886 nodestackline[nodestackpos][0] = start[0];
6887 nodestackline[nodestackpos][1] = start[1];
6888 nodestackline[nodestackpos][2] = start[2];
6889 nodestackline[nodestackpos][3] = end[0];
6890 nodestackline[nodestackpos][4] = end[1];
6891 nodestackline[nodestackpos][5] = end[2];
6892 nodestack[nodestackpos++] = nodenum;
6893 while (nodestackpos)
6895 nodenum = nodestack[--nodestackpos];
6896 node = bih->nodes + nodenum;
6897 VectorCopy(nodestackline[nodestackpos], nodestart);
6898 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6899 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6900 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6901 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6902 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6903 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6904 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6905 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6907 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6909 // recurse children of the split
6910 axis = node->type - BIH_SPLITX;
6911 d1 = node->backmax - nodestart[axis];
6912 d2 = node->backmax - nodeend[axis];
6913 d3 = nodestart[axis] - node->frontmin;
6914 d4 = nodeend[axis] - node->frontmin;
6915 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6917 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;
6918 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;
6919 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;
6920 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6921 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;
6922 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;
6923 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;
6924 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6925 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;
6926 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;
6927 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;
6928 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6929 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6930 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6931 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6932 case 15: /* <<<< */ break;
6935 else if (node->type == BIH_UNORDERED)
6937 // calculate sweep bounds for this node
6938 // copy node bounds into local variables
6939 VectorCopy(node->mins, nodebigmins);
6940 VectorCopy(node->maxs, nodebigmaxs);
6941 // clip line to this node bounds
6942 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); }
6943 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); }
6944 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); }
6945 // some of the line intersected the enlarged node box
6946 // calculate sweep bounds for this node
6947 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6948 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6949 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6950 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6951 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6952 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6953 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6955 leaf = bih->leafs + node->children[axis];
6956 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6961 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6962 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6964 case BIH_COLLISIONTRIANGLE:
6965 if (!mod_q3bsp_curves_collisions.integer)
6967 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6968 texture = model->data_textures + leaf->textureindex;
6969 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);
6971 case BIH_RENDERTRIANGLE:
6972 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6973 texture = model->data_textures + leaf->textureindex;
6974 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);
6982 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)
6984 if (VectorCompare(start, end))
6986 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
6989 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, &model->collision_bih);
6992 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)
6995 const bih_leaf_t *leaf;
6996 const bih_node_t *node;
6997 const colbrushf_t *brush;
6999 const texture_t *texture;
7000 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
7001 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
7002 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
7003 int axis, nodenum, nodestackpos = 0, nodestack[1024];
7005 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
7007 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
7008 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask);
7010 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask);
7014 bih = &model->collision_bih;
7017 nodenum = bih->rootnode;
7019 // box trace, performed as brush trace
7020 memset(trace, 0, sizeof(*trace));
7021 trace->fraction = 1;
7022 trace->hitsupercontentsmask = hitsupercontentsmask;
7023 trace->skipsupercontentsmask = skipsupercontentsmask;
7025 // calculate tracebox-like parameters for efficient culling
7026 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
7027 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
7028 VectorSubtract(thisbrush_start->mins, start, startmins);
7029 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
7030 VectorSubtract(thisbrush_end->mins, end, endmins);
7031 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7032 mins[0] = min(startmins[0], endmins[0]);
7033 mins[1] = min(startmins[1], endmins[1]);
7034 mins[2] = min(startmins[2], endmins[2]);
7035 maxs[0] = max(startmaxs[0], endmaxs[0]);
7036 maxs[1] = max(startmaxs[1], endmaxs[1]);
7037 maxs[2] = max(startmaxs[2], endmaxs[2]);
7040 nodestackline[nodestackpos][0] = start[0];
7041 nodestackline[nodestackpos][1] = start[1];
7042 nodestackline[nodestackpos][2] = start[2];
7043 nodestackline[nodestackpos][3] = end[0];
7044 nodestackline[nodestackpos][4] = end[1];
7045 nodestackline[nodestackpos][5] = end[2];
7046 nodestack[nodestackpos++] = nodenum;
7047 while (nodestackpos)
7049 nodenum = nodestack[--nodestackpos];
7050 node = bih->nodes + nodenum;
7051 VectorCopy(nodestackline[nodestackpos], nodestart);
7052 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7053 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7054 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7055 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7056 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7057 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7058 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7059 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7061 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7063 // recurse children of the split
7064 axis = node->type - BIH_SPLITX;
7065 d1 = node->backmax - nodestart[axis] - mins[axis];
7066 d2 = node->backmax - nodeend[axis] - mins[axis];
7067 d3 = nodestart[axis] - node->frontmin + maxs[axis];
7068 d4 = nodeend[axis] - node->frontmin + maxs[axis];
7069 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7071 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;
7072 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;
7073 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;
7074 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7075 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;
7076 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;
7077 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;
7078 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7079 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;
7080 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;
7081 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;
7082 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7083 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7084 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7085 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7086 case 15: /* <<<< */ break;
7089 else if (node->type == BIH_UNORDERED)
7091 // calculate sweep bounds for this node
7092 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7093 VectorSubtract(node->mins, maxs, nodebigmins);
7094 VectorSubtract(node->maxs, mins, nodebigmaxs);
7095 // clip line to this node bounds
7096 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); }
7097 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); }
7098 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); }
7099 // some of the line intersected the enlarged node box
7100 // calculate sweep bounds for this node
7101 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7102 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7103 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7104 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7105 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7106 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7107 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7109 leaf = bih->leafs + node->children[axis];
7110 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7115 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7116 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7118 case BIH_COLLISIONTRIANGLE:
7119 if (!mod_q3bsp_curves_collisions.integer)
7121 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7122 texture = model->data_textures + leaf->textureindex;
7123 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);
7125 case BIH_RENDERTRIANGLE:
7126 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7127 texture = model->data_textures + leaf->textureindex;
7128 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);
7136 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)
7138 colboxbrushf_t thisbrush_start, thisbrush_end;
7139 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7141 // box trace, performed as brush trace
7142 VectorAdd(start, boxmins, boxstartmins);
7143 VectorAdd(start, boxmaxs, boxstartmaxs);
7144 VectorAdd(end, boxmins, boxendmins);
7145 VectorAdd(end, boxmaxs, boxendmaxs);
7146 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7147 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7148 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask);
7152 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7155 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0);
7156 return trace.startsupercontents;
7159 qboolean Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
7162 Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0);
7163 return trace.fraction == 1;
7166 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)
7169 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7171 int hitsupercontents;
7172 VectorSet(end, start[0], start[1], model->normalmins[2]);
7174 memset(trace, 0, sizeof(*trace));
7175 trace->fraction = 1;
7176 trace->hitsupercontentsmask = hitsupercontentsmask;
7177 trace->skipsupercontentsmask = skipsupercontentsmask;
7179 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7180 hitsupercontents = trace->hitsupercontents;
7181 memset(trace, 0, sizeof(*trace));
7182 trace->fraction = 1;
7183 trace->hitsupercontentsmask = hitsupercontentsmask;
7184 trace->skipsupercontentsmask = skipsupercontentsmask;
7185 trace->startsupercontents = hitsupercontents;
7189 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7192 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7195 VectorSet(end, start[0], start[1], model->normalmins[2]);
7196 memset(&trace, 0, sizeof(trace));
7198 trace.hitsupercontentsmask = hitsupercontentsmask;
7199 trace.skipsupercontentsmask = skipsupercontentsmask;
7200 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7201 return trace.hitsupercontents;
7207 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
7212 // find which leaf the point is in
7214 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7215 // point trace the brushes
7216 leaf = (mleaf_t *)node;
7217 for (i = 0;i < leaf->numleafbrushes;i++)
7219 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7220 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
7222 brush->markframe = markframe;
7223 Collision_TracePointBrushFloat(trace, point, brush);
7226 // can't do point traces on curves (they have no thickness)
7229 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)
7231 int i, startside, endside;
7232 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
7234 msurface_t *surface;
7237 // walk the tree until we hit a leaf, recursing for any split cases
7241 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7243 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7244 node = node->children[1];
7246 // abort if this part of the bsp tree can not be hit by this trace
7247 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7249 plane = node->plane;
7250 // axial planes are much more common than non-axial, so an optimized
7251 // axial case pays off here
7252 if (plane->type < 3)
7254 dist1 = start[plane->type] - plane->dist;
7255 dist2 = end[plane->type] - plane->dist;
7259 dist1 = DotProduct(start, plane->normal) - plane->dist;
7260 dist2 = DotProduct(end, plane->normal) - plane->dist;
7262 startside = dist1 < 0;
7263 endside = dist2 < 0;
7264 if (startside == endside)
7266 // most of the time the line fragment is on one side of the plane
7267 node = node->children[startside];
7271 // line crosses node plane, split the line
7272 dist1 = PlaneDiff(linestart, plane);
7273 dist2 = PlaneDiff(lineend, plane);
7274 midfrac = dist1 / (dist1 - dist2);
7275 VectorLerp(linestart, midfrac, lineend, mid);
7276 // take the near side first
7277 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7278 // if we found an impact on the front side, don't waste time
7279 // exploring the far side
7280 if (midfrac <= trace->fraction)
7281 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7286 // abort if this part of the bsp tree can not be hit by this trace
7287 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7290 nodesegmentmins[0] = min(start[0], end[0]) - 1;
7291 nodesegmentmins[1] = min(start[1], end[1]) - 1;
7292 nodesegmentmins[2] = min(start[2], end[2]) - 1;
7293 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
7294 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
7295 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
7296 // line trace the brushes
7297 leaf = (mleaf_t *)node;
7299 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7302 for (i = 0;i < leaf->numleafbrushes;i++)
7304 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7305 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7307 brush->markframe = markframe;
7308 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
7311 // can't do point traces on curves (they have no thickness)
7312 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
7314 // line trace the curves
7315 for (i = 0;i < leaf->numleafsurfaces;i++)
7317 surface = model->data_surfaces + leaf->firstleafsurface[i];
7318 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7320 surface->deprecatedq3collisionmarkframe = markframe;
7321 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);
7327 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)
7333 msurface_t *surface;
7335 float nodesegmentmins[3], nodesegmentmaxs[3];
7336 // walk the tree until we hit a leaf, recursing for any split cases
7340 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7342 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7343 node = node->children[1];
7345 // abort if this part of the bsp tree can not be hit by this trace
7346 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7348 plane = node->plane;
7349 // axial planes are much more common than non-axial, so an optimized
7350 // axial case pays off here
7351 if (plane->type < 3)
7353 // this is an axial plane, compare bounding box directly to it and
7354 // recurse sides accordingly
7355 // recurse down node sides
7356 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
7357 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
7358 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
7359 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
7363 // this is a non-axial plane, so check if the start and end boxes
7364 // are both on one side of the plane to handle 'diagonal' cases
7365 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
7369 // segment crosses plane
7370 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7373 // if sides == 0 then the trace itself is bogus (Not A Number values),
7374 // in this case we simply pretend the trace hit nothing
7376 return; // ERROR: NAN bounding box!
7377 // take whichever side the segment box is on
7378 node = node->children[sides - 1];
7381 // abort if this part of the bsp tree can not be hit by this trace
7382 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7384 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
7385 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
7386 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
7387 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
7388 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
7389 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
7391 leaf = (mleaf_t *)node;
7393 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7396 for (i = 0;i < leaf->numleafbrushes;i++)
7398 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7399 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7401 brush->markframe = markframe;
7402 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7405 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
7407 for (i = 0;i < leaf->numleafsurfaces;i++)
7409 surface = model->data_surfaces + leaf->firstleafsurface[i];
7410 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7412 surface->deprecatedq3collisionmarkframe = markframe;
7413 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);
7420 static int markframe = 0;
7422 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)
7426 memset(trace, 0, sizeof(*trace));
7427 trace->fraction = 1;
7428 trace->hitsupercontentsmask = hitsupercontentsmask;
7429 trace->skipsupercontentsmask = skipsupercontentsmask;
7430 if (mod_collision_bih.integer)
7431 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
7432 else if (model->brush.submodel)
7434 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7435 if (brush->colbrushf)
7436 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
7439 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
7442 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)
7445 float segmentmins[3], segmentmaxs[3];
7446 msurface_t *surface;
7449 if (VectorCompare(start, end))
7451 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
7455 memset(trace, 0, sizeof(*trace));
7456 trace->fraction = 1;
7457 trace->hitsupercontentsmask = hitsupercontentsmask;
7458 trace->skipsupercontentsmask = skipsupercontentsmask;
7459 segmentmins[0] = min(start[0], end[0]) - 1;
7460 segmentmins[1] = min(start[1], end[1]) - 1;
7461 segmentmins[2] = min(start[2], end[2]) - 1;
7462 segmentmaxs[0] = max(start[0], end[0]) + 1;
7463 segmentmaxs[1] = max(start[1], end[1]) + 1;
7464 segmentmaxs[2] = max(start[2], end[2]) + 1;
7465 if (mod_collision_bih.integer)
7466 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7467 else if (model->brush.submodel)
7469 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7470 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7471 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7472 if (mod_q3bsp_curves_collisions.integer)
7473 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7474 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7475 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);
7478 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
7481 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)
7483 float segmentmins[3], segmentmaxs[3];
7485 msurface_t *surface;
7488 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
7490 if (VectorCompare(start->mins, end->mins))
7491 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask, skipsupercontentsmask);
7493 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask, skipsupercontentsmask);
7497 // box trace, performed as brush trace
7498 memset(trace, 0, sizeof(*trace));
7499 trace->fraction = 1;
7500 trace->hitsupercontentsmask = hitsupercontentsmask;
7501 trace->skipsupercontentsmask = skipsupercontentsmask;
7502 segmentmins[0] = min(start->mins[0], end->mins[0]) - 1;
7503 segmentmins[1] = min(start->mins[1], end->mins[1]) - 1;
7504 segmentmins[2] = min(start->mins[2], end->mins[2]) - 1;
7505 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]) + 1;
7506 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]) + 1;
7507 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]) + 1;
7508 if (mod_collision_bih.integer)
7509 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7510 else if (model->brush.submodel)
7512 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7513 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7514 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7515 if (mod_q3bsp_curves_collisions.integer)
7516 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7517 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7518 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);
7521 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
7524 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)
7526 colboxbrushf_t thisbrush_start, thisbrush_end;
7527 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7529 // box trace, performed as brush trace
7530 VectorAdd(start, boxmins, boxstartmins);
7531 VectorAdd(start, boxmaxs, boxstartmaxs);
7532 VectorAdd(end, boxmins, boxendmins);
7533 VectorAdd(end, boxmaxs, boxendmaxs);
7534 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7535 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7536 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask);
7539 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7542 int supercontents = 0;
7544 if (mod_collision_bih.integer)
7546 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
7548 // test if the point is inside each brush
7549 else if (model->brush.submodel)
7551 // submodels are effectively one leaf
7552 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7553 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7554 supercontents |= brush->colbrushf->supercontents;
7558 mnode_t *node = model->brush.data_nodes;
7560 // find which leaf the point is in
7562 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7563 leaf = (mleaf_t *)node;
7564 // now check the brushes in the leaf
7565 for (i = 0;i < leaf->numleafbrushes;i++)
7567 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
7568 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7569 supercontents |= brush->colbrushf->supercontents;
7572 return supercontents;
7575 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)
7577 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, &model->render_bih);
7581 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
7589 int nummodelbrushes = model->nummodelbrushes;
7590 int nummodelsurfaces = model->nummodelsurfaces;
7592 const int *collisionelement3i;
7593 const float *collisionvertex3f;
7594 const int *renderelement3i;
7595 const float *rendervertex3f;
7596 bih_leaf_t *bihleafs;
7597 bih_node_t *bihnodes;
7599 int *temp_leafsortscratch;
7600 const msurface_t *surface;
7601 const q3mbrush_t *brush;
7603 // find out how many BIH leaf nodes we need
7605 if (userendersurfaces)
7607 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7608 bihnumleafs += surface->num_triangles;
7612 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7613 if (brush->colbrushf)
7615 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7617 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7618 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7620 bihnumleafs += surface->num_collisiontriangles;
7627 // allocate the memory for the BIH leaf nodes
7628 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7630 // now populate the BIH leaf nodes
7633 // add render surfaces
7634 renderelement3i = model->surfmesh.data_element3i;
7635 rendervertex3f = model->surfmesh.data_vertex3f;
7636 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7638 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7640 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7642 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7643 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7644 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7645 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7646 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7647 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7648 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7649 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7650 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7651 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7656 if (!userendersurfaces)
7658 // add collision brushes
7659 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7661 if (!brush->colbrushf)
7663 bihleafs[bihleafindex].type = BIH_BRUSH;
7664 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7665 bihleafs[bihleafindex].surfaceindex = -1;
7666 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7667 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7668 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7672 // add collision surfaces
7673 collisionelement3i = model->brush.data_collisionelement3i;
7674 collisionvertex3f = model->brush.data_collisionvertex3f;
7675 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7677 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7679 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7680 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7681 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7682 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7683 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7684 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7685 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7686 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7687 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7688 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7694 // allocate buffers for the produced and temporary data
7695 bihmaxnodes = bihnumleafs + 1;
7696 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7697 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7698 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7701 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7703 // we're done with the temporary data
7704 Mem_Free(temp_leafsort);
7706 // resize the BIH nodes array if it over-allocated
7707 if (out->maxnodes > out->numnodes)
7709 out->maxnodes = out->numnodes;
7710 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7716 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7718 int supercontents = 0;
7719 if (nativecontents & CONTENTSQ3_SOLID)
7720 supercontents |= SUPERCONTENTS_SOLID;
7721 if (nativecontents & CONTENTSQ3_WATER)
7722 supercontents |= SUPERCONTENTS_WATER;
7723 if (nativecontents & CONTENTSQ3_SLIME)
7724 supercontents |= SUPERCONTENTS_SLIME;
7725 if (nativecontents & CONTENTSQ3_LAVA)
7726 supercontents |= SUPERCONTENTS_LAVA;
7727 if (nativecontents & CONTENTSQ3_BODY)
7728 supercontents |= SUPERCONTENTS_BODY;
7729 if (nativecontents & CONTENTSQ3_CORPSE)
7730 supercontents |= SUPERCONTENTS_CORPSE;
7731 if (nativecontents & CONTENTSQ3_NODROP)
7732 supercontents |= SUPERCONTENTS_NODROP;
7733 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7734 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7735 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7736 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7737 if (nativecontents & CONTENTSQ3_DONOTENTER)
7738 supercontents |= SUPERCONTENTS_DONOTENTER;
7739 if (nativecontents & CONTENTSQ3_BOTCLIP)
7740 supercontents |= SUPERCONTENTS_BOTCLIP;
7741 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7742 supercontents |= SUPERCONTENTS_OPAQUE;
7743 return supercontents;
7746 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7748 int nativecontents = 0;
7749 if (supercontents & SUPERCONTENTS_SOLID)
7750 nativecontents |= CONTENTSQ3_SOLID;
7751 if (supercontents & SUPERCONTENTS_WATER)
7752 nativecontents |= CONTENTSQ3_WATER;
7753 if (supercontents & SUPERCONTENTS_SLIME)
7754 nativecontents |= CONTENTSQ3_SLIME;
7755 if (supercontents & SUPERCONTENTS_LAVA)
7756 nativecontents |= CONTENTSQ3_LAVA;
7757 if (supercontents & SUPERCONTENTS_BODY)
7758 nativecontents |= CONTENTSQ3_BODY;
7759 if (supercontents & SUPERCONTENTS_CORPSE)
7760 nativecontents |= CONTENTSQ3_CORPSE;
7761 if (supercontents & SUPERCONTENTS_NODROP)
7762 nativecontents |= CONTENTSQ3_NODROP;
7763 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7764 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7765 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7766 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7767 if (supercontents & SUPERCONTENTS_DONOTENTER)
7768 nativecontents |= CONTENTSQ3_DONOTENTER;
7769 if (supercontents & SUPERCONTENTS_BOTCLIP)
7770 nativecontents |= CONTENTSQ3_BOTCLIP;
7771 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7772 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7773 return nativecontents;
7776 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7781 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7782 node = node->children[1];
7784 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7785 if (loadmodel->brush.num_leafs < numleafs)
7786 loadmodel->brush.num_leafs = numleafs;
7789 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7792 q3dheader_t *header;
7793 float corner[3], yawradius, modelradius;
7795 mod->modeldatatypestring = "Q3BSP";
7797 mod->type = mod_brushq3;
7798 mod->brush.ishlbsp = false;
7799 mod->brush.isbsp2rmqe = false;
7800 mod->brush.isbsp2 = false;
7801 mod->brush.isq2bsp = false;
7802 mod->brush.isq3bsp = true;
7803 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7806 header = (q3dheader_t *)buffer;
7807 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7808 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7810 i = LittleLong(header->version);
7811 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7812 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7814 mod->soundfromcenter = true;
7815 mod->TraceBox = Mod_Q3BSP_TraceBox;
7816 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7817 mod->TraceLine = Mod_Q3BSP_TraceLine;
7818 mod->TracePoint = Mod_Q3BSP_TracePoint;
7819 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7820 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7821 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7822 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7823 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7824 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7825 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7826 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7827 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7828 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7829 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7830 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7831 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7832 mod->brush.AmbientSoundLevelsForPoint = NULL;
7833 mod->brush.RoundUpToHullSize = NULL;
7834 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7835 mod->Draw = R_Q1BSP_Draw;
7836 mod->DrawDepth = R_Q1BSP_DrawDepth;
7837 mod->DrawDebug = R_Q1BSP_DrawDebug;
7838 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7839 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7840 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7841 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7842 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7843 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7844 mod->DrawLight = R_Q1BSP_DrawLight;
7846 mod_base = (unsigned char *)header;
7848 // swap all the lumps
7849 header->ident = LittleLong(header->ident);
7850 header->version = LittleLong(header->version);
7851 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7852 for (i = 0;i < lumps;i++)
7854 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7855 if((char *) bufferend < (char *) buffer + j)
7856 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7857 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7858 if((char *) bufferend < (char *) buffer + j)
7859 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7862 * NO, do NOT clear them!
7863 * they contain actual data referenced by other stuff.
7864 * Instead, before using the advertisements lump, check header->versio
7866 * Sorry, but otherwise it breaks memory of the first lump.
7867 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7869 header->lumps[i].fileofs = 0;
7870 header->lumps[i].filelen = 0;
7874 mod->brush.qw_md4sum = 0;
7875 mod->brush.qw_md4sum2 = 0;
7876 for (i = 0;i < lumps;i++)
7878 if (i == Q3LUMP_ENTITIES)
7880 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7881 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7883 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7885 // all this checksumming can take a while, so let's send keepalives here too
7886 CL_KeepaliveMessage(false);
7889 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7890 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7891 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7892 if (header->version == Q3BSPVERSION_IG)
7893 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7895 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7896 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7897 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7898 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7899 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7900 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7901 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7902 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7903 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7904 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7905 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7906 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7907 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7908 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7909 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7911 // the MakePortals code works fine on the q3bsp data as well
7912 if (mod_bsp_portalize.integer)
7913 Mod_Q1BSP_MakePortals();
7915 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7916 loadmodel->brush.supportwateralpha = true;
7918 // make a single combined shadow mesh to allow optimized shadow volume creation
7919 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7921 loadmodel->brush.num_leafs = 0;
7922 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7924 if (loadmodel->brush.numsubmodels)
7925 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7928 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7933 // duplicate the basic information
7934 dpsnprintf(name, sizeof(name), "*%i", i);
7935 mod = Mod_FindName(name, loadmodel->name);
7936 // copy the base model to this one
7938 // rename the clone back to its proper name
7939 strlcpy(mod->name, name, sizeof(mod->name));
7940 mod->brush.parentmodel = loadmodel;
7941 // textures and memory belong to the main model
7942 mod->texturepool = NULL;
7943 mod->mempool = NULL;
7944 mod->brush.GetPVS = NULL;
7945 mod->brush.FatPVS = NULL;
7946 mod->brush.BoxTouchingPVS = NULL;
7947 mod->brush.BoxTouchingLeafPVS = NULL;
7948 mod->brush.BoxTouchingVisibleLeafs = NULL;
7949 mod->brush.FindBoxClusters = NULL;
7950 mod->brush.LightPoint = NULL;
7951 mod->brush.AmbientSoundLevelsForPoint = NULL;
7953 mod->brush.submodel = i;
7954 if (loadmodel->brush.submodels)
7955 loadmodel->brush.submodels[i] = mod;
7957 // make the model surface list (used by shadowing/lighting)
7958 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7959 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7960 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7961 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7962 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7963 Mod_MakeSortedSurfaces(mod);
7965 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7966 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7967 // enlarge the bounding box to enclose all geometry of this model,
7968 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7969 // which can in turn mess up the farclip (as well as culling when
7970 // outside the level - an unimportant concern)
7972 //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]);
7973 for (j = 0;j < mod->nummodelsurfaces;j++)
7975 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7976 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7978 if (!surface->num_vertices)
7980 for (k = 0;k < surface->num_vertices;k++, v += 3)
7982 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7983 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7984 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7985 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7986 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7987 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7990 //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]);
7991 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7992 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7993 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7994 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7995 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7996 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7997 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7998 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7999 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8000 mod->yawmins[2] = mod->normalmins[2];
8001 mod->yawmaxs[2] = mod->normalmaxs[2];
8002 mod->radius = modelradius;
8003 mod->radius2 = modelradius * modelradius;
8005 // this gets altered below if sky or water is used
8006 mod->DrawSky = NULL;
8007 mod->DrawAddWaterPlanes = NULL;
8009 for (j = 0;j < mod->nummodelsurfaces;j++)
8010 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8012 if (j < mod->nummodelsurfaces)
8013 mod->DrawSky = R_Q1BSP_DrawSky;
8015 for (j = 0;j < mod->nummodelsurfaces;j++)
8016 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8018 if (j < mod->nummodelsurfaces)
8019 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8021 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
8022 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
8024 // generate VBOs and other shared data before cloning submodels
8029 if (mod_q3bsp_sRGBlightmaps.integer)
8031 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
8033 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
8034 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
8035 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
8036 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
8037 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
8039 else // if this is NOT set, regular rendering looks right by this requirement anyway
8042 // we want color 1 to do the same as without sRGB
8043 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
8044 loadmodel->lightmapscale *= 2.476923f; // fixes max level
8047 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
8048 // we need to undo that
8049 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
8053 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);
8056 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
8058 int i = LittleLong(((int *)buffer)[1]);
8059 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
8060 Mod_Q3BSP_Load(mod,buffer, bufferend);
8061 else if (i == Q2BSPVERSION)
8062 Mod_Q2BSP_Load(mod,buffer, bufferend);
8064 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
8067 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
8069 Host_Error("Mod_MAP_Load: not yet implemented");
8072 typedef struct objvertex_s
8083 static unsigned char nobsp_pvs[1] = {1};
8085 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
8087 const char *textbase = (char *)buffer, *text = textbase;
8091 char materialname[MAX_QPATH];
8092 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
8093 int index1, index2, index3;
8094 objvertex_t vfirst, vprev, vcurrent;
8097 int numtriangles = 0;
8098 int maxtriangles = 0;
8099 objvertex_t *vertices = NULL;
8101 int maxtextures = 0, numtextures = 0, textureindex = 0;
8102 int maxv = 0, numv = 1;
8103 int maxvt = 0, numvt = 1;
8104 int maxvn = 0, numvn = 1;
8105 char *texturenames = NULL;
8106 float dist, modelradius, modelyawradius, yawradius;
8107 float *obj_v = NULL;
8108 float *obj_vt = NULL;
8109 float *obj_vn = NULL;
8113 objvertex_t *thisvertex = NULL;
8114 int vertexhashindex;
8115 int *vertexhashtable = NULL;
8116 objvertex_t *vertexhashdata = NULL;
8117 objvertex_t *vdata = NULL;
8118 int vertexhashsize = 0;
8119 int vertexhashcount = 0;
8120 skinfile_t *skinfiles = NULL;
8121 unsigned char *data = NULL;
8122 int *submodelfirstsurface;
8123 msurface_t *tempsurface;
8124 msurface_t *tempsurfaces;
8126 memset(&vfirst, 0, sizeof(vfirst));
8127 memset(&vprev, 0, sizeof(vprev));
8128 memset(&vcurrent, 0, sizeof(vcurrent));
8130 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8132 loadmodel->modeldatatypestring = "OBJ";
8134 loadmodel->type = mod_obj;
8135 loadmodel->soundfromcenter = true;
8136 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
8137 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
8138 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
8139 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
8140 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8141 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
8142 loadmodel->brush.TraceLineOfSight = NULL;
8143 loadmodel->brush.SuperContentsFromNativeContents = NULL;
8144 loadmodel->brush.NativeContentsFromSuperContents = NULL;
8145 loadmodel->brush.GetPVS = NULL;
8146 loadmodel->brush.FatPVS = NULL;
8147 loadmodel->brush.BoxTouchingPVS = NULL;
8148 loadmodel->brush.BoxTouchingLeafPVS = NULL;
8149 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
8150 loadmodel->brush.FindBoxClusters = NULL;
8151 loadmodel->brush.LightPoint = NULL;
8152 loadmodel->brush.FindNonSolidLocation = NULL;
8153 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8154 loadmodel->brush.RoundUpToHullSize = NULL;
8155 loadmodel->brush.PointInLeaf = NULL;
8156 loadmodel->Draw = R_Q1BSP_Draw;
8157 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
8158 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
8159 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
8160 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
8161 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
8162 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
8163 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
8164 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
8165 loadmodel->DrawLight = R_Q1BSP_DrawLight;
8167 skinfiles = Mod_LoadSkinFiles();
8168 if (loadmodel->numskins < 1)
8169 loadmodel->numskins = 1;
8171 // make skinscenes for the skins (no groups)
8172 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8173 for (i = 0;i < loadmodel->numskins;i++)
8175 loadmodel->skinscenes[i].firstframe = i;
8176 loadmodel->skinscenes[i].framecount = 1;
8177 loadmodel->skinscenes[i].loop = true;
8178 loadmodel->skinscenes[i].framerate = 10;
8184 // we always have model 0, i.e. the first "submodel"
8185 loadmodel->brush.numsubmodels = 1;
8187 // parse the OBJ text now
8190 static char emptyarg[1] = "";
8195 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8196 line[linelen] = text[linelen];
8198 for (argc = 0;argc < 4;argc++)
8199 argv[argc] = emptyarg;
8202 while (*s == ' ' || *s == '\t')
8212 while (*s == ' ' || *s == '\t')
8222 if (argv[0][0] == '#')
8224 if (!strcmp(argv[0], "v"))
8228 maxv = max(maxv * 2, 1024);
8229 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
8231 if(mod_obj_orientation.integer)
8233 obj_v[numv*3+0] = atof(argv[1]);
8234 obj_v[numv*3+2] = atof(argv[2]);
8235 obj_v[numv*3+1] = atof(argv[3]);
8239 obj_v[numv*3+0] = atof(argv[1]);
8240 obj_v[numv*3+1] = atof(argv[2]);
8241 obj_v[numv*3+2] = atof(argv[3]);
8245 else if (!strcmp(argv[0], "vt"))
8249 maxvt = max(maxvt * 2, 1024);
8250 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
8252 obj_vt[numvt*2+0] = atof(argv[1]);
8253 obj_vt[numvt*2+1] = 1-atof(argv[2]);
8256 else if (!strcmp(argv[0], "vn"))
8260 maxvn = max(maxvn * 2, 1024);
8261 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
8263 if(mod_obj_orientation.integer)
8265 obj_vn[numvn*3+0] = atof(argv[1]);
8266 obj_vn[numvn*3+2] = atof(argv[2]);
8267 obj_vn[numvn*3+1] = atof(argv[3]);
8271 obj_vn[numvn*3+0] = atof(argv[1]);
8272 obj_vn[numvn*3+1] = atof(argv[2]);
8273 obj_vn[numvn*3+2] = atof(argv[3]);
8277 else if (!strcmp(argv[0], "f"))
8281 if (maxtextures <= numtextures)
8283 maxtextures = max(maxtextures * 2, 256);
8284 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8286 textureindex = numtextures++;
8287 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
8289 for (j = 1;j < argc;j++)
8291 index1 = atoi(argv[j]);
8292 while(argv[j][0] && argv[j][0] != '/')
8296 index2 = atoi(argv[j]);
8297 while(argv[j][0] && argv[j][0] != '/')
8301 index3 = atoi(argv[j]);
8302 // negative refers to a recent vertex
8303 // zero means not specified
8304 // positive means an absolute vertex index
8306 index1 = numv - index1;
8308 index2 = numvt - index2;
8310 index3 = numvn - index3;
8311 vcurrent.nextindex = -1;
8312 vcurrent.textureindex = textureindex;
8313 vcurrent.submodelindex = submodelindex;
8314 if (obj_v && index1 >= 0 && index1 < numv)
8315 VectorCopy(obj_v + 3*index1, vcurrent.v);
8316 if (obj_vt && index2 >= 0 && index2 < numvt)
8317 Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
8318 if (obj_vn && index3 >= 0 && index3 < numvn)
8319 VectorCopy(obj_vn + 3*index3, vcurrent.vn);
8320 if (numtriangles == 0)
8322 VectorCopy(vcurrent.v, mins);
8323 VectorCopy(vcurrent.v, maxs);
8327 mins[0] = min(mins[0], vcurrent.v[0]);
8328 mins[1] = min(mins[1], vcurrent.v[1]);
8329 mins[2] = min(mins[2], vcurrent.v[2]);
8330 maxs[0] = max(maxs[0], vcurrent.v[0]);
8331 maxs[1] = max(maxs[1], vcurrent.v[1]);
8332 maxs[2] = max(maxs[2], vcurrent.v[2]);
8338 if (maxtriangles <= numtriangles)
8340 maxtriangles = max(maxtriangles * 2, 32768);
8341 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8343 if(mod_obj_orientation.integer)
8345 vertices[numtriangles*3+0] = vfirst;
8346 vertices[numtriangles*3+1] = vprev;
8347 vertices[numtriangles*3+2] = vcurrent;
8351 vertices[numtriangles*3+0] = vfirst;
8352 vertices[numtriangles*3+2] = vprev;
8353 vertices[numtriangles*3+1] = vcurrent;
8360 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8362 submodelindex = atof(argv[1]);
8363 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8365 else if (!strcmp(argv[0], "usemtl"))
8367 for (i = 0;i < numtextures;i++)
8368 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8370 if (i < numtextures)
8374 if (maxtextures <= numtextures)
8376 maxtextures = max(maxtextures * 2, 256);
8377 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8379 textureindex = numtextures++;
8380 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8385 // now that we have the OBJ data loaded as-is, we can convert it
8387 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8388 VectorCopy(mins, loadmodel->normalmins);
8389 VectorCopy(maxs, loadmodel->normalmaxs);
8390 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8391 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8392 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8393 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8394 modelradius = modelyawradius + modelradius * modelradius;
8395 modelyawradius = sqrt(modelyawradius);
8396 modelradius = sqrt(modelradius);
8397 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8398 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8399 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8400 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8401 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8402 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8403 loadmodel->radius = modelradius;
8404 loadmodel->radius2 = modelradius * modelradius;
8406 // allocate storage for triangles
8407 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8408 // allocate vertex hash structures to build an optimal vertex subset
8409 vertexhashsize = numtriangles*2;
8410 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8411 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8412 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8413 vertexhashcount = 0;
8415 // gather surface stats for assigning vertex/triangle ranges
8419 loadmodel->num_surfaces = 0;
8420 // allocate storage for the worst case number of surfaces, later we resize
8421 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8422 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8423 tempsurface = tempsurfaces;
8424 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8426 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8427 for (textureindex = 0;textureindex < numtextures;textureindex++)
8429 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8431 thisvertex = vertices + vertexindex;
8432 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8435 // skip the surface creation if there are no triangles for it
8436 if (vertexindex == numtriangles*3)
8438 // create a surface for these vertices
8439 surfacevertices = 0;
8440 surfaceelements = 0;
8441 // we hack in a texture index in the surface to be fixed up later...
8442 tempsurface->texture = (texture_t *)((size_t)textureindex);
8443 // calculate bounds as we go
8444 VectorCopy(thisvertex->v, tempsurface->mins);
8445 VectorCopy(thisvertex->v, tempsurface->maxs);
8446 for (;vertexindex < numtriangles*3;vertexindex++)
8448 thisvertex = vertices + vertexindex;
8449 if (thisvertex->submodelindex != submodelindex)
8451 if (thisvertex->textureindex != textureindex)
8453 // add vertex to surface bounds
8454 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8455 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8456 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8457 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8458 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8459 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8460 // add the vertex if it is not found in the merged set, and
8461 // get its index (triangle element) for the surface
8462 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8463 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8465 vdata = vertexhashdata + i;
8466 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8471 i = vertexhashcount++;
8472 vdata = vertexhashdata + i;
8473 *vdata = *thisvertex;
8474 vdata->nextindex = vertexhashtable[vertexhashindex];
8475 vertexhashtable[vertexhashindex] = i;
8478 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8481 surfacetriangles = surfaceelements / 3;
8482 tempsurface->num_vertices = surfacevertices;
8483 tempsurface->num_triangles = surfacetriangles;
8484 tempsurface->num_firstvertex = firstvertex;
8485 tempsurface->num_firsttriangle = firsttriangle;
8486 firstvertex += tempsurface->num_vertices;
8487 firsttriangle += tempsurface->num_triangles;
8489 loadmodel->num_surfaces++;
8492 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8493 numvertices = firstvertex;
8494 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8495 tempsurfaces = NULL;
8497 // allocate storage for final mesh data
8498 loadmodel->num_textures = numtextures * loadmodel->numskins;
8499 loadmodel->num_texturesperskin = numtextures;
8500 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 *));
8501 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
8502 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8503 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8504 loadmodel->surfmesh.num_vertices = numvertices;
8505 loadmodel->surfmesh.num_triangles = numtriangles;
8506 if (r_enableshadowvolumes.integer)
8507 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
8508 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8509 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8510 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8511 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8512 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8513 if (loadmodel->surfmesh.num_vertices <= 65536)
8514 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8516 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8518 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8519 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8520 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8523 // load the textures
8524 for (textureindex = 0;textureindex < numtextures;textureindex++)
8525 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8526 Mod_FreeSkinFiles(skinfiles);
8528 // set the surface textures to their real values now that we loaded them...
8529 for (i = 0;i < loadmodel->num_surfaces;i++)
8530 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8534 Mem_Free(texturenames);
8538 Mem_Free(vertexhashtable);
8539 Mem_Free(vertexhashdata);
8541 // make a single combined shadow mesh to allow optimized shadow volume creation
8542 Mod_Q1BSP_CreateShadowMesh(loadmodel);
8544 // compute all the mesh information that was not loaded from the file
8545 if (loadmodel->surfmesh.data_element3s)
8546 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8547 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8548 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8549 // generate normals if the file did not have them
8550 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8551 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);
8552 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);
8553 if (loadmodel->surfmesh.data_neighbor3i)
8554 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8556 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8557 loadmodel->brush.num_visleafs = 1;
8558 loadmodel->brush.num_leafs = 1;
8559 loadmodel->brush.num_nodes = 0;
8560 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8561 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8562 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8563 loadmodel->brush.num_pvsclusters = 1;
8564 loadmodel->brush.num_pvsclusterbytes = 1;
8565 loadmodel->brush.data_pvsclusters = nobsp_pvs;
8566 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8567 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8568 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
8569 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8570 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8571 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8572 loadmodel->brush.data_leafs->clusterindex = 0;
8573 loadmodel->brush.data_leafs->areaindex = 0;
8574 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8575 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8576 loadmodel->brush.data_leafs->numleafbrushes = 0;
8577 loadmodel->brush.data_leafs->firstleafbrush = NULL;
8578 loadmodel->brush.supportwateralpha = true;
8580 if (loadmodel->brush.numsubmodels)
8581 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8584 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8589 // duplicate the basic information
8590 dpsnprintf(name, sizeof(name), "*%i", i);
8591 mod = Mod_FindName(name, loadmodel->name);
8592 // copy the base model to this one
8594 // rename the clone back to its proper name
8595 strlcpy(mod->name, name, sizeof(mod->name));
8596 mod->brush.parentmodel = loadmodel;
8597 // textures and memory belong to the main model
8598 mod->texturepool = NULL;
8599 mod->mempool = NULL;
8600 mod->brush.GetPVS = NULL;
8601 mod->brush.FatPVS = NULL;
8602 mod->brush.BoxTouchingPVS = NULL;
8603 mod->brush.BoxTouchingLeafPVS = NULL;
8604 mod->brush.BoxTouchingVisibleLeafs = NULL;
8605 mod->brush.FindBoxClusters = NULL;
8606 mod->brush.LightPoint = NULL;
8607 mod->brush.AmbientSoundLevelsForPoint = NULL;
8609 mod->brush.submodel = i;
8610 if (loadmodel->brush.submodels)
8611 loadmodel->brush.submodels[i] = mod;
8613 // make the model surface list (used by shadowing/lighting)
8614 mod->firstmodelsurface = submodelfirstsurface[i];
8615 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8616 mod->firstmodelbrush = 0;
8617 mod->nummodelbrushes = 0;
8618 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8619 Mod_MakeSortedSurfaces(mod);
8621 VectorClear(mod->normalmins);
8622 VectorClear(mod->normalmaxs);
8624 for (j = 0;j < mod->nummodelsurfaces;j++)
8626 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8627 const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8629 if (!surface->num_vertices)
8634 VectorCopy(v3f, mod->normalmins);
8635 VectorCopy(v3f, mod->normalmaxs);
8637 for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8639 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8640 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8641 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8642 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8643 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8644 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8647 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8648 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8649 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8650 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8651 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8652 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8653 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8654 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8655 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8656 mod->yawmins[2] = mod->normalmins[2];
8657 mod->yawmaxs[2] = mod->normalmaxs[2];
8658 mod->radius = modelradius;
8659 mod->radius2 = modelradius * modelradius;
8661 // this gets altered below if sky or water is used
8662 mod->DrawSky = NULL;
8663 mod->DrawAddWaterPlanes = NULL;
8665 for (j = 0;j < mod->nummodelsurfaces;j++)
8666 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8668 if (j < mod->nummodelsurfaces)
8669 mod->DrawSky = R_Q1BSP_DrawSky;
8671 for (j = 0;j < mod->nummodelsurfaces;j++)
8672 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8674 if (j < mod->nummodelsurfaces)
8675 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8677 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8678 mod->render_bih = mod->collision_bih;
8680 // generate VBOs and other shared data before cloning submodels
8685 Mem_Free(submodelfirstsurface);
8687 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);