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_CLIENT | 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 = {CVAR_CLIENT | CVAR_SERVER, "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 = {CVAR_CLIENT, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {CVAR_CLIENT, "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 = {CVAR_CLIENT, "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 = {CVAR_CLIENT, "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 = {CVAR_CLIENT, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {CVAR_CLIENT, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {CVAR_CLIENT, "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 = {CVAR_CLIENT, "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 = {CVAR_CLIENT, "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 = {CVAR_CLIENT, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t r_trippy = {CVAR_CLIENT, "r_trippy", "0", "easter egg"};
42 cvar_t r_fxaa = {CVAR_CLIENT | CVAR_SAVE, "r_fxaa", "0", "fast approximate anti aliasing"};
43 cvar_t mod_noshader_default_offsetmapping = {CVAR_CLIENT | 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 = {CVAR_CLIENT | CVAR_SERVER, "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 = {CVAR_CLIENT, "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 = {CVAR_CLIENT | CVAR_SERVER, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
47 cvar_t mod_q3bsp_curves_collisions_stride = {CVAR_CLIENT | CVAR_SERVER, "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 = {CVAR_CLIENT | CVAR_SERVER, "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 = {CVAR_CLIENT | CVAR_SERVER, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
50 cvar_t mod_q3bsp_debugtracebrush = {CVAR_CLIENT | CVAR_SERVER, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
51 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_CLIENT | 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_CLIENT | 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 = {CVAR_CLIENT | CVAR_SERVER, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
54 cvar_t mod_q3bsp_sRGBlightmaps = {CVAR_CLIENT, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
55 cvar_t mod_q3bsp_lightgrid_texture = {CVAR_CLIENT, "mod_q3bsp_lightgrid_texture", "1", "directly apply the lightgrid as a global texture rather than only reading it at the entity origin"};
56 cvar_t mod_q3bsp_lightgrid_world_surfaces = {CVAR_CLIENT, "mod_q3bsp_lightgrid_world_surfaces", "0", "apply lightgrid lighting to the world bsp geometry rather than using lightmaps (experimental/debug tool)"};
57 cvar_t mod_q3bsp_lightgrid_bsp_surfaces = {CVAR_CLIENT, "mod_q3bsp_lightgrid_bsp_surfaces", "0", "apply lightgrid lighting to bsp models other than the world rather than using their lightmaps (experimental/debug tool)"};
58 cvar_t mod_q3shader_default_offsetmapping = {CVAR_CLIENT | CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
59 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_CLIENT | CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
60 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_CLIENT | CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
61 cvar_t mod_q3shader_default_polygonfactor = {CVAR_CLIENT, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
62 cvar_t mod_q3shader_default_polygonoffset = {CVAR_CLIENT, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
63 cvar_t mod_q3shader_default_refractive_index = {CVAR_CLIENT, "mod_q3shader_default_refractive_index", "1.33", "angle of refraction specified as n to apply when a photon is refracted, example values are: 1.0003 = air, water = 1.333, crown glass = 1.517, flint glass = 1.655, diamond = 2.417"};
64 cvar_t mod_q3shader_force_addalpha = {CVAR_CLIENT, "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"};
65 cvar_t mod_q3shader_force_terrain_alphaflag = {CVAR_CLIENT, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
67 cvar_t mod_q1bsp_polygoncollisions = {CVAR_CLIENT | CVAR_SERVER, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
68 cvar_t mod_recalculatenodeboxes = {CVAR_CLIENT | CVAR_SERVER, "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"};
70 static texture_t mod_q1bsp_texture_solid;
71 static texture_t mod_q1bsp_texture_sky;
72 static texture_t mod_q1bsp_texture_lava;
73 static texture_t mod_q1bsp_texture_slime;
74 static texture_t mod_q1bsp_texture_water;
76 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs);
78 void Mod_BrushInit(void)
80 // Cvar_RegisterVariable(&r_subdivide_size);
81 Cvar_RegisterVariable(&mod_bsp_portalize);
82 Cvar_RegisterVariable(&r_novis);
83 Cvar_RegisterVariable(&r_nosurftextures);
84 Cvar_RegisterVariable(&r_subdivisions_tolerance);
85 Cvar_RegisterVariable(&r_subdivisions_mintess);
86 Cvar_RegisterVariable(&r_subdivisions_maxtess);
87 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
88 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
89 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
90 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
91 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
92 Cvar_RegisterVariable(&r_trippy);
93 Cvar_RegisterVariable(&r_fxaa);
94 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
95 Cvar_RegisterVariable(&mod_obj_orientation);
96 Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
97 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
98 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
99 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
100 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
101 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
102 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
103 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
104 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
105 Cvar_RegisterVariable(&mod_q3bsp_lightgrid_texture);
106 Cvar_RegisterVariable(&mod_q3bsp_lightgrid_world_surfaces);
107 Cvar_RegisterVariable(&mod_q3bsp_lightgrid_bsp_surfaces);
108 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
109 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
110 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
111 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
112 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
113 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
114 Cvar_RegisterVariable(&mod_q3shader_default_refractive_index);
115 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
116 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
117 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
118 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
120 // these games were made for older DP engines and are no longer
121 // maintained; use this hack to show their textures properly
122 if(gamemode == GAME_NEXUIZ)
123 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
125 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
126 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
127 mod_q1bsp_texture_solid.surfaceflags = 0;
128 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
130 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
131 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
132 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
133 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
135 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
136 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
137 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
138 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
140 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
141 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
142 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
143 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
145 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
146 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
147 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
148 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
151 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
158 // LadyHavoc: modified to start at first clip node,
159 // in other words: first node of the (sub)model
160 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
162 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
164 return (mleaf_t *)node;
167 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
171 leaf = Mod_Q1BSP_PointInLeaf(model, p);
174 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
177 memcpy(out, leaf->ambient_sound_level, i);
183 memset(out, 0, outsize);
186 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
189 int nodestackindex = 0;
190 mnode_t *node, *nodestack[1024];
191 if (!model->brush.num_pvsclusters)
193 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
199 // node - recurse down the BSP tree
200 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
204 return -1; // ERROR: NAN bounding box!
205 // box is on one side of plane, take that path
206 node = node->children[sides-1];
210 // box crosses plane, take one path and remember the other
211 if (nodestackindex < 1024)
212 nodestack[nodestackindex++] = node->children[0];
213 node = node->children[1];
219 // leaf - add clusterindex to list
220 if (numclusters < maxclusters)
221 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
225 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
229 if (nodestackindex < 1024)
230 nodestack[nodestackindex++] = node->children[0];
231 node = node->children[1];
236 // leaf - add clusterindex to list
237 if (numclusters < maxclusters)
238 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
243 // try another path we didn't take earlier
244 if (nodestackindex == 0)
246 node = nodestack[--nodestackindex];
248 // return number of clusters found (even if more than the maxclusters)
252 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
254 int nodestackindex = 0;
255 mnode_t *node, *nodestack[1024];
256 if (!model->brush.num_pvsclusters)
258 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
264 // node - recurse down the BSP tree
265 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
269 return -1; // ERROR: NAN bounding box!
270 // box is on one side of plane, take that path
271 node = node->children[sides-1];
275 // box crosses plane, take one path and remember the other
276 if (nodestackindex < 1024)
277 nodestack[nodestackindex++] = node->children[0];
278 node = node->children[1];
284 // leaf - check cluster bit
285 int clusterindex = ((mleaf_t *)node)->clusterindex;
286 if (CHECKPVSBIT(pvs, clusterindex))
288 // it is visible, return immediately with the news
293 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
297 if (nodestackindex < 1024)
298 nodestack[nodestackindex++] = node->children[0];
299 node = node->children[1];
304 // leaf - check cluster bit
305 int clusterindex = ((mleaf_t *)node)->clusterindex;
306 if (CHECKPVSBIT(pvs, clusterindex))
308 // it is visible, return immediately with the news
314 // nothing to see here, try another path we didn't take earlier
315 if (nodestackindex == 0)
317 node = nodestack[--nodestackindex];
323 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
325 int nodestackindex = 0;
326 mnode_t *node, *nodestack[1024];
327 if (!model->brush.num_leafs)
329 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
335 // node - recurse down the BSP tree
336 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
340 return -1; // ERROR: NAN bounding box!
341 // box is on one side of plane, take that path
342 node = node->children[sides-1];
346 // box crosses plane, take one path and remember the other
347 if (nodestackindex < 1024)
348 nodestack[nodestackindex++] = node->children[0];
349 node = node->children[1];
355 // leaf - check cluster bit
356 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
357 if (CHECKPVSBIT(pvs, clusterindex))
359 // it is visible, return immediately with the news
364 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
368 if (nodestackindex < 1024)
369 nodestack[nodestackindex++] = node->children[0];
370 node = node->children[1];
375 // leaf - check cluster bit
376 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
377 if (CHECKPVSBIT(pvs, clusterindex))
379 // it is visible, return immediately with the news
385 // nothing to see here, try another path we didn't take earlier
386 if (nodestackindex == 0)
388 node = nodestack[--nodestackindex];
394 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
396 int nodestackindex = 0;
397 mnode_t *node, *nodestack[1024];
398 if (!model->brush.num_leafs)
400 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
406 // node - recurse down the BSP tree
407 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
411 return -1; // ERROR: NAN bounding box!
412 // box is on one side of plane, take that path
413 node = node->children[sides-1];
417 // box crosses plane, take one path and remember the other
418 if (nodestackindex < 1024)
419 nodestack[nodestackindex++] = node->children[0];
420 node = node->children[1];
426 // leaf - check if it is visible
427 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
429 // it is visible, return immediately with the news
434 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
438 if (nodestackindex < 1024)
439 nodestack[nodestackindex++] = node->children[0];
440 node = node->children[1];
445 // leaf - check if it is visible
446 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
448 // it is visible, return immediately with the news
454 // nothing to see here, try another path we didn't take earlier
455 if (nodestackindex == 0)
457 node = nodestack[--nodestackindex];
463 typedef struct findnonsolidlocationinfo_s
466 vec3_t absmin, absmax;
472 findnonsolidlocationinfo_t;
474 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
477 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
479 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
480 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
481 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
482 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
483 VectorSubtract(vert[1], vert[0], edge[0]);
484 VectorSubtract(vert[2], vert[1], edge[1]);
485 CrossProduct(edge[1], edge[0], facenormal);
486 if (facenormal[0] || facenormal[1] || facenormal[2])
488 VectorNormalize(facenormal);
489 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
490 if (f <= info->bestdist && f >= -info->bestdist)
492 VectorSubtract(vert[0], vert[2], edge[2]);
493 VectorNormalize(edge[0]);
494 VectorNormalize(edge[1]);
495 VectorNormalize(edge[2]);
496 CrossProduct(facenormal, edge[0], edgenormal[0]);
497 CrossProduct(facenormal, edge[1], edgenormal[1]);
498 CrossProduct(facenormal, edge[2], edgenormal[2]);
500 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
501 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
502 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
504 // we got lucky, the center is within the face
505 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
509 if (info->bestdist > dist)
511 info->bestdist = dist;
512 VectorScale(facenormal, (info->radius - -dist), info->nudge);
517 if (info->bestdist > dist)
519 info->bestdist = dist;
520 VectorScale(facenormal, (info->radius - dist), info->nudge);
526 // check which edge or vertex the center is nearest
527 for (i = 0;i < 3;i++)
529 f = DotProduct(info->center, edge[i]);
530 if (f >= DotProduct(vert[0], edge[i])
531 && f <= DotProduct(vert[1], edge[i]))
534 VectorMA(info->center, -f, edge[i], point);
535 dist = sqrt(DotProduct(point, point));
536 if (info->bestdist > dist)
538 info->bestdist = dist;
539 VectorScale(point, (info->radius / dist), info->nudge);
541 // skip both vertex checks
542 // (both are further away than this edge)
547 // not on edge, check first vertex of edge
548 VectorSubtract(info->center, vert[i], point);
549 dist = sqrt(DotProduct(point, point));
550 if (info->bestdist > dist)
552 info->bestdist = dist;
553 VectorScale(point, (info->radius / dist), info->nudge);
562 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
564 int surfacenum, k, *mark;
566 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
568 surface = info->model->data_surfaces + *mark;
569 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
571 for (k = 0;k < surface->num_triangles;k++)
573 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
579 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
583 float f = PlaneDiff(info->center, node->plane);
584 if (f >= -info->bestdist)
585 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
586 if (f <= info->bestdist)
587 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
591 if (((mleaf_t *)node)->numleafsurfaces)
592 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
596 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
599 findnonsolidlocationinfo_t info;
605 VectorCopy(in, info.center);
606 info.radius = radius;
611 VectorClear(info.nudge);
612 info.bestdist = radius;
613 VectorCopy(info.center, info.absmin);
614 VectorCopy(info.center, info.absmax);
615 info.absmin[0] -= info.radius + 1;
616 info.absmin[1] -= info.radius + 1;
617 info.absmin[2] -= info.radius + 1;
618 info.absmax[0] += info.radius + 1;
619 info.absmax[1] += info.radius + 1;
620 info.absmax[2] += info.radius + 1;
621 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
622 VectorAdd(info.center, info.nudge, info.center);
624 while (info.bestdist < radius && ++i < 10);
625 VectorCopy(info.center, out);
628 int Mod_Q1BSP_SuperContentsFromNativeContents(int nativecontents)
630 switch(nativecontents)
635 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
637 return SUPERCONTENTS_WATER;
639 return SUPERCONTENTS_SLIME;
641 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
643 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
648 int Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents)
650 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
651 return CONTENTS_SOLID;
652 if (supercontents & SUPERCONTENTS_SKY)
654 if (supercontents & SUPERCONTENTS_LAVA)
655 return CONTENTS_LAVA;
656 if (supercontents & SUPERCONTENTS_SLIME)
657 return CONTENTS_SLIME;
658 if (supercontents & SUPERCONTENTS_WATER)
659 return CONTENTS_WATER;
660 return CONTENTS_EMPTY;
663 typedef struct RecursiveHullCheckTraceInfo_s
665 // the hull we're tracing through
668 // the trace structure to fill in
671 // start, end, and end - start (in model space)
676 RecursiveHullCheckTraceInfo_t;
678 // 1/32 epsilon to keep floating point happy
679 #define DIST_EPSILON (0.03125)
681 #define HULLCHECKSTATE_EMPTY 0
682 #define HULLCHECKSTATE_SOLID 1
683 #define HULLCHECKSTATE_DONE 2
685 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
687 // status variables, these don't need to be saved on the stack when
688 // recursing... but are because this should be thread-safe
689 // (note: tracing against a bbox is not thread-safe, yet)
694 // variables that need to be stored on the stack when recursing
699 // keep looping until we hit a leaf
702 // find the point distances
703 node = t->hull->clipnodes + num;
704 plane = t->hull->planes + node->planenum;
706 // axial planes can be calculated more quickly without the DotProduct
709 t1 = p1[plane->type] - plane->dist;
710 t2 = p2[plane->type] - plane->dist;
714 t1 = DotProduct (plane->normal, p1) - plane->dist;
715 t2 = DotProduct (plane->normal, p2) - plane->dist;
718 // negative plane distances indicate children[1] (behind plane)
722 // if the line starts and ends on the same side of the plane, recurse
723 // into that child instantly
724 if (p1side == p2side)
726 #if COLLISIONPARANOID >= 3
732 // loop back and process the start child
733 num = node->children[p1side];
737 // find the midpoint where the line crosses the plane, use the
738 // original line for best accuracy
739 #if COLLISIONPARANOID >= 3
744 t1 = t->start[plane->type] - plane->dist;
745 t2 = t->end[plane->type] - plane->dist;
749 t1 = DotProduct (plane->normal, t->start) - plane->dist;
750 t2 = DotProduct (plane->normal, t->end) - plane->dist;
752 midf = t1 / (t1 - t2);
753 midf = bound(p1f, midf, p2f);
754 VectorMA(t->start, midf, t->dist, mid);
756 // we now have a mid point, essentially splitting the line into
757 // the segments in the near child and the far child, we can now
758 // recurse those in order and get their results
760 // recurse both sides, front side first
761 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
762 // if this side is not empty, return what it is (solid or done)
763 if (ret != HULLCHECKSTATE_EMPTY)
766 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
767 // if other side is not solid, return what it is (empty or done)
768 if (ret != HULLCHECKSTATE_SOLID)
771 // front is air and back is solid, this is the impact point...
773 // copy the plane information, flipping it if needed
776 t->trace->plane.dist = -plane->dist;
777 VectorNegate (plane->normal, t->trace->plane.normal);
781 t->trace->plane.dist = plane->dist;
782 VectorCopy (plane->normal, t->trace->plane.normal);
785 // calculate the return fraction which is nudged off the surface a bit
786 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
787 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
788 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
789 t->trace->fraction = bound(0, midf, 1);
791 #if COLLISIONPARANOID >= 3
794 return HULLCHECKSTATE_DONE;
798 // we reached a leaf contents
801 num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
802 if (!t->trace->startfound)
804 t->trace->startfound = true;
805 t->trace->startsupercontents |= num;
807 if (num & SUPERCONTENTS_LIQUIDSMASK)
808 t->trace->inwater = true;
810 t->trace->inopen = true;
811 if (num & SUPERCONTENTS_SOLID)
812 t->trace->hittexture = &mod_q1bsp_texture_solid;
813 else if (num & SUPERCONTENTS_SKY)
814 t->trace->hittexture = &mod_q1bsp_texture_sky;
815 else if (num & SUPERCONTENTS_LAVA)
816 t->trace->hittexture = &mod_q1bsp_texture_lava;
817 else if (num & SUPERCONTENTS_SLIME)
818 t->trace->hittexture = &mod_q1bsp_texture_slime;
820 t->trace->hittexture = &mod_q1bsp_texture_water;
821 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
822 t->trace->hitsupercontents = num;
823 if (num & t->trace->hitsupercontentsmask)
825 // if the first leaf is solid, set startsolid
826 if (t->trace->allsolid)
827 t->trace->startsolid = true;
828 #if COLLISIONPARANOID >= 3
831 return HULLCHECKSTATE_SOLID;
835 t->trace->allsolid = false;
836 #if COLLISIONPARANOID >= 3
839 return HULLCHECKSTATE_EMPTY;
843 //#if COLLISIONPARANOID < 2
844 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
847 mclipnode_t *nodes = t->hull->clipnodes;
848 mplane_t *planes = t->hull->planes;
850 VectorCopy(t->start, point);
853 plane = planes + nodes[num].planenum;
854 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
856 num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
857 t->trace->startsupercontents |= num;
858 if (num & SUPERCONTENTS_LIQUIDSMASK)
859 t->trace->inwater = true;
861 t->trace->inopen = true;
862 if (num & t->trace->hitsupercontentsmask)
864 t->trace->allsolid = t->trace->startsolid = true;
865 return HULLCHECKSTATE_SOLID;
869 t->trace->allsolid = t->trace->startsolid = false;
870 return HULLCHECKSTATE_EMPTY;
875 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, int skipmaterialflagsmask)
877 RecursiveHullCheckTraceInfo_t rhc;
879 memset(&rhc, 0, sizeof(rhc));
880 memset(trace, 0, sizeof(trace_t));
882 rhc.trace->fraction = 1;
883 rhc.trace->allsolid = true;
884 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
885 VectorCopy(start, rhc.start);
886 VectorCopy(start, rhc.end);
887 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
890 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, int skipmaterialflagsmask);
892 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, int skipmaterialflagsmask)
894 RecursiveHullCheckTraceInfo_t rhc;
896 if (VectorCompare(start, end))
898 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
902 // 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...
903 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
905 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
909 memset(&rhc, 0, sizeof(rhc));
910 memset(trace, 0, sizeof(trace_t));
912 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
913 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
914 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
915 rhc.trace->fraction = 1;
916 rhc.trace->allsolid = true;
917 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
918 VectorCopy(start, rhc.start);
919 VectorCopy(end, rhc.end);
920 VectorSubtract(rhc.end, rhc.start, rhc.dist);
921 #if COLLISIONPARANOID >= 2
922 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]);
923 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
928 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
929 memset(&testtrace, 0, sizeof(trace_t));
930 rhc.trace = &testtrace;
931 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
932 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
933 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
934 rhc.trace->fraction = 1;
935 rhc.trace->allsolid = true;
936 VectorCopy(test, rhc.start);
937 VectorCopy(test, rhc.end);
938 VectorClear(rhc.dist);
939 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
940 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
941 if (!trace->startsolid && testtrace.startsolid)
942 Con_Printf(" - ended in solid!\n");
946 if (VectorLength2(rhc.dist))
947 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
949 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
953 static void Mod_Q1BSP_TraceBox(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
955 // this function currently only supports same size start and end
957 RecursiveHullCheckTraceInfo_t rhc;
959 if (VectorCompare(boxmins, boxmaxs))
961 if (VectorCompare(start, end))
962 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
964 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
968 memset(&rhc, 0, sizeof(rhc));
969 memset(trace, 0, sizeof(trace_t));
971 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
972 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
973 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
974 rhc.trace->fraction = 1;
975 rhc.trace->allsolid = true;
976 VectorSubtract(boxmaxs, boxmins, boxsize);
978 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
979 else if (model->brush.ishlbsp)
981 // LadyHavoc: this has to have a minor tolerance (the .1) because of
982 // minor float precision errors from the box being transformed around
983 if (boxsize[0] < 32.1)
985 if (boxsize[2] < 54) // pick the nearest of 36 or 72
986 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
988 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
991 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
995 // LadyHavoc: this has to have a minor tolerance (the .1) because of
996 // minor float precision errors from the box being transformed around
997 if (boxsize[0] < 32.1)
998 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1000 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1002 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1003 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1004 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1005 #if COLLISIONPARANOID >= 2
1006 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]);
1007 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1012 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1013 memset(&testtrace, 0, sizeof(trace_t));
1014 rhc.trace = &testtrace;
1015 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1016 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1017 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1018 rhc.trace->fraction = 1;
1019 rhc.trace->allsolid = true;
1020 VectorCopy(test, rhc.start);
1021 VectorCopy(test, rhc.end);
1022 VectorClear(rhc.dist);
1023 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1024 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1025 if (!trace->startsolid && testtrace.startsolid)
1026 Con_Printf(" - ended in solid!\n");
1030 if (VectorLength2(rhc.dist))
1031 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1033 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1037 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1039 int num = model->brushq1.hulls[0].firstclipnode;
1041 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1042 mplane_t *planes = model->brushq1.hulls[0].planes;
1045 plane = planes + nodes[num].planenum;
1046 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1048 return Mod_Q1BSP_SuperContentsFromNativeContents(num);
1051 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 skipmaterialflagsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1055 colplanef_t cbox_planes[6];
1057 cbox.hasaabbplanes = true;
1058 cbox.supercontents = boxsupercontents;
1061 cbox.numtriangles = 0;
1062 cbox.planes = cbox_planes;
1064 cbox.elements = NULL;
1072 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];
1073 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];
1074 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];
1075 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];
1076 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];
1077 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];
1078 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1079 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1080 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1081 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1082 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1083 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1084 memset(trace, 0, sizeof(trace_t));
1085 trace->hitsupercontentsmask = hitsupercontentsmask;
1086 trace->skipsupercontentsmask = skipsupercontentsmask;
1087 trace->skipmaterialflagsmask = skipmaterialflagsmask;
1088 trace->fraction = 1;
1089 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1091 RecursiveHullCheckTraceInfo_t rhc;
1092 static hull_t box_hull;
1093 static mclipnode_t box_clipnodes[6];
1094 static mplane_t box_planes[6];
1095 // fill in a default trace
1096 memset(&rhc, 0, sizeof(rhc));
1097 memset(trace, 0, sizeof(trace_t));
1098 //To keep everything totally uniform, bounding boxes are turned into small
1099 //BSP trees instead of being compared directly.
1100 // create a temp hull from bounding box sizes
1101 box_planes[0].dist = cmaxs[0] - mins[0];
1102 box_planes[1].dist = cmins[0] - maxs[0];
1103 box_planes[2].dist = cmaxs[1] - mins[1];
1104 box_planes[3].dist = cmins[1] - maxs[1];
1105 box_planes[4].dist = cmaxs[2] - mins[2];
1106 box_planes[5].dist = cmins[2] - maxs[2];
1107 #if COLLISIONPARANOID >= 3
1108 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]);
1111 if (box_hull.clipnodes == NULL)
1115 //Set up the planes and clipnodes so that the six floats of a bounding box
1116 //can just be stored out and get a proper hull_t structure.
1118 box_hull.clipnodes = box_clipnodes;
1119 box_hull.planes = box_planes;
1120 box_hull.firstclipnode = 0;
1121 box_hull.lastclipnode = 5;
1123 for (i = 0;i < 6;i++)
1125 box_clipnodes[i].planenum = i;
1129 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1131 box_clipnodes[i].children[side^1] = i + 1;
1133 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1135 box_planes[i].type = i>>1;
1136 box_planes[i].normal[i>>1] = 1;
1140 // trace a line through the generated clipping hull
1141 //rhc.boxsupercontents = boxsupercontents;
1142 rhc.hull = &box_hull;
1144 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1145 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1146 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1147 rhc.trace->fraction = 1;
1148 rhc.trace->allsolid = true;
1149 VectorCopy(start, rhc.start);
1150 VectorCopy(end, rhc.end);
1151 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1152 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1153 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1154 if (rhc.trace->startsupercontents)
1155 rhc.trace->startsupercontents = boxsupercontents;
1159 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1161 memset(trace, 0, sizeof(trace_t));
1162 trace->fraction = 1;
1163 trace->hitsupercontentsmask = hitsupercontentsmask;
1164 trace->skipsupercontentsmask = skipsupercontentsmask;
1165 trace->skipmaterialflagsmask = skipmaterialflagsmask;
1166 if (BoxesOverlap(start, start, cmins, cmaxs))
1168 trace->startsupercontents |= boxsupercontents;
1169 if ((hitsupercontentsmask & boxsupercontents) && !(skipsupercontentsmask & boxsupercontents))
1171 trace->startsolid = true;
1172 trace->allsolid = true;
1177 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
1180 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
1181 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
1184 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)
1188 float mid, distz = endz - startz;
1192 switch (node->plane->type)
1195 node = node->children[x < node->plane->dist];
1196 continue; // loop back and process the new node
1198 node = node->children[y < node->plane->dist];
1199 continue; // loop back and process the new node
1201 side = startz < node->plane->dist;
1202 if ((endz < node->plane->dist) == side)
1204 node = node->children[side];
1205 continue; // loop back and process the new node
1207 // found an intersection
1208 mid = node->plane->dist;
1211 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1212 front += startz * node->plane->normal[2];
1213 back += endz * node->plane->normal[2];
1214 side = front < node->plane->dist;
1215 if ((back < node->plane->dist) == side)
1217 node = node->children[side];
1218 continue; // loop back and process the new node
1220 // found an intersection
1221 mid = startz + distz * (front - node->plane->dist) / (front - back);
1225 // go down front side
1226 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1227 return true; // hit something
1229 // check for impact on this node
1230 if (node->numsurfaces)
1233 int dsi, dti, lmwidth, lmheight;
1235 msurface_t *surface;
1236 unsigned char *lightmap;
1237 int maps, line3, size3;
1240 float scale, w, w00, w01, w10, w11;
1242 surface = model->data_surfaces + node->firstsurface;
1243 for (i = 0;i < node->numsurfaces;i++, surface++)
1245 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1246 continue; // no lightmaps
1248 // location we want to sample in the lightmap
1249 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;
1250 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;
1253 // thanks to jitspoe for pointing out that this int cast was
1254 // rounding toward zero, so we floor it
1255 dsi = (int)floor(ds);
1256 dti = (int)floor(dt);
1257 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1258 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1261 // we have to tolerate a position of lmwidth-1 for some rare
1262 // cases - in which case the sampling position still gets
1263 // clamped but the color gets interpolated to that edge.
1264 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1266 // in the rare cases where we're sampling slightly off
1267 // the polygon, clamp the sampling position (we can still
1268 // interpolate outside it, where it becomes extrapolation)
1273 if (dsi > lmwidth-2)
1275 if (dti > lmheight-2)
1278 // calculate bilinear interpolation factors
1279 // and also multiply by fixedpoint conversion factors to
1280 // compensate for lightmaps being 0-255 (as 0-2), we use
1281 // r_refdef.scene.rtlightstylevalue here which is already
1282 // 0.000-2.148 range
1283 // (if we used r_refdef.scene.lightstylevalue this
1284 // divisor would be 32768 rather than 128)
1287 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1288 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1289 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1290 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1292 // values for pointer math
1293 line3 = lmwidth * 3; // LadyHavoc: *3 for colored lighting
1294 size3 = lmwidth * lmheight * 3; // LadyHavoc: *3 for colored lighting
1296 // look up the pixel
1297 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LadyHavoc: *3 for colored lighting
1299 // bilinear filter each lightmap style, and sum them
1300 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1302 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1303 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1304 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1305 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1306 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1310 return true; // success
1315 // go down back side
1316 node = node->children[side ^ 1];
1318 distz = endz - startz;
1319 // loop back and process the new node
1322 // did not hit anything
1326 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1328 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1329 VectorSet(diffusenormal, 0, 0, 1);
1331 if (!model->brushq1.lightdata)
1333 VectorSet(ambientcolor, 1, 1, 1);
1334 VectorSet(diffusecolor, 0, 0, 0);
1338 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);
1341 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1346 const msurface_t *surface;
1351 float edgenormal[3];
1358 surface = model->data_surfaces + node->firstsurface;
1359 for (i = 0;i < node->numsurfaces;i++, surface++)
1361 // skip surfaces whose bounding box does not include the point
1362 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1364 // skip faces with contents we don't care about
1365 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1367 // ignore surfaces matching the skipsupercontentsmask (this is rare)
1368 if (t->trace->skipsupercontentsmask & surface->texture->supercontents)
1370 // skip surfaces matching the skipmaterialflagsmask (e.g. MATERIALFLAG_NOSHADOW)
1371 if (t->trace->skipmaterialflagsmask & surface->texture->currentmaterialflags)
1373 // get the surface normal - since it is flat we know any vertex normal will suffice
1374 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1376 if (DotProduct(t->dist, normal) > 0)
1378 // iterate edges and see if the point is outside one of them
1379 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1381 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1382 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1383 VectorSubtract(v0, v1, edgedir);
1384 CrossProduct(edgedir, normal, edgenormal);
1385 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1388 // if the point is outside one of the edges, it is not within the surface
1389 if (j < surface->num_vertices)
1392 // we hit a surface, this is the impact point...
1393 VectorCopy(normal, t->trace->plane.normal);
1394 t->trace->plane.dist = DotProduct(normal, p);
1396 // calculate the return fraction which is nudged off the surface a bit
1397 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1398 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1399 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1400 t->trace->fraction = bound(0, midf, 1);
1402 t->trace->hittexture = surface->texture->currentframe;
1403 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1404 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1405 return surface->texture->currentframe;
1410 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])
1412 const mplane_t *plane;
1415 double midf, mid[3];
1416 const mleaf_t *leaf;
1420 plane = node->plane;
1421 if (plane->type < 3)
1423 t1 = p1[plane->type] - plane->dist;
1424 t2 = p2[plane->type] - plane->dist;
1428 t1 = DotProduct (plane->normal, p1) - plane->dist;
1429 t2 = DotProduct (plane->normal, p2) - plane->dist;
1435 node = node->children[1];
1444 node = node->children[0];
1450 // the line intersects, find intersection point
1451 // LadyHavoc: this uses the original trace for maximum accuracy
1452 if (plane->type < 3)
1454 t1 = t->start[plane->type] - plane->dist;
1455 t2 = t->end[plane->type] - plane->dist;
1459 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1460 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1463 midf = t1 / (t1 - t2);
1464 VectorMA(t->start, midf, t->dist, mid);
1466 // recurse both sides, front side first, return if we hit a surface
1467 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1468 return HULLCHECKSTATE_DONE;
1470 // test each surface on the node
1471 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1472 if (t->trace->hittexture)
1473 return HULLCHECKSTATE_DONE;
1475 // recurse back side
1476 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1478 leaf = (const mleaf_t *)node;
1479 side = Mod_Q1BSP_SuperContentsFromNativeContents(leaf->contents);
1480 if (!t->trace->startfound)
1482 t->trace->startfound = true;
1483 t->trace->startsupercontents |= side;
1485 if (side & SUPERCONTENTS_LIQUIDSMASK)
1486 t->trace->inwater = true;
1488 t->trace->inopen = true;
1489 if (side & t->trace->hitsupercontentsmask)
1491 // if the first leaf is solid, set startsolid
1492 if (t->trace->allsolid)
1493 t->trace->startsolid = true;
1494 return HULLCHECKSTATE_SOLID;
1498 t->trace->allsolid = false;
1499 return HULLCHECKSTATE_EMPTY;
1503 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, int skipmaterialflagsmask)
1505 RecursiveHullCheckTraceInfo_t rhc;
1507 memset(&rhc, 0, sizeof(rhc));
1508 memset(trace, 0, sizeof(trace_t));
1510 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1511 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1512 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1513 rhc.trace->fraction = 1;
1514 rhc.trace->allsolid = true;
1515 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1516 VectorCopy(start, rhc.start);
1517 VectorCopy(end, rhc.end);
1518 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1519 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1520 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1523 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1526 unsigned char *outstart = out;
1527 while (out < outend)
1531 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));
1541 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));
1544 for (c = *in++;c > 0;c--)
1548 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));
1559 R_Q1BSP_LoadSplitSky
1561 A sky texture is 256*128, with the right side being a masked overlay
1564 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1569 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1570 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1572 // allocate a texture pool if we need it
1573 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1574 loadmodel->texturepool = R_AllocTexturePool();
1576 if (bytesperpixel == 4)
1578 for (y = 0;y < h;y++)
1580 for (x = 0;x < w;x++)
1582 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1583 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1589 // make an average value for the back to avoid
1590 // a fringe on the top level
1599 for (y = 0;y < h;y++)
1601 for (x = 0;x < w;x++)
1603 p = src[x*width+y+w];
1604 r += palette_rgb[p][0];
1605 g += palette_rgb[p][1];
1606 b += palette_rgb[p][2];
1609 bgra.b[2] = r/(w*h);
1610 bgra.b[1] = g/(w*h);
1611 bgra.b[0] = b/(w*h);
1613 for (y = 0;y < h;y++)
1615 for (x = 0;x < w;x++)
1617 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1619 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1624 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, 0, 0, 0, vid.sRGB3D);
1625 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, 0, 0, 0, vid.sRGB3D);
1626 Mem_Free(solidpixels);
1627 Mem_Free(alphapixels);
1630 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1632 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0, firstskynoshadowtexture = 0;
1633 skinframe_t *skinframemissing;
1634 texture_t *tx, *tx2, *anims[10], *altanims[10], *currentskynoshadowtexture;
1635 texture_t backuptex;
1636 unsigned char *data, *mtdata;
1638 char mapname[MAX_QPATH], name[MAX_QPATH];
1639 unsigned char zeroopaque[4], zerotrans[4];
1642 Vector4Set(zeroopaque, 0, 0, 0, 255);
1643 Vector4Set(zerotrans, 0, 0, 0, 128);
1645 loadmodel->data_textures = NULL;
1647 // add two slots for notexture walls and notexture liquids, and duplicate
1648 // all sky textures; sky surfaces can be shadow-casting or not, the surface
1649 // loading will choose according to the contents behind the surface
1650 // (necessary to support e1m5 logo shadow which has a SKY contents brush,
1651 // while correctly treating sky textures as occluders in other situations).
1656 nummiptex = MSG_ReadLittleLong(sb);
1657 loadmodel->num_textures = nummiptex + 2;
1658 // save the position so we can go back to it
1659 watermark = sb->readcount;
1660 for (i = 0; i < nummiptex; i++)
1662 doffset = MSG_ReadLittleLong(sb);
1663 if (r_nosurftextures.integer)
1667 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1671 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1673 // copy name, but only up to 16 characters
1674 // (the output buffer can hold more than this, but the input buffer is
1676 for (j = 0; j < 16; j++)
1677 name[j] = MSG_ReadByte(&miptexsb);
1679 // pretty up the buffer (replacing any trailing garbage with 0)
1680 for (j = (int)strlen(name); j < 16; j++)
1683 if (!strncmp(name, "sky", 3))
1687 // bump it back to where we started parsing
1688 sb->readcount = (int)watermark;
1690 firstskynoshadowtexture = loadmodel->num_textures;
1691 loadmodel->num_textures += numsky;
1695 loadmodel->num_textures = 2;
1696 firstskynoshadowtexture = loadmodel->num_textures;
1698 loadmodel->num_texturesperskin = loadmodel->num_textures;
1700 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1702 // we'll be writing to these in parallel for sky textures
1703 currentskynoshadowtexture = loadmodel->data_textures + firstskynoshadowtexture;
1705 // fill out all slots with notexture
1706 skinframemissing = R_SkinFrame_LoadMissing();
1707 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1709 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1712 tx->basealpha = 1.0f;
1713 tx->materialshaderpass = tx->shaderpasses[0] = Mod_CreateShaderPass(loadmodel->mempool, skinframemissing);
1714 tx->materialshaderpass->skinframes[0] = skinframemissing;
1715 tx->currentskinframe = skinframemissing;
1716 tx->basematerialflags = MATERIALFLAG_WALL;
1717 if (i == loadmodel->num_textures - 1)
1719 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1720 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1721 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1725 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1726 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1728 tx->currentframe = tx;
1730 // clear water settings
1733 tx->refractive_index = mod_q3shader_default_refractive_index.value;
1734 tx->refractfactor = 1;
1735 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1736 tx->reflectfactor = 1;
1737 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1738 tx->r_water_wateralpha = 1;
1739 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1740 tx->offsetscale = 1;
1742 tx->specularscalemod = 1;
1743 tx->specularpowermod = 1;
1744 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1745 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1746 // JUST GREP FOR "specularscalemod = 1".
1751 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1755 s = loadmodel->name;
1756 if (!strncasecmp(s, "maps/", 5))
1758 FS_StripExtension(s, mapname, sizeof(mapname));
1760 // LadyHavoc: mostly rewritten map texture loader
1761 for (i = 0;i < nummiptex;i++)
1763 doffset = MSG_ReadLittleLong(sb);
1764 if (r_nosurftextures.integer)
1768 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1772 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1774 // copy name, but only up to 16 characters
1775 // (the output buffer can hold more than this, but the input buffer is
1777 for (j = 0;j < 16;j++)
1778 name[j] = MSG_ReadByte(&miptexsb);
1780 // pretty up the buffer (replacing any trailing garbage with 0)
1781 for (j = (int)strlen(name);j < 16;j++)
1786 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1787 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1790 mtwidth = MSG_ReadLittleLong(&miptexsb);
1791 mtheight = MSG_ReadLittleLong(&miptexsb);
1793 j = MSG_ReadLittleLong(&miptexsb);
1797 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1799 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1802 mtdata = miptexsb.data + j;
1805 if ((mtwidth & 15) || (mtheight & 15))
1806 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1808 // LadyHavoc: force all names to lowercase
1809 for (j = 0;name[j];j++)
1810 if (name[j] >= 'A' && name[j] <= 'Z')
1811 name[j] += 'a' - 'A';
1813 // LadyHavoc: backup the texture_t because q3 shader loading overwrites it
1814 backuptex = loadmodel->data_textures[i];
1815 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, loadmodel->data_textures + i, name, false, false, 0, MATERIALFLAG_WALL))
1817 loadmodel->data_textures[i] = backuptex;
1819 tx = loadmodel->data_textures + i;
1820 strlcpy(tx->name, name, sizeof(tx->name));
1821 tx->width = mtwidth;
1822 tx->height = mtheight;
1823 tx->basealpha = 1.0f;
1825 // start out with no animation
1826 tx->currentframe = tx;
1827 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
1829 if (tx->name[0] == '*')
1831 if (!strncmp(tx->name, "*lava", 5))
1833 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1834 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1836 else if (!strncmp(tx->name, "*slime", 6))
1838 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1839 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1843 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1844 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1847 else if (!strncmp(tx->name, "sky", 3))
1849 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1850 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1851 // for the surface traceline we need to hit this surface as a solid...
1852 tx->supercontents |= SUPERCONTENTS_SOLID;
1856 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1857 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1860 if (cls.state != ca_dedicated)
1862 // LadyHavoc: HL sky textures are entirely different than quake
1863 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1865 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1867 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1868 if (data && image_width == image_height * 2)
1870 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1873 else if (mtdata != NULL)
1874 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1878 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, false);
1880 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, false);
1882 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1885 // did not find external texture, load it from the bsp or wad3
1886 if (loadmodel->brush.ishlbsp)
1888 // internal texture overrides wad
1889 unsigned char *pixels, *freepixels;
1890 pixels = freepixels = NULL;
1892 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1894 pixels = freepixels = W_GetTextureBGRA(tx->name);
1897 tx->width = image_width;
1898 tx->height = image_height;
1899 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, image_width, image_height, CRC_Block(pixels, image_width * image_height * 4), true);
1902 Mem_Free(freepixels);
1904 else if (mtdata) // texture included
1905 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1907 // if skinframe is still NULL the "missing" texture has already been assigned to this
1909 tx->materialshaderpass->skinframes[0] = skinframe;
1911 // LadyHavoc: some Tenebrae textures get replaced by black
1912 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1913 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, 0, 0, 0, false);
1914 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1915 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, 0, 0, 0, false);
1916 tx->currentskinframe = tx->materialshaderpass->skinframes[0];
1919 tx->basematerialflags = MATERIALFLAG_WALL;
1920 if (tx->name[0] == '*')
1922 // LadyHavoc: some turbulent textures should not be affected by wateralpha
1923 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1924 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1925 else if (!strncmp(tx->name,"*lava",5)
1926 || !strncmp(tx->name,"*teleport",9)
1927 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1928 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1930 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1931 if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1932 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1934 else if (tx->name[0] == '{') // fence textures
1936 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1938 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1940 // replace the texture with black
1941 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1943 else if (!strncmp(tx->name, "sky", 3))
1944 tx->basematerialflags = MATERIALFLAG_SKY;
1945 else if (!strcmp(tx->name, "caulk"))
1946 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1947 else if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1948 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1949 tx->currentmaterialflags = tx->basematerialflags;
1951 // duplicate of sky with NOSHADOW
1952 if (tx->basematerialflags & MATERIALFLAG_SKY)
1954 *currentskynoshadowtexture = *tx;
1955 currentskynoshadowtexture->basematerialflags |= MATERIALFLAG_NOSHADOW;
1956 tx->skynoshadowtexture = currentskynoshadowtexture;
1957 currentskynoshadowtexture++;
1961 // sequence the animations
1962 for (i = 0;i < nummiptex;i++)
1964 tx = loadmodel->data_textures + i;
1965 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1968 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1970 Con_Printf("Bad animating texture %s\n", tx->name);
1973 if (tx->anim_total[0] || tx->anim_total[1])
1974 continue; // already sequenced
1976 // find the number of frames in the animation
1977 memset(anims, 0, sizeof(anims));
1978 memset(altanims, 0, sizeof(altanims));
1980 for (j = i;j < nummiptex;j++)
1982 tx2 = loadmodel->data_textures + j;
1983 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1987 if (num >= '0' && num <= '9')
1988 anims[num - '0'] = tx2;
1989 else if (num >= 'a' && num <= 'j')
1990 altanims[num - 'a'] = tx2;
1991 // No need to warn otherwise - we already did above.
1995 for (j = 0;j < 10;j++)
2002 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
2005 for (j = 0;j < max;j++)
2009 Con_Printf("Missing frame %i of %s\n", j, tx->name);
2013 for (j = 0;j < altmax;j++)
2017 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
2024 // If we have exactly one frame, something's wrong.
2025 if (max + altmax <= 1)
2027 Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
2032 // if there is no alternate animation, duplicate the primary
2033 // animation into the alternate
2035 for (k = 0;k < 10;k++)
2036 altanims[k] = anims[k];
2042 Con_Printf("Missing frame 0 of %s\n", tx->name);
2044 // however, we can handle this by duplicating the alternate animation into the primary
2046 for (k = 0;k < 10;k++)
2047 anims[k] = altanims[k];
2051 // link together the primary animation
2052 for (j = 0;j < max;j++)
2055 tx2->animated = 1; // q1bsp
2056 tx2->anim_total[0] = max;
2057 tx2->anim_total[1] = altmax;
2058 for (k = 0;k < 10;k++)
2060 tx2->anim_frames[0][k] = anims[k];
2061 tx2->anim_frames[1][k] = altanims[k];
2065 // if there really is an alternate anim...
2066 if (anims[0] != altanims[0])
2068 // link together the alternate animation
2069 for (j = 0;j < altmax;j++)
2072 tx2->animated = 1; // q1bsp
2073 // the primary/alternate are reversed here
2074 tx2->anim_total[0] = altmax;
2075 tx2->anim_total[1] = max;
2076 for (k = 0;k < 10;k++)
2078 tx2->anim_frames[0][k] = altanims[k];
2079 tx2->anim_frames[1][k] = anims[k];
2086 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2089 unsigned char *in, *out, *data, d;
2090 char litfilename[MAX_QPATH];
2091 char dlitfilename[MAX_QPATH];
2092 fs_offset_t filesize;
2093 if (loadmodel->brush.ishlbsp) // LadyHavoc: load the colored lighting data straight
2095 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2096 for (i = 0;i < sb->cursize;i++)
2097 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2099 else // LadyHavoc: bsp version 29 (normal white lighting)
2101 // LadyHavoc: hope is not lost yet, check for a .lit file to load
2102 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2103 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2104 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2105 strlcat (litfilename, ".lit", sizeof (litfilename));
2106 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2107 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2110 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2112 i = LittleLong(((int *)data)[1]);
2115 if (developer_loading.integer)
2116 Con_Printf("loaded %s\n", litfilename);
2117 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2118 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2120 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2123 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2125 i = LittleLong(((int *)data)[1]);
2128 if (developer_loading.integer)
2129 Con_Printf("loaded %s\n", dlitfilename);
2130 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2131 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2132 loadmodel->brushq3.deluxemapping_modelspace = false;
2133 loadmodel->brushq3.deluxemapping = true;
2142 Con_Printf("Unknown .lit file version (%d)\n", i);
2144 else if (filesize == 8)
2145 Con_Print("Empty .lit file, ignoring\n");
2147 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2154 // LadyHavoc: oh well, expand the white lighting data
2157 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2159 out = loadmodel->brushq1.lightdata;
2160 for (i = 0;i < sb->cursize;i++)
2170 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2172 loadmodel->brushq1.num_compressedpvs = 0;
2173 loadmodel->brushq1.data_compressedpvs = NULL;
2176 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2177 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2178 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2181 // used only for HalfLife maps
2182 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2184 char key[128], value[4096];
2188 if (!COM_ParseToken_Simple(&data, false, false, true))
2190 if (com_token[0] != '{')
2194 if (!COM_ParseToken_Simple(&data, false, false, true))
2196 if (com_token[0] == '}')
2197 break; // end of worldspawn
2198 if (com_token[0] == '_')
2199 strlcpy(key, com_token + 1, sizeof(key));
2201 strlcpy(key, com_token, sizeof(key));
2202 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2203 key[strlen(key)-1] = 0;
2204 if (!COM_ParseToken_Simple(&data, false, false, true))
2206 dpsnprintf(value, sizeof(value), "%s", com_token);
2207 if (!strcmp("wad", key)) // for HalfLife maps
2209 if (loadmodel->brush.ishlbsp)
2212 for (i = 0;i < (int)sizeof(value);i++)
2213 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2215 if (i < (int)sizeof(value) && value[i])
2217 for (;i < (int)sizeof(value);i++)
2219 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2220 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2222 else if (value[i] == ';' || value[i] == 0)
2226 W_LoadTextureWadFile(&value[j], false);
2238 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2240 loadmodel->brush.entities = NULL;
2243 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2244 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2245 loadmodel->brush.entities[sb->cursize] = 0;
2246 if (loadmodel->brush.ishlbsp)
2247 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2251 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2255 int structsize = 12;
2257 if (sb->cursize % structsize)
2258 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2259 count = sb->cursize / structsize;
2260 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2262 loadmodel->brushq1.vertexes = out;
2263 loadmodel->brushq1.numvertexes = count;
2265 for ( i=0 ; i<count ; i++, out++)
2267 out->position[0] = MSG_ReadLittleFloat(sb);
2268 out->position[1] = MSG_ReadLittleFloat(sb);
2269 out->position[2] = MSG_ReadLittleFloat(sb);
2273 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2277 int structsize = (48+4*hullinfo->filehulls);
2279 if (sb->cursize % structsize)
2280 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2282 count = sb->cursize / structsize;
2283 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2285 loadmodel->brushq1.submodels = out;
2286 loadmodel->brush.numsubmodels = count;
2288 for (i = 0; i < count; i++, out++)
2290 // spread out the mins / maxs by a pixel
2291 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2292 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2293 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2294 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2295 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2296 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2297 out->origin[0] = MSG_ReadLittleFloat(sb);
2298 out->origin[1] = MSG_ReadLittleFloat(sb);
2299 out->origin[2] = MSG_ReadLittleFloat(sb);
2300 for (j = 0; j < hullinfo->filehulls; j++)
2301 out->headnode[j] = MSG_ReadLittleLong(sb);
2302 out->visleafs = MSG_ReadLittleLong(sb);
2303 out->firstface = MSG_ReadLittleLong(sb);
2304 out->numfaces = MSG_ReadLittleLong(sb);
2308 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2312 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2314 if (sb->cursize % structsize)
2315 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2316 count = sb->cursize / structsize;
2317 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2319 loadmodel->brushq1.edges = out;
2320 loadmodel->brushq1.numedges = count;
2322 for ( i=0 ; i<count ; i++, out++)
2324 if (loadmodel->brush.isbsp2)
2326 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2327 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2331 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2332 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2334 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2336 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);
2337 if(!loadmodel->brushq1.numvertexes)
2338 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2346 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2349 int i, j, k, count, miptex;
2350 int structsize = 40;
2352 if (sb->cursize % structsize)
2353 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2354 count = sb->cursize / structsize;
2355 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2357 loadmodel->brushq1.texinfo = out;
2358 loadmodel->brushq1.numtexinfo = count;
2360 for (i = 0;i < count;i++, out++)
2362 for (k = 0;k < 2;k++)
2363 for (j = 0;j < 4;j++)
2364 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2366 miptex = MSG_ReadLittleLong(sb);
2367 out->q1flags = MSG_ReadLittleLong(sb);
2369 if (out->q1flags & TEX_SPECIAL)
2371 // if texture chosen is NULL or the shader needs a lightmap,
2372 // force to notexture water shader
2373 out->textureindex = loadmodel->num_textures - 1;
2377 // if texture chosen is NULL, force to notexture
2378 out->textureindex = loadmodel->num_textures - 2;
2380 // see if the specified miptex is valid and try to use it instead
2381 if (loadmodel->data_textures)
2383 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2384 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2386 out->textureindex = miptex;
2392 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2397 mins[0] = mins[1] = mins[2] = 9999;
2398 maxs[0] = maxs[1] = maxs[2] = -9999;
2400 for (i = 0;i < numverts;i++)
2402 for (j = 0;j < 3;j++, v++)
2412 #define MAX_SUBDIVPOLYTRIANGLES 4096
2413 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2415 static int subdivpolyverts, subdivpolytriangles;
2416 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2417 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2419 static int subdivpolylookupvert(vec3_t v)
2422 for (i = 0;i < subdivpolyverts;i++)
2423 if (subdivpolyvert[i][0] == v[0]
2424 && subdivpolyvert[i][1] == v[1]
2425 && subdivpolyvert[i][2] == v[2])
2427 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2428 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2429 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2430 return subdivpolyverts++;
2433 static void SubdividePolygon(int numverts, float *verts)
2435 int i, i1, i2, i3, f, b, c, p;
2436 vec3_t mins, maxs, front[256], back[256];
2437 float m, *pv, *cv, dist[256], frac;
2440 Host_Error("SubdividePolygon: ran out of verts in buffer");
2442 BoundPoly(numverts, verts, mins, maxs);
2444 for (i = 0;i < 3;i++)
2446 m = (mins[i] + maxs[i]) * 0.5;
2447 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2448 if (maxs[i] - m < 8)
2450 if (m - mins[i] < 8)
2454 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2455 dist[c] = cv[i] - m;
2458 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2462 VectorCopy(pv, front[f]);
2467 VectorCopy(pv, back[b]);
2470 if (dist[p] == 0 || dist[c] == 0)
2472 if ((dist[p] > 0) != (dist[c] > 0) )
2475 frac = dist[p] / (dist[p] - dist[c]);
2476 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2477 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2478 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2484 SubdividePolygon(f, front[0]);
2485 SubdividePolygon(b, back[0]);
2489 i1 = subdivpolylookupvert(verts);
2490 i2 = subdivpolylookupvert(verts + 3);
2491 for (i = 2;i < numverts;i++)
2493 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2495 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2499 i3 = subdivpolylookupvert(verts + i * 3);
2500 subdivpolyindex[subdivpolytriangles][0] = i1;
2501 subdivpolyindex[subdivpolytriangles][1] = i2;
2502 subdivpolyindex[subdivpolytriangles][2] = i3;
2504 subdivpolytriangles++;
2508 //Breaks a polygon up along axial 64 unit
2509 //boundaries so that turbulent and sky warps
2510 //can be done reasonably.
2511 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2517 subdivpolytriangles = 0;
2518 subdivpolyverts = 0;
2519 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2520 if (subdivpolytriangles < 1)
2521 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2523 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2524 mesh->num_vertices = subdivpolyverts;
2525 mesh->num_triangles = subdivpolytriangles;
2526 mesh->vertex = (surfvertex_t *)(mesh + 1);
2527 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2528 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2530 for (i = 0;i < mesh->num_triangles;i++)
2531 for (j = 0;j < 3;j++)
2532 mesh->index[i*3+j] = subdivpolyindex[i][j];
2534 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2536 VectorCopy(subdivpolyvert[i], v->v);
2537 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2538 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2543 extern cvar_t gl_max_lightmapsize;
2544 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2546 msurface_t *surface;
2547 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2548 float texmins[2], texmaxs[2], val;
2549 rtexture_t *lightmaptexture, *deluxemaptexture;
2551 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2553 if (sb->cursize % structsize)
2554 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2555 count = sb->cursize / structsize;
2556 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2557 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2559 loadmodel->num_surfaces = count;
2561 loadmodel->brushq1.firstrender = true;
2562 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2566 for (surfacenum = 0;surfacenum < count;surfacenum++)
2568 if (loadmodel->brush.isbsp2)
2569 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2571 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2572 totalverts += numedges;
2573 totaltris += numedges - 2;
2576 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
2578 lightmaptexture = NULL;
2579 deluxemaptexture = r_texture_blanknormalmap;
2581 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2582 totallightmapsamples = 0;
2586 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2588 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2589 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2590 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2591 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2592 firstedge = MSG_ReadLittleLong(sb);
2593 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2594 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2595 for (i = 0;i < MAXLIGHTMAPS;i++)
2596 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2597 lightmapoffset = MSG_ReadLittleLong(sb);
2599 // FIXME: validate edges, texinfo, etc?
2600 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)
2601 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2602 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2603 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2604 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2605 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2607 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2608 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2610 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2611 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2612 lightmapoffset = -1;
2614 //surface->flags = surface->texture->flags;
2615 //if (LittleShort(in->side))
2616 // surface->flags |= SURF_PLANEBACK;
2617 //surface->plane = loadmodel->brush.data_planes + planenum;
2619 surface->num_firstvertex = totalverts;
2620 surface->num_vertices = numedges;
2621 surface->num_firsttriangle = totaltris;
2622 surface->num_triangles = numedges - 2;
2623 totalverts += numedges;
2624 totaltris += numedges - 2;
2626 // convert edges back to a normal polygon
2627 for (i = 0;i < surface->num_vertices;i++)
2629 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2631 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2633 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2635 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2636 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2637 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2638 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2639 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2640 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2641 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2642 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2645 for (i = 0;i < surface->num_triangles;i++)
2647 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2648 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2649 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2652 // compile additional data about the surface geometry
2653 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);
2654 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);
2655 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2657 // generate surface extents information
2658 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2659 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2660 for (i = 1;i < surface->num_vertices;i++)
2662 for (j = 0;j < 2;j++)
2664 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2665 texmins[j] = min(texmins[j], val);
2666 texmaxs[j] = max(texmaxs[j], val);
2669 for (i = 0;i < 2;i++)
2671 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2672 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2675 smax = surface->lightmapinfo->extents[0] >> 4;
2676 tmax = surface->lightmapinfo->extents[1] >> 4;
2677 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2678 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2681 surface->lightmaptexture = NULL;
2682 surface->deluxemaptexture = r_texture_blanknormalmap;
2683 if (lightmapoffset == -1)
2685 surface->lightmapinfo->samples = NULL;
2687 // give non-lightmapped water a 1x white lightmap
2688 if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2690 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2691 surface->lightmapinfo->styles[0] = 0;
2692 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2696 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LadyHavoc: HalfLife map (bsp version 30)
2697 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2698 else // LadyHavoc: white lighting (bsp version 29)
2700 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2701 if (loadmodel->brushq1.nmaplightdata)
2702 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2705 // check if we should apply a lightmap to this
2706 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2708 if (ssize > 256 || tsize > 256)
2709 Host_Error("Bad surface extents");
2711 if (lightmapsize < ssize)
2712 lightmapsize = ssize;
2713 if (lightmapsize < tsize)
2714 lightmapsize = tsize;
2716 totallightmapsamples += ssize*tsize;
2718 // force lightmap upload on first time seeing the surface
2720 // additionally this is used by the later code to see if a
2721 // lightmap is needed on this surface (rather than duplicating the
2723 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2724 loadmodel->lit = true;
2728 // small maps (such as ammo boxes especially) don't need big lightmap
2729 // textures, so this code tries to guess a good size based on
2730 // totallightmapsamples (size of the lightmaps lump basically), as well as
2731 // trying to max out the size if there is a lot of lightmap data to store
2732 // additionally, never choose a lightmapsize that is smaller than the
2733 // largest surface encountered (as it would fail)
2735 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2738 // now that we've decided the lightmap texture size, we can do the rest
2739 if (cls.state != ca_dedicated)
2741 int stainmapsize = 0;
2742 mod_alloclightmap_state_t allocState;
2744 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2745 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2747 int iu, iv, lightmapx = 0, lightmapy = 0;
2748 float u, v, ubase, vbase, uscale, vscale;
2750 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2753 smax = surface->lightmapinfo->extents[0] >> 4;
2754 tmax = surface->lightmapinfo->extents[1] >> 4;
2755 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2756 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2757 stainmapsize += ssize * tsize * 3;
2759 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2761 // allocate a texture pool if we need it
2762 if (loadmodel->texturepool == NULL)
2763 loadmodel->texturepool = R_AllocTexturePool();
2764 // could not find room, make a new lightmap
2765 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2766 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2767 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2768 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);
2769 if (loadmodel->brushq1.nmaplightdata)
2770 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);
2772 Mod_AllocLightmap_Reset(&allocState);
2773 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2775 surface->lightmaptexture = lightmaptexture;
2776 surface->deluxemaptexture = deluxemaptexture;
2777 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2778 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2780 uscale = 1.0f / (float)lightmapsize;
2781 vscale = 1.0f / (float)lightmapsize;
2782 ubase = lightmapx * uscale;
2783 vbase = lightmapy * vscale;
2785 for (i = 0;i < surface->num_vertices;i++)
2787 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);
2788 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);
2789 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2790 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2791 // LadyHavoc: calc lightmap data offset for vertex lighting to use
2794 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2798 if (cl_stainmaps.integer)
2800 // allocate stainmaps for permanent marks on walls and clear white
2801 unsigned char *stainsamples = NULL;
2802 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2803 memset(stainsamples, 255, stainmapsize);
2805 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2807 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2809 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2810 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2811 surface->lightmapinfo->stainsamples = stainsamples;
2812 stainsamples += ssize * tsize * 3;
2817 // generate ushort elements array if possible
2818 if (loadmodel->surfmesh.data_element3s)
2819 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2820 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2823 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2826 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2827 node->parent = parent;
2830 // this is a node, recurse to children
2831 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2832 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2833 // combine supercontents of children
2834 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2839 mleaf_t *leaf = (mleaf_t *)node;
2840 // if this is a leaf, calculate supercontents mask from all collidable
2841 // primitives in the leaf (brushes and collision surfaces)
2842 // also flag if the leaf contains any collision surfaces
2843 leaf->combinedsupercontents = 0;
2844 // combine the supercontents values of all brushes in this leaf
2845 for (j = 0;j < leaf->numleafbrushes;j++)
2846 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2847 // check if this leaf contains any collision surfaces (q3 patches)
2848 for (j = 0;j < leaf->numleafsurfaces;j++)
2850 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2851 if (surface->num_collisiontriangles)
2853 leaf->containscollisionsurfaces = true;
2854 leaf->combinedsupercontents |= surface->texture->supercontents;
2860 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2862 int i, j, count, p, child[2];
2864 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2866 if (sb->cursize % structsize)
2867 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2868 count = sb->cursize / structsize;
2870 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2871 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2873 loadmodel->brush.data_nodes = out;
2874 loadmodel->brush.num_nodes = count;
2876 for ( i=0 ; i<count ; i++, out++)
2878 p = MSG_ReadLittleLong(sb);
2879 out->plane = loadmodel->brush.data_planes + p;
2881 if (loadmodel->brush.isbsp2rmqe)
2883 child[0] = MSG_ReadLittleLong(sb);
2884 child[1] = MSG_ReadLittleLong(sb);
2885 out->mins[0] = MSG_ReadLittleShort(sb);
2886 out->mins[1] = MSG_ReadLittleShort(sb);
2887 out->mins[2] = MSG_ReadLittleShort(sb);
2888 out->maxs[0] = MSG_ReadLittleShort(sb);
2889 out->maxs[1] = MSG_ReadLittleShort(sb);
2890 out->maxs[2] = MSG_ReadLittleShort(sb);
2891 out->firstsurface = MSG_ReadLittleLong(sb);
2892 out->numsurfaces = MSG_ReadLittleLong(sb);
2894 else if (loadmodel->brush.isbsp2)
2896 child[0] = MSG_ReadLittleLong(sb);
2897 child[1] = MSG_ReadLittleLong(sb);
2898 out->mins[0] = MSG_ReadLittleFloat(sb);
2899 out->mins[1] = MSG_ReadLittleFloat(sb);
2900 out->mins[2] = MSG_ReadLittleFloat(sb);
2901 out->maxs[0] = MSG_ReadLittleFloat(sb);
2902 out->maxs[1] = MSG_ReadLittleFloat(sb);
2903 out->maxs[2] = MSG_ReadLittleFloat(sb);
2904 out->firstsurface = MSG_ReadLittleLong(sb);
2905 out->numsurfaces = MSG_ReadLittleLong(sb);
2909 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2910 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2911 if (child[0] >= count)
2913 if (child[1] >= count)
2916 out->mins[0] = MSG_ReadLittleShort(sb);
2917 out->mins[1] = MSG_ReadLittleShort(sb);
2918 out->mins[2] = MSG_ReadLittleShort(sb);
2919 out->maxs[0] = MSG_ReadLittleShort(sb);
2920 out->maxs[1] = MSG_ReadLittleShort(sb);
2921 out->maxs[2] = MSG_ReadLittleShort(sb);
2923 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2924 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2927 for (j=0 ; j<2 ; j++)
2929 // LadyHavoc: this code supports broken bsp files produced by
2930 // arguire qbsp which can produce more than 32768 nodes, any value
2931 // below count is assumed to be a node number, any other value is
2932 // assumed to be a leaf number
2936 if (p < loadmodel->brush.num_nodes)
2937 out->children[j] = loadmodel->brush.data_nodes + p;
2940 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2941 // map it to the solid leaf
2942 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2947 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2949 if (p < loadmodel->brush.num_leafs)
2950 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2953 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2954 // map it to the solid leaf
2955 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2961 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2964 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2967 int i, j, count, p, firstmarksurface, nummarksurfaces;
2968 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2970 if (sb->cursize % structsize)
2971 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2972 count = sb->cursize / structsize;
2973 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2975 loadmodel->brush.data_leafs = out;
2976 loadmodel->brush.num_leafs = count;
2977 // get visleafs from the submodel data
2978 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2979 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2980 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2981 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2983 // FIXME: this function could really benefit from some error checking
2984 for ( i=0 ; i<count ; i++, out++)
2986 out->contents = MSG_ReadLittleLong(sb);
2988 out->clusterindex = i - 1;
2989 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2990 out->clusterindex = -1;
2992 p = MSG_ReadLittleLong(sb);
2993 // ignore visofs errors on leaf 0 (solid)
2994 if (p >= 0 && out->clusterindex >= 0)
2996 if (p >= loadmodel->brushq1.num_compressedpvs)
2997 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2999 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);
3002 if (loadmodel->brush.isbsp2rmqe)
3004 out->mins[0] = MSG_ReadLittleShort(sb);
3005 out->mins[1] = MSG_ReadLittleShort(sb);
3006 out->mins[2] = MSG_ReadLittleShort(sb);
3007 out->maxs[0] = MSG_ReadLittleShort(sb);
3008 out->maxs[1] = MSG_ReadLittleShort(sb);
3009 out->maxs[2] = MSG_ReadLittleShort(sb);
3011 firstmarksurface = MSG_ReadLittleLong(sb);
3012 nummarksurfaces = MSG_ReadLittleLong(sb);
3014 else if (loadmodel->brush.isbsp2)
3016 out->mins[0] = MSG_ReadLittleFloat(sb);
3017 out->mins[1] = MSG_ReadLittleFloat(sb);
3018 out->mins[2] = MSG_ReadLittleFloat(sb);
3019 out->maxs[0] = MSG_ReadLittleFloat(sb);
3020 out->maxs[1] = MSG_ReadLittleFloat(sb);
3021 out->maxs[2] = MSG_ReadLittleFloat(sb);
3023 firstmarksurface = MSG_ReadLittleLong(sb);
3024 nummarksurfaces = MSG_ReadLittleLong(sb);
3028 out->mins[0] = MSG_ReadLittleShort(sb);
3029 out->mins[1] = MSG_ReadLittleShort(sb);
3030 out->mins[2] = MSG_ReadLittleShort(sb);
3031 out->maxs[0] = MSG_ReadLittleShort(sb);
3032 out->maxs[1] = MSG_ReadLittleShort(sb);
3033 out->maxs[2] = MSG_ReadLittleShort(sb);
3035 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
3036 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
3039 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
3041 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
3042 out->numleafsurfaces = nummarksurfaces;
3046 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
3047 out->firstleafsurface = NULL;
3048 out->numleafsurfaces = 0;
3051 for (j = 0;j < 4;j++)
3052 out->ambient_sound_level[j] = MSG_ReadByte(sb);
3056 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
3060 const unsigned char *pvs;
3061 // if there's no vis data, assume supported (because everything is visible all the time)
3062 if (!loadmodel->brush.data_pvsclusters)
3064 // check all liquid leafs to see if they can see into empty leafs, if any
3065 // can we can assume this map supports r_wateralpha
3066 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3068 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3070 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3071 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3072 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3079 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3084 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3086 if (sb->cursize % structsize)
3087 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3088 count = sb->cursize / structsize;
3089 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3091 loadmodel->brushq1.clipnodes = out;
3092 loadmodel->brushq1.numclipnodes = count;
3094 for (i = 1; i < MAX_MAP_HULLS; i++)
3096 hull = &loadmodel->brushq1.hulls[i];
3097 hull->clipnodes = out;
3098 hull->firstclipnode = 0;
3099 hull->lastclipnode = count-1;
3100 hull->planes = loadmodel->brush.data_planes;
3101 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3102 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3103 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3104 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3105 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3106 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3107 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3110 for (i=0 ; i<count ; i++, out++)
3112 out->planenum = MSG_ReadLittleLong(sb);
3113 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3114 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3115 if (loadmodel->brush.isbsp2)
3117 out->children[0] = MSG_ReadLittleLong(sb);
3118 out->children[1] = MSG_ReadLittleLong(sb);
3119 if (out->children[0] >= count)
3120 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3121 if (out->children[1] >= count)
3122 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3126 // LadyHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3127 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3128 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3129 if (out->children[0] >= count)
3130 out->children[0] -= 65536;
3131 if (out->children[1] >= count)
3132 out->children[1] -= 65536;
3137 //Duplicate the drawing hull structure as a clipping hull
3138 static void Mod_Q1BSP_MakeHull0(void)
3145 hull = &loadmodel->brushq1.hulls[0];
3147 in = loadmodel->brush.data_nodes;
3148 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3150 hull->clipnodes = out;
3151 hull->firstclipnode = 0;
3152 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3153 hull->planes = loadmodel->brush.data_planes;
3155 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3157 out->planenum = in->plane - loadmodel->brush.data_planes;
3158 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3159 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3163 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3166 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3168 if (sb->cursize % structsize)
3169 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3170 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3171 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3173 if (loadmodel->brush.isbsp2)
3175 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3177 j = MSG_ReadLittleLong(sb);
3178 if (j < 0 || j >= loadmodel->num_surfaces)
3179 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3180 loadmodel->brush.data_leafsurfaces[i] = j;
3185 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3187 j = (unsigned short) MSG_ReadLittleShort(sb);
3188 if (j >= loadmodel->num_surfaces)
3189 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3190 loadmodel->brush.data_leafsurfaces[i] = j;
3195 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3200 if (sb->cursize % structsize)
3201 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3202 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3203 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3205 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3206 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3210 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3214 int structsize = 20;
3216 if (sb->cursize % structsize)
3217 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3218 loadmodel->brush.num_planes = sb->cursize / structsize;
3219 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3221 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3223 out->normal[0] = MSG_ReadLittleFloat(sb);
3224 out->normal[1] = MSG_ReadLittleFloat(sb);
3225 out->normal[2] = MSG_ReadLittleFloat(sb);
3226 out->dist = MSG_ReadLittleFloat(sb);
3227 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3232 // fixes up sky surfaces that have SKY contents behind them, so that they do not cast shadows (e1m5 logo shadow trick).
3233 static void Mod_Q1BSP_AssignNoShadowSkySurfaces(dp_model_t *mod)
3236 msurface_t *surface;
3239 for (i = 0, surface = mod->data_surfaces + mod->firstmodelsurface; i < mod->nummodelsurfaces; i++, surface++)
3241 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3243 // check if the point behind the surface polygon is SOLID or SKY contents
3244 VectorMAMAM(0.5f, surface->mins, 0.5f, surface->maxs, -0.25f, mod->surfmesh.data_normal3f + 3*surface->num_firstvertex, center);
3245 contents = Mod_Q1BSP_PointSuperContents(mod, 0, center);
3246 if (!(contents & SUPERCONTENTS_SOLID))
3247 surface->texture = surface->texture->skynoshadowtexture;
3252 static void Mod_Q1BSP_LoadMapBrushes(void)
3256 int submodel, numbrushes;
3257 qboolean firstbrush;
3258 char *text, *maptext;
3259 char mapfilename[MAX_QPATH];
3260 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3261 strlcat (mapfilename, ".map", sizeof (mapfilename));
3262 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3266 if (!COM_ParseToken_Simple(&data, false, false, true))
3271 if (!COM_ParseToken_Simple(&data, false, false, true))
3273 if (com_token[0] != '{')
3279 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3282 if (!COM_ParseToken_Simple(&data, false, false, true))
3284 if (com_token[0] == '}')
3285 break; // end of entity
3286 if (com_token[0] == '{')
3293 if (submodel > loadmodel->brush.numsubmodels)
3295 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3299 model = loadmodel->brush.submodels[submodel];
3306 if (!COM_ParseToken_Simple(&data, false, false, true))
3308 if (com_token[0] == '}')
3309 break; // end of brush
3310 // each brush face should be this format:
3311 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3312 // FIXME: support hl .map format
3313 for (pointnum = 0;pointnum < 3;pointnum++)
3315 COM_ParseToken_Simple(&data, false, false, true);
3316 for (componentnum = 0;componentnum < 3;componentnum++)
3318 COM_ParseToken_Simple(&data, false, false, true);
3319 point[pointnum][componentnum] = atof(com_token);
3321 COM_ParseToken_Simple(&data, false, false, true);
3323 COM_ParseToken_Simple(&data, false, false, true);
3324 strlcpy(facetexture, com_token, sizeof(facetexture));
3325 COM_ParseToken_Simple(&data, false, false, true);
3326 //scroll_s = atof(com_token);
3327 COM_ParseToken_Simple(&data, false, false, true);
3328 //scroll_t = atof(com_token);
3329 COM_ParseToken_Simple(&data, false, false, true);
3330 //rotate = atof(com_token);
3331 COM_ParseToken_Simple(&data, false, false, true);
3332 //scale_s = atof(com_token);
3333 COM_ParseToken_Simple(&data, false, false, true);
3334 //scale_t = atof(com_token);
3335 TriangleNormal(point[0], point[1], point[2], planenormal);
3336 VectorNormalizeDouble(planenormal);
3337 planedist = DotProduct(point[0], planenormal);
3338 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3348 #define MAX_PORTALPOINTS 64
3350 typedef struct portal_s
3353 mnode_t *nodes[2]; // [0] = front side of plane
3354 struct portal_s *next[2];
3356 double points[3*MAX_PORTALPOINTS];
3357 struct portal_s *chain; // all portals are linked into a list
3361 static memexpandablearray_t portalarray;
3363 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3365 // process only nodes (leafs already had their box calculated)
3369 // calculate children first
3370 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3371 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3373 // make combined bounding box from children
3374 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3375 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3376 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3377 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3378 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3379 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3382 static void Mod_Q1BSP_FinalizePortals(void)
3384 int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3388 mleaf_t *leaf, *endleaf;
3390 // tally up portal and point counts and recalculate bounding boxes for all
3391 // leafs (because qbsp is very sloppy)
3392 leaf = loadmodel->brush.data_leafs;
3393 endleaf = leaf + loadmodel->brush.num_leafs;
3394 if (mod_recalculatenodeboxes.integer)
3396 for (;leaf < endleaf;leaf++)
3398 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3399 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3404 for (portalindex = 0;portalindex < portalrange;portalindex++)
3406 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3409 // note: this check must match the one below or it will usually corrupt memory
3410 // 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
3411 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3414 numpoints += p->numpoints * 2;
3417 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3418 loadmodel->brush.num_portals = numportals;
3419 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3420 loadmodel->brush.num_portalpoints = numpoints;
3421 // clear all leaf portal chains
3422 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3423 loadmodel->brush.data_leafs[i].portals = NULL;
3424 // process all portals in the global portal chain, while freeing them
3425 portal = loadmodel->brush.data_portals;
3426 point = loadmodel->brush.data_portalpoints;
3427 for (portalindex = 0;portalindex < portalrange;portalindex++)
3429 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3432 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3434 // note: this check must match the one above or it will usually corrupt memory
3435 // 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
3436 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3438 // first make the back to front portal(forward portal)
3439 portal->points = point;
3440 portal->numpoints = p->numpoints;
3441 portal->plane.dist = p->plane.dist;
3442 VectorCopy(p->plane.normal, portal->plane.normal);
3443 portal->here = (mleaf_t *)p->nodes[1];
3444 portal->past = (mleaf_t *)p->nodes[0];
3446 for (j = 0;j < portal->numpoints;j++)
3448 VectorCopy(p->points + j*3, point->position);
3451 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3452 PlaneClassify(&portal->plane);
3454 // link into leaf's portal chain
3455 portal->next = portal->here->portals;
3456 portal->here->portals = portal;
3458 // advance to next portal
3461 // then make the front to back portal(backward portal)
3462 portal->points = point;
3463 portal->numpoints = p->numpoints;
3464 portal->plane.dist = -p->plane.dist;
3465 VectorNegate(p->plane.normal, portal->plane.normal);
3466 portal->here = (mleaf_t *)p->nodes[0];
3467 portal->past = (mleaf_t *)p->nodes[1];
3469 for (j = portal->numpoints - 1;j >= 0;j--)
3471 VectorCopy(p->points + j*3, point->position);
3474 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3475 PlaneClassify(&portal->plane);
3477 // link into leaf's portal chain
3478 portal->next = portal->here->portals;
3479 portal->here->portals = portal;
3481 // advance to next portal
3484 // add the portal's polygon points to the leaf bounding boxes
3485 if (mod_recalculatenodeboxes.integer)
3487 for (i = 0;i < 2;i++)
3489 leaf = (mleaf_t *)p->nodes[i];
3490 for (j = 0;j < p->numpoints;j++)
3492 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3493 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3494 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3495 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3496 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3497 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3503 // now recalculate the node bounding boxes from the leafs
3504 if (mod_recalculatenodeboxes.integer)
3505 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3513 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3516 Host_Error("AddPortalToNodes: NULL front node");
3518 Host_Error("AddPortalToNodes: NULL back node");
3519 if (p->nodes[0] || p->nodes[1])
3520 Host_Error("AddPortalToNodes: already included");
3521 // 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
3523 p->nodes[0] = front;
3524 p->next[0] = (portal_t *)front->portals;
3525 front->portals = (mportal_t *)p;
3528 p->next[1] = (portal_t *)back->portals;
3529 back->portals = (mportal_t *)p;
3534 RemovePortalFromNode
3537 static void RemovePortalFromNodes(portal_t *portal)
3541 void **portalpointer;
3543 for (i = 0;i < 2;i++)
3545 node = portal->nodes[i];
3547 portalpointer = (void **) &node->portals;
3550 t = (portal_t *)*portalpointer;
3552 Host_Error("RemovePortalFromNodes: portal not in leaf");
3556 if (portal->nodes[0] == node)
3558 *portalpointer = portal->next[0];
3559 portal->nodes[0] = NULL;
3561 else if (portal->nodes[1] == node)
3563 *portalpointer = portal->next[1];
3564 portal->nodes[1] = NULL;
3567 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3571 if (t->nodes[0] == node)
3572 portalpointer = (void **) &t->next[0];
3573 else if (t->nodes[1] == node)
3574 portalpointer = (void **) &t->next[1];
3576 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3581 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3582 static double *portalpointsbuffer;
3583 static int portalpointsbufferoffset;
3584 static int portalpointsbuffersize;
3585 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3588 mnode_t *front, *back, *other_node;
3589 mplane_t clipplane, *plane;
3590 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3591 int numfrontpoints, numbackpoints;
3592 double *frontpoints, *backpoints;
3594 // if a leaf, we're done
3598 // get some space for our clipping operations to use
3599 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3601 portalpointsbuffersize = portalpointsbufferoffset * 2;
3602 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3604 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3605 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3606 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3607 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3609 plane = node->plane;
3611 front = node->children[0];
3612 back = node->children[1];
3614 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3616 // create the new portal by generating a polygon for the node plane,
3617 // and clipping it by all of the other portals(which came from nodes above this one)
3618 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3619 nodeportal->plane = *plane;
3621 // 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)
3622 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);
3623 nodeportal->numpoints = 4;
3624 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3625 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3627 clipplane = portal->plane;
3628 if (portal->nodes[0] == portal->nodes[1])
3629 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3630 if (portal->nodes[0] == node)
3632 else if (portal->nodes[1] == node)
3634 clipplane.dist = -clipplane.dist;
3635 VectorNegate(clipplane.normal, clipplane.normal);
3640 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3641 side = 0; // hush warning
3644 for (i = 0;i < nodeportal->numpoints*3;i++)
3645 frontpoints[i] = nodeportal->points[i];
3646 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);
3647 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3651 if (nodeportal->numpoints < 3)
3653 Con_Warn("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3654 nodeportal->numpoints = 0;
3656 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3658 Con_Warn("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3659 nodeportal->numpoints = 0;
3662 AddPortalToNodes(nodeportal, front, back);
3664 // split the portals of this node along this node's plane and assign them to the children of this node
3665 // (migrating the portals downward through the tree)
3666 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3668 if (portal->nodes[0] == portal->nodes[1])
3669 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3670 if (portal->nodes[0] == node)
3672 else if (portal->nodes[1] == node)
3676 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3677 side = 0; // hush warning
3679 nextportal = portal->next[side];
3680 if (!portal->numpoints)
3683 other_node = portal->nodes[!side];
3684 RemovePortalFromNodes(portal);
3686 // cut the portal into two portals, one on each side of the node plane
3687 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);
3689 if (!numfrontpoints)
3692 AddPortalToNodes(portal, back, other_node);
3694 AddPortalToNodes(portal, other_node, back);
3700 AddPortalToNodes(portal, front, other_node);
3702 AddPortalToNodes(portal, other_node, front);
3706 // the portal is split
3707 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3708 temp = splitportal->chain;
3709 *splitportal = *portal;
3710 splitportal->chain = temp;
3711 for (i = 0;i < numbackpoints*3;i++)
3712 splitportal->points[i] = backpoints[i];
3713 splitportal->numpoints = numbackpoints;
3714 for (i = 0;i < numfrontpoints*3;i++)
3715 portal->points[i] = frontpoints[i];
3716 portal->numpoints = numfrontpoints;
3720 AddPortalToNodes(portal, front, other_node);
3721 AddPortalToNodes(splitportal, back, other_node);
3725 AddPortalToNodes(portal, other_node, front);
3726 AddPortalToNodes(splitportal, other_node, back);
3730 Mod_Q1BSP_RecursiveNodePortals(front);
3731 Mod_Q1BSP_RecursiveNodePortals(back);
3733 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3736 static void Mod_Q1BSP_MakePortals(void)
3738 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3739 portalpointsbufferoffset = 0;
3740 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3741 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3742 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3743 Mem_Free(portalpointsbuffer);
3744 portalpointsbuffer = NULL;
3745 portalpointsbufferoffset = 0;
3746 portalpointsbuffersize = 0;
3747 Mod_Q1BSP_FinalizePortals();
3748 Mem_ExpandableArray_FreeArray(&portalarray);
3751 //Returns PVS data for a given point
3752 //(note: can return NULL)
3753 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3756 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3758 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3759 if (((mleaf_t *)node)->clusterindex >= 0)
3760 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3765 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)
3769 float d = PlaneDiff(org, node->plane);
3771 node = node->children[0];
3772 else if (d < -radius)
3773 node = node->children[1];
3776 // go down both sides
3777 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3778 node = node->children[1];
3781 // if this leaf is in a cluster, accumulate the pvs bits
3782 if (((mleaf_t *)node)->clusterindex >= 0)
3785 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3786 for (i = 0;i < pvsbytes;i++)
3787 pvsbuffer[i] |= pvs[i];
3791 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3792 //of the given point.
3793 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3795 int bytes = model->brush.num_pvsclusterbytes;
3796 bytes = min(bytes, pvsbufferlength);
3797 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3799 memset(pvsbuffer, 0xFF, bytes);
3803 memset(pvsbuffer, 0, bytes);
3804 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3808 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3813 VectorSubtract(inmaxs, inmins, size);
3814 if (cmodel->brush.ishlbsp)
3817 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3818 else if (size[0] <= 32)
3820 if (size[2] < 54) // pick the nearest of 36 or 72
3821 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3823 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3826 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3831 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3832 else if (size[0] <= 32)
3833 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3835 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3837 VectorCopy(inmins, outmins);
3838 VectorAdd(inmins, hull->clip_size, outmaxs);
3841 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, int skipmaterialflagsmask);
3843 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3846 sizebuf_t lumpsb[HEADER_LUMPS];
3848 float dist, modelyawradius, modelradius;
3849 msurface_t *surface;
3850 hullinfo_t hullinfo;
3851 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3852 model_brush_lightstyleinfo_t styleinfo[256];
3853 unsigned char *datapointer;
3856 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3858 mod->type = mod_brushq1;
3860 mod->brush.ishlbsp = false;
3861 mod->brush.isbsp2rmqe = false;
3862 mod->brush.isbsp2 = false;
3863 mod->brush.isq2bsp = false;
3864 mod->brush.isq3bsp = false;
3865 mod->brush.skymasking = true;
3866 i = MSG_ReadLittleLong(&sb);
3870 mod->modeldatatypestring = "Q1BSP";
3873 mod->brush.ishlbsp = true;
3874 mod->modeldatatypestring = "HLBSP";
3876 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3877 mod->brush.isbsp2 = true;
3878 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3879 mod->modeldatatypestring = "Q1BSP2rmqe";
3881 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3882 mod->brush.isbsp2 = true;
3883 mod->modeldatatypestring = "Q1BSP2";
3886 mod->modeldatatypestring = "Unknown BSP";
3887 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);
3891 // fill in hull info
3892 VectorClear (hullinfo.hullsizes[0][0]);
3893 VectorClear (hullinfo.hullsizes[0][1]);
3894 if (mod->brush.ishlbsp)
3896 hullinfo.filehulls = 4;
3897 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3898 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3899 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3900 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3901 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3902 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3906 hullinfo.filehulls = 4;
3907 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3908 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3909 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3910 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3914 for (i = 0; i < HEADER_LUMPS; i++)
3916 int offset = MSG_ReadLittleLong(&sb);
3917 int size = MSG_ReadLittleLong(&sb);
3918 if (offset < 0 || offset + size > sb.cursize)
3919 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);
3920 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3923 mod->soundfromcenter = true;
3924 mod->TraceBox = Mod_Q1BSP_TraceBox;
3925 mod->TraceLine = Mod_Q1BSP_TraceLine;
3926 mod->TracePoint = Mod_Q1BSP_TracePoint;
3927 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3928 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3929 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3930 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3931 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3932 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3933 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3934 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3935 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3936 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3937 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3938 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3939 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3940 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3941 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3942 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3943 mod->Draw = R_Q1BSP_Draw;
3944 mod->DrawDepth = R_Q1BSP_DrawDepth;
3945 mod->DrawDebug = R_Q1BSP_DrawDebug;
3946 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3947 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3948 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3949 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3950 mod->DrawLight = R_Q1BSP_DrawLight;
3954 mod->brush.qw_md4sum = 0;
3955 mod->brush.qw_md4sum2 = 0;
3956 for (i = 0;i < HEADER_LUMPS;i++)
3959 if (i == LUMP_ENTITIES)
3961 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3962 mod->brush.qw_md4sum ^= LittleLong(temp);
3963 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3965 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3968 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3969 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3970 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3971 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3972 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3973 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3974 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3975 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3976 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3977 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3978 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3979 // load submodels before leafs because they contain the number of vis leafs
3980 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3981 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3982 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3983 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3985 for (i = 0; i < HEADER_LUMPS; i++)
3986 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3987 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3989 // check if the map supports transparent water rendering
3990 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3992 // we don't need the compressed pvs data anymore
3993 if (mod->brushq1.data_compressedpvs)
3994 Mem_Free(mod->brushq1.data_compressedpvs);
3995 mod->brushq1.data_compressedpvs = NULL;
3996 mod->brushq1.num_compressedpvs = 0;
3998 Mod_Q1BSP_MakeHull0();
3999 if (mod_bsp_portalize.integer)
4000 Mod_Q1BSP_MakePortals();
4002 mod->numframes = 2; // regular and alternate animation
4005 if (loadmodel->brush.numsubmodels)
4006 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
4008 // LadyHavoc: to clear the fog around the original quake submodel code, I
4010 // first of all, some background info on the submodels:
4011 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
4012 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
4013 // now the weird for loop itself:
4014 // the loop functions in an odd way, on each iteration it sets up the
4015 // current 'mod' model (which despite the confusing code IS the model of
4016 // the number i), at the end of the loop it duplicates the model to become
4017 // the next submodel, and loops back to set up the new submodel.
4019 // LadyHavoc: now the explanation of my sane way (which works identically):
4020 // set up the world model, then on each submodel copy from the world model
4021 // and set up the submodel with the respective model info.
4022 totalstylesurfaces = 0;
4024 for (i = 0;i < mod->brush.numsubmodels;i++)
4026 memset(stylecounts, 0, sizeof(stylecounts));
4027 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4029 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4030 for (j = 0;j < MAXLIGHTMAPS;j++)
4031 stylecounts[surface->lightmapinfo->styles[j]]++;
4033 for (k = 0;k < 255;k++)
4037 totalstylesurfaces += stylecounts[k];
4040 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4041 for (i = 0;i < mod->brush.numsubmodels;i++)
4043 // LadyHavoc: this code was originally at the end of this loop, but
4044 // has been transformed to something more readable at the start here.
4049 // duplicate the basic information
4050 dpsnprintf(name, sizeof(name), "*%i", i);
4051 mod = Mod_FindName(name, loadmodel->name);
4052 // copy the base model to this one
4054 // rename the clone back to its proper name
4055 strlcpy(mod->name, name, sizeof(mod->name));
4056 mod->brush.parentmodel = loadmodel;
4057 // textures and memory belong to the main model
4058 mod->texturepool = NULL;
4059 mod->mempool = NULL;
4060 mod->brush.GetPVS = NULL;
4061 mod->brush.FatPVS = NULL;
4062 mod->brush.BoxTouchingPVS = NULL;
4063 mod->brush.BoxTouchingLeafPVS = NULL;
4064 mod->brush.BoxTouchingVisibleLeafs = NULL;
4065 mod->brush.FindBoxClusters = NULL;
4066 mod->brush.LightPoint = NULL;
4067 mod->brush.AmbientSoundLevelsForPoint = NULL;
4070 mod->brush.submodel = i;
4072 if (loadmodel->brush.submodels)
4073 loadmodel->brush.submodels[i] = mod;
4075 bm = &mod->brushq1.submodels[i];
4077 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4078 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4080 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4081 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4084 mod->firstmodelsurface = bm->firstface;
4085 mod->nummodelsurfaces = bm->numfaces;
4087 // set node/leaf parents for this submodel
4088 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4090 // this has to occur after hull info has been set, as it uses Mod_Q1BSP_PointSuperContents
4091 Mod_Q1BSP_AssignNoShadowSkySurfaces(mod);
4093 // make the model surface list (used by shadowing/lighting)
4094 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4095 Mod_MakeSortedSurfaces(mod);
4097 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4098 // (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)
4099 VectorCopy(bm->mins, mod->normalmins);
4100 VectorCopy(bm->maxs, mod->normalmaxs);
4101 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4102 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4103 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4104 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4105 modelradius = modelyawradius + modelradius * modelradius;
4106 modelyawradius = sqrt(modelyawradius);
4107 modelradius = sqrt(modelradius);
4108 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4109 mod->yawmins[2] = mod->normalmins[2];
4110 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4111 mod->yawmaxs[2] = mod->normalmaxs[2];
4112 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4113 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4114 mod->radius = modelradius;
4115 mod->radius2 = modelradius * modelradius;
4117 // this gets altered below if sky or water is used
4118 mod->DrawSky = NULL;
4119 mod->DrawAddWaterPlanes = NULL;
4121 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4122 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4123 if (mod->nummodelsurfaces)
4125 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4126 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4128 if (j < mod->nummodelsurfaces)
4129 mod->DrawSky = R_Q1BSP_DrawSky;
4131 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4132 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4134 if (j < mod->nummodelsurfaces)
4135 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4137 // build lightstyle update chains
4138 // (used to rapidly mark lightmapupdateflags on many surfaces
4139 // when d_lightstylevalue changes)
4140 memset(stylecounts, 0, sizeof(stylecounts));
4141 for (k = 0;k < mod->nummodelsurfaces;k++)
4143 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4144 for (j = 0;j < MAXLIGHTMAPS;j++)
4145 stylecounts[surface->lightmapinfo->styles[j]]++;
4147 mod->brushq1.num_lightstyles = 0;
4148 for (k = 0;k < 255;k++)
4152 styleinfo[mod->brushq1.num_lightstyles].style = k;
4153 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4154 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4155 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4156 remapstyles[k] = mod->brushq1.num_lightstyles;
4157 mod->brushq1.num_lightstyles++;
4160 for (k = 0;k < mod->nummodelsurfaces;k++)
4162 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4163 for (j = 0;j < MAXLIGHTMAPS;j++)
4165 if (surface->lightmapinfo->styles[j] != 255)
4167 int r = remapstyles[surface->lightmapinfo->styles[j]];
4168 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4172 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4173 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4177 // LadyHavoc: empty submodel(lacrima.bsp has such a glitch)
4178 Con_Warnf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4180 //mod->brushq1.num_visleafs = bm->visleafs;
4182 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4183 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4185 if (mod_q1bsp_polygoncollisions.integer)
4187 mod->collision_bih = mod->render_bih;
4188 // point traces and contents checks still use the bsp tree
4189 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4190 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4191 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4192 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4195 // generate VBOs and other shared data before cloning submodels
4199 Mod_Q1BSP_LoadMapBrushes();
4200 //Mod_Q1BSP_ProcessLightList();
4204 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);
4207 int Mod_Q2BSP_SuperContentsFromNativeContents(int nativecontents)
4209 int supercontents = 0;
4210 if (nativecontents & CONTENTSQ2_SOLID)
4211 supercontents |= SUPERCONTENTS_SOLID;
4212 if (nativecontents & CONTENTSQ2_WATER)
4213 supercontents |= SUPERCONTENTS_WATER;
4214 if (nativecontents & CONTENTSQ2_SLIME)
4215 supercontents |= SUPERCONTENTS_SLIME;
4216 if (nativecontents & CONTENTSQ2_LAVA)
4217 supercontents |= SUPERCONTENTS_LAVA;
4218 if (nativecontents & CONTENTSQ2_MONSTER)
4219 supercontents |= SUPERCONTENTS_BODY;
4220 if (nativecontents & CONTENTSQ2_DEADMONSTER)
4221 supercontents |= SUPERCONTENTS_CORPSE;
4222 if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4223 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4224 if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4225 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4226 if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4227 supercontents |= SUPERCONTENTS_OPAQUE;
4228 return supercontents;
4231 int Mod_Q2BSP_NativeContentsFromSuperContents(int supercontents)
4233 int nativecontents = 0;
4234 if (supercontents & SUPERCONTENTS_SOLID)
4235 nativecontents |= CONTENTSQ2_SOLID;
4236 if (supercontents & SUPERCONTENTS_WATER)
4237 nativecontents |= CONTENTSQ2_WATER;
4238 if (supercontents & SUPERCONTENTS_SLIME)
4239 nativecontents |= CONTENTSQ2_SLIME;
4240 if (supercontents & SUPERCONTENTS_LAVA)
4241 nativecontents |= CONTENTSQ2_LAVA;
4242 if (supercontents & SUPERCONTENTS_BODY)
4243 nativecontents |= CONTENTSQ2_MONSTER;
4244 if (supercontents & SUPERCONTENTS_CORPSE)
4245 nativecontents |= CONTENTSQ2_DEADMONSTER;
4246 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4247 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4248 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4249 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4250 if (!(supercontents & SUPERCONTENTS_OPAQUE))
4251 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4252 return nativecontents;
4255 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4258 loadmodel->brushq1.num_compressedpvs = 0;
4259 loadmodel->brushq1.data_compressedpvs = NULL;
4260 loadmodel->brush.num_pvsclusters = 0;
4261 loadmodel->brush.num_pvsclusterbytes = 0;
4262 loadmodel->brush.data_pvsclusters = NULL;
4267 count = MSG_ReadLittleLong(sb);
4268 loadmodel->brush.num_pvsclusters = count;
4269 loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4270 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4271 for (i = 0;i < count;i++)
4273 int pvsofs = MSG_ReadLittleLong(sb);
4274 /*int phsofs = */MSG_ReadLittleLong(sb);
4275 // decompress the vis data for this cluster
4276 // (note this accesses the underlying data store of sb, which is kind of evil)
4277 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);
4279 // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4280 sb->readcount = sb->cursize;
4283 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4285 int i, j, count, p, child[2];
4287 int structsize = 28;
4289 if (sb->cursize % structsize)
4290 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4291 count = sb->cursize / structsize;
4293 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4294 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4296 loadmodel->brush.data_nodes = out;
4297 loadmodel->brush.num_nodes = count;
4299 for ( i=0 ; i<count ; i++, out++)
4301 p = MSG_ReadLittleLong(sb);
4302 out->plane = loadmodel->brush.data_planes + p;
4303 child[0] = MSG_ReadLittleLong(sb);
4304 child[1] = MSG_ReadLittleLong(sb);
4305 out->mins[0] = MSG_ReadLittleShort(sb);
4306 out->mins[1] = MSG_ReadLittleShort(sb);
4307 out->mins[2] = MSG_ReadLittleShort(sb);
4308 out->maxs[0] = MSG_ReadLittleShort(sb);
4309 out->maxs[1] = MSG_ReadLittleShort(sb);
4310 out->maxs[2] = MSG_ReadLittleShort(sb);
4311 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4312 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4313 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4315 Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4316 out->firstsurface = 0;
4317 out->numsurfaces = 0;
4319 for (j=0 ; j<2 ; j++)
4324 if (p < loadmodel->brush.num_nodes)
4325 out->children[j] = loadmodel->brush.data_nodes + p;
4328 Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4329 // map it to the solid leaf
4330 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4335 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4337 if (p < loadmodel->brush.num_leafs)
4338 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4341 Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4342 // map it to the solid leaf
4343 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4349 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
4352 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4356 int structsize = 76;
4357 int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4358 char filename[MAX_QPATH];
4360 if (sb->cursize % structsize)
4361 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4362 count = sb->cursize / structsize;
4363 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4364 loadmodel->brushq1.texinfo = out;
4365 loadmodel->brushq1.numtexinfo = count;
4366 loadmodel->num_texturesperskin = 0;
4367 loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4369 for (i = 0;i < count;i++, out++)
4372 for (k = 0;k < 2;k++)
4373 for (j = 0;j < 4;j++)
4374 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4376 out->q2flags = MSG_ReadLittleLong(sb);
4377 out->q2value = MSG_ReadLittleLong(sb);
4378 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4379 out->q2texture[31] = 0; // make absolutely sure it is terminated
4380 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4382 // find an existing match for the texture if possible
4383 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4384 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4385 if (!strcmp(filename, loadmodel->data_textures[j].name)
4386 && out->q2flags == loadmodel->data_textures[j].q2flags
4387 && out->q2value == loadmodel->data_textures[j].q2value)
4389 // if we don't find the texture, store the new texture
4390 if (j == loadmodel->num_texturesperskin)
4392 if (loadmodel->num_texturesperskin < maxtextures)
4394 texture_t *tx = loadmodel->data_textures + j;
4395 int q2flags = out->q2flags;
4396 unsigned char *walfile = NULL;
4397 fs_offset_t walfilesize = 0;
4398 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
4399 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4400 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4404 LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4414 tx->q2flags = out->q2flags;
4415 tx->q2value = out->q2value;
4416 // also modify the texture to have the correct contents and such based on flags
4417 // note that we create multiple texture_t structures if q2flags differs
4418 if (q2flags & Q2SURF_LIGHT)
4420 // doesn't mean anything to us
4422 if (q2flags & Q2SURF_SLICK)
4424 // would be nice to support...
4426 if (q2flags & Q2SURF_SKY)
4428 // sky is a rather specific thing
4429 q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4430 tx->basematerialflags = MATERIALFLAG_SKY;
4431 tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4432 tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4434 if (q2flags & Q2SURF_WARP)
4436 // we use a scroll instead of a warp
4437 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4438 // if it's also transparent, we can enable the WATERSHADER
4439 // but we do not set the WATERALPHA flag because we don't
4440 // want to honor r_wateralpha in q2bsp
4441 // (it would go against the artistic intent)
4442 if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4443 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4445 if (q2flags & Q2SURF_TRANS33)
4447 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4448 tx->basealpha = 1.0f / 3.0f;
4449 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4450 if (tx->q2contents & Q2CONTENTS_SOLID)
4451 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4453 if (q2flags & Q2SURF_TRANS66)
4455 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4456 tx->basealpha = 2.0f / 3.0f;
4457 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4458 if (tx->q2contents & Q2CONTENTS_SOLID)
4459 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4461 if ((q2flags & Q2SURF_FLOWING) && tx->materialshaderpass != NULL)
4463 tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4464 if (q2flags & Q2SURF_WARP)
4465 tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
4467 tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
4468 tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
4470 if (q2flags & Q2SURF_ALPHATEST)
4472 // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4473 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4475 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4477 if (!mod_q2bsp_littransparentsurfaces.integer)
4478 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4480 if (q2flags & Q2SURF_NODRAW)
4482 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4484 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4485 tx->q2contents |= Q2CONTENTS_DETAIL;
4486 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4487 tx->q2contents |= Q2CONTENTS_SOLID;
4488 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4490 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(tx->q2contents);
4491 // set the current values to the base values
4492 tx->currentframe = tx;
4493 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
4494 tx->currentmaterialflags = tx->basematerialflags;
4495 loadmodel->num_texturesperskin++;
4496 loadmodel->num_textures = loadmodel->num_texturesperskin;
4500 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4501 j = 0; // use first texture and give up
4504 // store the index we found for this texture
4505 out->textureindex = j;
4508 // realloc the textures array now that we know how many we actually need
4509 loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4511 // now assemble the texture chains
4512 // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier
4513 for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4516 texture_t *t = loadmodel->data_textures + out->textureindex;
4517 t->currentframe = t; // fix the reallocated pointer
4519 // if this is not animated, skip it
4520 // if this is already processed, skip it (part of an existing sequence)
4521 if (out->q2nexttexinfo == 0 || t->animated)
4524 // store the array of frames to use
4525 t->animated = 2; // q2bsp animation
4526 t->anim_total[0] = 0;
4527 t->anim_total[1] = 0;
4528 // gather up to 10 frames (we don't support more)
4529 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)
4531 // detect looping and stop there
4532 if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4534 t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4536 // we could look for the +a sequence here if this is the +0 sequence,
4537 // but it seems that quake2 did not implement that (even though the
4538 // files exist in the baseq2 content)
4540 // write the frame sequence to all the textures involved (just like
4541 // in the q1bsp loader)
4543 // note that this can overwrite the rest of the sequence - so if the
4544 // start of a sequence is found later than the other parts of the
4545 // sequence, it will go back and rewrite them correctly.
4546 for (k = 0;k < t->anim_total[0];k++)
4548 texture_t *txk = t->anim_frames[0][k];
4549 txk->animated = t->animated;
4550 txk->anim_total[0] = t->anim_total[0];
4551 for (l = 0;l < t->anim_total[0];l++)
4552 txk->anim_frames[0][l] = t->anim_frames[0][l];
4557 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4559 // LadyHavoc: this fits exactly the same format that we use in .lit files
4560 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4561 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4564 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4567 int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4568 int structsize = 28;
4570 if (sb->cursize % structsize)
4571 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4572 count = sb->cursize / structsize;
4573 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4575 loadmodel->brush.data_leafs = out;
4576 loadmodel->brush.num_leafs = count;
4578 // FIXME: this function could really benefit from some error checking
4579 for ( i=0 ; i<count ; i++, out++)
4581 out->contents = MSG_ReadLittleLong(sb);
4582 out->clusterindex = MSG_ReadLittleShort(sb);
4583 out->areaindex = MSG_ReadLittleShort(sb);
4584 out->mins[0] = MSG_ReadLittleShort(sb);
4585 out->mins[1] = MSG_ReadLittleShort(sb);
4586 out->mins[2] = MSG_ReadLittleShort(sb);
4587 out->maxs[0] = MSG_ReadLittleShort(sb);
4588 out->maxs[1] = MSG_ReadLittleShort(sb);
4589 out->maxs[2] = MSG_ReadLittleShort(sb);
4591 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4592 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4593 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4594 nummarkbrushes = (unsigned short)MSG_ReadLittleShort(sb);
4596 for (j = 0;j < 4;j++)
4597 out->ambient_sound_level[j] = 0;
4599 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4601 Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4602 out->clusterindex = -1;
4605 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4607 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4608 out->numleafsurfaces = nummarksurfaces;
4612 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4613 out->firstleafsurface = NULL;
4614 out->numleafsurfaces = 0;
4617 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4619 out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4620 out->numleafbrushes = nummarkbrushes;
4624 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4625 out->firstleafbrush = NULL;
4626 out->numleafbrushes = 0;
4631 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4636 if (sb->cursize % structsize)
4637 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4638 loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4639 loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4641 for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4643 j = (unsigned short) MSG_ReadLittleShort(sb);
4644 if (j >= loadmodel->brush.num_brushes)
4645 Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4646 loadmodel->brush.data_leafbrushes[i] = j;
4650 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4652 q3mbrushside_t *out;
4656 if (sb->cursize % structsize)
4657 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4658 count = sb->cursize / structsize;
4659 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4661 loadmodel->brush.data_brushsides = out;
4662 loadmodel->brush.num_brushsides = count;
4664 for (i = 0;i < count;i++, out++)
4666 n = (unsigned short)MSG_ReadLittleShort(sb);
4667 if (n < 0 || n >= loadmodel->brush.num_planes)
4668 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4669 out->plane = loadmodel->brush.data_planes + n;
4670 n = MSG_ReadLittleShort(sb);
4673 if (n >= loadmodel->brushq1.numtexinfo)
4674 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4675 out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4679 //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4680 out->texture = &mod_q1bsp_texture_solid;
4685 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4688 int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4689 colplanef_t *planes;
4690 int structsize = 12;
4691 qboolean brushmissingtextures;
4692 int numbrushesmissingtextures = 0;
4693 int numcreatedtextures = 0;
4695 if (sb->cursize % structsize)
4696 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4697 count = sb->cursize / structsize;
4698 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4700 loadmodel->brush.data_brushes = out;
4701 loadmodel->brush.num_brushes = count;
4706 for (i = 0; i < count; i++, out++)
4708 firstside = MSG_ReadLittleLong(sb);
4709 numsides = MSG_ReadLittleLong(sb);
4710 contents = MSG_ReadLittleLong(sb);
4711 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4712 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4714 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4715 out->numbrushsides = numsides;
4716 // convert the contents to our values
4717 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(contents);
4719 // problem: q2bsp brushes have contents but not a texture
4720 // problem: q2bsp brushsides *may* have a texture or may not
4721 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4722 // solution: nasty hacks
4723 brushmissingtextures = false;
4724 out->texture = NULL;
4725 for (j = 0; j < out->numbrushsides; j++)
4727 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4728 brushmissingtextures = true;
4731 // if we can find a matching texture on a brush side we can use it instead of creating one
4732 if (out->firstbrushside[j].texture->supercontents == supercontents)
4733 out->texture = out->firstbrushside[j].texture;
4736 if (brushmissingtextures || out->texture == NULL)
4738 numbrushesmissingtextures++;
4739 // if we didn't find any appropriate texture (matching contents), we'll have to create one
4740 // we could search earlier ones for a matching one but that can be slow
4741 if (out->texture == NULL)
4743 texture_t *validtexture;
4744 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4745 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4746 validtexture->surfaceflags = 0;
4747 validtexture->supercontents = supercontents;
4748 numcreatedtextures++;
4749 out->texture = validtexture;
4751 // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4752 for (j = 0; j < out->numbrushsides; j++)
4753 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4754 out->firstbrushside[j].texture = out->texture;
4757 // make a colbrush from the brush
4759 // make a list of mplane_t structs to construct a colbrush from
4760 if (maxplanes < out->numbrushsides)
4762 maxplanes = out->numbrushsides;
4765 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4767 for (j = 0;j < out->numbrushsides;j++)
4769 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4770 planes[j].dist = out->firstbrushside[j].plane->dist;
4771 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4772 planes[j].texture = out->firstbrushside[j].texture;
4773 q3surfaceflags |= planes[j].q3surfaceflags;
4775 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4777 // this whole loop can take a while (e.g. on redstarrepublic4)
4778 CL_KeepaliveMessage(false);
4782 if (numcreatedtextures)
4783 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);
4786 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4788 // 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)
4789 sb->readcount = sb->cursize;
4792 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4794 // we currently don't use areas, they represent closable doors as vis blockers
4795 sb->readcount = sb->cursize;
4798 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4800 // we currently don't use areas, they represent closable doors as vis blockers
4801 sb->readcount = sb->cursize;
4804 static void Mod_Q2BSP_LoadSubmodels(sizebuf_t *sb)
4808 int structsize = 48;
4810 if (sb->cursize % structsize)
4811 Host_Error ("Mod_Q2BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
4813 count = sb->cursize / structsize;
4814 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
4816 loadmodel->brushq1.submodels = out;
4817 loadmodel->brush.numsubmodels = count;
4819 // this is identical to the q1 submodel structure except for having 1 hull
4820 for (i = 0; i < count; i++, out++)
4822 // spread out the mins / maxs by a pixel
4823 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
4824 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
4825 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
4826 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
4827 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
4828 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
4829 out->origin[0] = MSG_ReadLittleFloat(sb);
4830 out->origin[1] = MSG_ReadLittleFloat(sb);
4831 out->origin[2] = MSG_ReadLittleFloat(sb);
4832 out->headnode[0] = MSG_ReadLittleLong(sb);
4833 out->firstface = MSG_ReadLittleLong(sb);
4834 out->numfaces = MSG_ReadLittleLong(sb);
4838 static void Mod_Q2BSP_FindSubmodelBrushRange_r(dp_model_t *mod, mnode_t *node, int *first, int *last)
4844 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4845 node = node->children[1];
4847 leaf = (mleaf_t*)node;
4848 for (i = 0;i < leaf->numleafbrushes;i++)
4850 int brushnum = leaf->firstleafbrush[i];
4851 if (*first > brushnum)
4853 if (*last < brushnum)
4858 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4861 sizebuf_t lumpsb[Q2HEADER_LUMPS];
4863 float dist, modelyawradius, modelradius;
4864 msurface_t *surface;
4865 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4866 model_brush_lightstyleinfo_t styleinfo[256];
4867 unsigned char *datapointer;
4870 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4872 mod->type = mod_brushq2;
4874 mod->brush.ishlbsp = false;
4875 mod->brush.isbsp2rmqe = false;
4876 mod->brush.isbsp2 = false;
4877 mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4878 mod->brush.isq3bsp = false;
4879 mod->brush.skymasking = true;
4880 mod->modeldatatypestring = "Q2BSP";
4882 i = MSG_ReadLittleLong(&sb);
4883 if (i != Q2BSPMAGIC)
4884 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4886 i = MSG_ReadLittleLong(&sb);
4887 if (i != Q2BSPVERSION)
4888 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4891 for (i = 0; i < Q2HEADER_LUMPS; i++)
4893 int offset = MSG_ReadLittleLong(&sb);
4894 int size = MSG_ReadLittleLong(&sb);
4895 if (offset < 0 || offset + size > sb.cursize)
4896 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);
4897 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4900 mod->soundfromcenter = true;
4901 mod->TracePoint = Mod_CollisionBIH_TracePoint;
4902 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4903 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4904 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4905 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4906 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4907 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4908 mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4909 mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4910 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
4911 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
4912 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
4913 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
4914 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
4915 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
4916 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
4917 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
4918 mod->brush.AmbientSoundLevelsForPoint = NULL;
4919 mod->brush.RoundUpToHullSize = NULL;
4920 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
4921 mod->Draw = R_Q1BSP_Draw;
4922 mod->DrawDepth = R_Q1BSP_DrawDepth;
4923 mod->DrawDebug = R_Q1BSP_DrawDebug;
4924 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
4925 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
4926 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
4927 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
4928 mod->DrawLight = R_Q1BSP_DrawLight;
4932 mod->brush.qw_md4sum = 0;
4933 mod->brush.qw_md4sum2 = 0;
4934 for (i = 0;i < Q2HEADER_LUMPS;i++)
4937 if (i == Q2LUMP_ENTITIES)
4939 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4940 mod->brush.qw_md4sum ^= LittleLong(temp);
4941 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4943 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4946 // many of these functions are identical to Q1 loaders, so we use those where possible
4947 Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4948 Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4949 Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4950 Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4951 Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4952 Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4953 Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4954 Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4955 Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4956 Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4957 Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4958 Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4959 Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4960 Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4961 Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4962 Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4963 Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4964 Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4965 Mod_Q2BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS]);
4967 for (i = 0; i < Q2HEADER_LUMPS; i++)
4968 if (lumpsb[i].readcount != lumpsb[i].cursize)
4969 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4971 // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4972 // doesn't enable the cvar, just indicates that transparent water is OK
4973 loadmodel->brush.supportwateralpha = true;
4975 // we don't need the compressed pvs data anymore
4976 if (mod->brushq1.data_compressedpvs)
4977 Mem_Free(mod->brushq1.data_compressedpvs);
4978 mod->brushq1.data_compressedpvs = NULL;
4979 mod->brushq1.num_compressedpvs = 0;
4981 // the MakePortals code works fine on the q2bsp data as well
4982 if (mod_bsp_portalize.integer)
4983 Mod_Q1BSP_MakePortals();
4985 mod->numframes = 0; // q2bsp animations are kind of special, frame is unbounded...
4988 if (loadmodel->brush.numsubmodels)
4989 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
4991 totalstylesurfaces = 0;
4993 for (i = 0;i < mod->brush.numsubmodels;i++)
4995 memset(stylecounts, 0, sizeof(stylecounts));
4996 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4998 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4999 for (j = 0;j < MAXLIGHTMAPS;j++)
5000 stylecounts[surface->lightmapinfo->styles[j]]++;
5002 for (k = 0;k < 255;k++)
5006 totalstylesurfaces += stylecounts[k];
5009 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
5010 // set up the world model, then on each submodel copy from the world model
5011 // and set up the submodel with the respective model info.
5013 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
5015 mnode_t *rootnode = NULL;
5016 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
5020 // duplicate the basic information
5021 dpsnprintf(name, sizeof(name), "*%i", i);
5022 mod = Mod_FindName(name, loadmodel->name);
5023 // copy the base model to this one
5025 // rename the clone back to its proper name
5026 strlcpy(mod->name, name, sizeof(mod->name));
5027 mod->brush.parentmodel = loadmodel;
5028 // textures and memory belong to the main model
5029 mod->texturepool = NULL;
5030 mod->mempool = NULL;
5031 mod->brush.GetPVS = NULL;
5032 mod->brush.FatPVS = NULL;
5033 mod->brush.BoxTouchingPVS = NULL;
5034 mod->brush.BoxTouchingLeafPVS = NULL;
5035 mod->brush.BoxTouchingVisibleLeafs = NULL;
5036 mod->brush.FindBoxClusters = NULL;
5037 mod->brush.LightPoint = NULL;
5038 mod->brush.AmbientSoundLevelsForPoint = NULL;
5040 mod->brush.submodel = i;
5041 if (loadmodel->brush.submodels)
5042 loadmodel->brush.submodels[i] = mod;
5044 bm = &mod->brushq1.submodels[i];
5046 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5047 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5049 mod->firstmodelsurface = bm->firstface;
5050 mod->nummodelsurfaces = bm->numfaces;
5052 // set node/leaf parents for this submodel
5053 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5054 // (this happens in base3.bsp)
5055 if (bm->headnode[0] >= 0)
5056 rootnode = mod->brush.data_nodes + bm->headnode[0];
5058 rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5059 Mod_Q1BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5061 // make the model surface list (used by shadowing/lighting)
5062 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
5063 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5064 if (firstbrush <= lastbrush)
5066 mod->firstmodelbrush = firstbrush;
5067 mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5071 mod->firstmodelbrush = 0;
5072 mod->nummodelbrushes = 0;
5074 Mod_MakeSortedSurfaces(mod);
5076 VectorCopy(bm->mins, mod->normalmins);
5077 VectorCopy(bm->maxs, mod->normalmaxs);
5078 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5079 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5080 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5081 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5082 modelradius = modelyawradius + modelradius * modelradius;
5083 modelyawradius = sqrt(modelyawradius);
5084 modelradius = sqrt(modelradius);
5085 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5086 mod->yawmins[2] = mod->normalmins[2];
5087 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
5088 mod->yawmaxs[2] = mod->normalmaxs[2];
5089 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5090 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5091 mod->radius = modelradius;
5092 mod->radius2 = modelradius * modelradius;
5094 // this gets altered below if sky or water is used
5095 mod->DrawSky = NULL;
5096 mod->DrawAddWaterPlanes = NULL;
5098 // scan surfaces for sky and water and flag the submodel as possessing these features or not
5099 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5100 if (mod->nummodelsurfaces)
5102 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5103 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
5105 if (j < mod->nummodelsurfaces)
5106 mod->DrawSky = R_Q1BSP_DrawSky;
5108 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5109 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
5111 if (j < mod->nummodelsurfaces)
5112 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
5114 // build lightstyle update chains
5115 // (used to rapidly mark lightmapupdateflags on many surfaces
5116 // when d_lightstylevalue changes)
5117 memset(stylecounts, 0, sizeof(stylecounts));
5118 for (k = 0;k < mod->nummodelsurfaces;k++)
5120 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5121 for (j = 0;j < MAXLIGHTMAPS;j++)
5122 stylecounts[surface->lightmapinfo->styles[j]]++;
5124 mod->brushq1.num_lightstyles = 0;
5125 for (k = 0;k < 255;k++)
5129 styleinfo[mod->brushq1.num_lightstyles].style = k;
5130 styleinfo[mod->brushq1.num_lightstyles].value = 0;
5131 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5132 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
5133 remapstyles[k] = mod->brushq1.num_lightstyles;
5134 mod->brushq1.num_lightstyles++;
5137 for (k = 0;k < mod->nummodelsurfaces;k++)
5139 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5140 for (j = 0;j < MAXLIGHTMAPS;j++)
5142 if (surface->lightmapinfo->styles[j] != 255)
5144 int r = remapstyles[surface->lightmapinfo->styles[j]];
5145 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
5149 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
5150 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5154 Con_Warnf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5156 //mod->brushq1.num_visleafs = bm->visleafs;
5158 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5159 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5161 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5162 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5164 // generate VBOs and other shared data before cloning submodels
5170 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);
5173 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents);
5174 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents);
5176 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5179 char key[128], value[MAX_INPUTLINE];
5181 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5182 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5183 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5186 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5187 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5188 loadmodel->brush.entities[l->filelen] = 0;
5189 data = loadmodel->brush.entities;
5190 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5191 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5192 loadmodel->brushq3.deluxemapping = false;
5193 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5197 if (!COM_ParseToken_Simple(&data, false, false, true))
5199 if (com_token[0] == '}')
5200 break; // end of worldspawn
5201 if (com_token[0] == '_')
5202 strlcpy(key, com_token + 1, sizeof(key));
5204 strlcpy(key, com_token, sizeof(key));
5205 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5206 key[strlen(key)-1] = 0;
5207 if (!COM_ParseToken_Simple(&data, false, false, true))
5209 strlcpy(value, com_token, sizeof(value));
5210 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5212 #if _MSC_VER >= 1400
5213 #define sscanf sscanf_s
5216 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5217 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5219 VectorSet(v, 64, 64, 128);
5220 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5221 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]);
5222 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5223 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5226 else if (!strcmp("deluxeMaps", key))
5228 if (!strcmp(com_token, "1"))
5230 loadmodel->brushq3.deluxemapping = true;
5231 loadmodel->brushq3.deluxemapping_modelspace = true;
5233 else if (!strcmp(com_token, "2"))
5235 loadmodel->brushq3.deluxemapping = true;
5236 loadmodel->brushq3.deluxemapping_modelspace = false;
5243 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5249 in = (q3dtexture_t *)(mod_base + l->fileofs);
5250 if (l->filelen % sizeof(*in))
5251 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5252 count = l->filelen / sizeof(*in);
5253 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5255 loadmodel->data_textures = out;
5256 loadmodel->num_textures = count;
5257 loadmodel->num_texturesperskin = loadmodel->num_textures;
5259 for (i = 0;i < count;i++)
5261 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5262 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5263 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
5264 // restore the surfaceflags and supercontents
5265 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5266 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5270 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5276 in = (q3dplane_t *)(mod_base + l->fileofs);
5277 if (l->filelen % sizeof(*in))
5278 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5279 count = l->filelen / sizeof(*in);
5280 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5282 loadmodel->brush.data_planes = out;
5283 loadmodel->brush.num_planes = count;
5285 for (i = 0;i < count;i++, in++, out++)
5287 out->normal[0] = LittleFloat(in->normal[0]);
5288 out->normal[1] = LittleFloat(in->normal[1]);
5289 out->normal[2] = LittleFloat(in->normal[2]);
5290 out->dist = LittleFloat(in->dist);
5295 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5298 q3mbrushside_t *out;
5301 in = (q3dbrushside_t *)(mod_base + l->fileofs);
5302 if (l->filelen % sizeof(*in))
5303 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5304 count = l->filelen / sizeof(*in);
5305 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5307 loadmodel->brush.data_brushsides = out;
5308 loadmodel->brush.num_brushsides = count;
5310 for (i = 0;i < count;i++, in++, out++)
5312 n = LittleLong(in->planeindex);
5313 if (n < 0 || n >= loadmodel->brush.num_planes)
5314 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5315 out->plane = loadmodel->brush.data_planes + n;
5316 n = LittleLong(in->textureindex);
5317 if (n < 0 || n >= loadmodel->num_textures)
5318 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5319 out->texture = loadmodel->data_textures + n;
5323 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5325 q3dbrushside_ig_t *in;
5326 q3mbrushside_t *out;
5329 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5330 if (l->filelen % sizeof(*in))
5331 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5332 count = l->filelen / sizeof(*in);
5333 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5335 loadmodel->brush.data_brushsides = out;
5336 loadmodel->brush.num_brushsides = count;
5338 for (i = 0;i < count;i++, in++, out++)
5340 n = LittleLong(in->planeindex);
5341 if (n < 0 || n >= loadmodel->brush.num_planes)
5342 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5343 out->plane = loadmodel->brush.data_planes + n;
5344 n = LittleLong(in->textureindex);
5345 if (n < 0 || n >= loadmodel->num_textures)
5346 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5347 out->texture = loadmodel->data_textures + n;
5351 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5355 int i, j, n, c, count, maxplanes, q3surfaceflags;
5356 colplanef_t *planes;
5358 in = (q3dbrush_t *)(mod_base + l->fileofs);
5359 if (l->filelen % sizeof(*in))
5360 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5361 count = l->filelen / sizeof(*in);
5362 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5364 loadmodel->brush.data_brushes = out;
5365 loadmodel->brush.num_brushes = count;
5370 for (i = 0;i < count;i++, in++, out++)
5372 n = LittleLong(in->firstbrushside);
5373 c = LittleLong(in->numbrushsides);
5374 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5375 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5376 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5377 out->numbrushsides = c;
5378 n = LittleLong(in->textureindex);
5379 if (n < 0 || n >= loadmodel->num_textures)
5380 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5381 out->texture = loadmodel->data_textures + n;
5383 // make a list of mplane_t structs to construct a colbrush from
5384 if (maxplanes < out->numbrushsides)
5386 maxplanes = out->numbrushsides;
5389 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5392 for (j = 0;j < out->numbrushsides;j++)
5394 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5395 planes[j].dist = out->firstbrushside[j].plane->dist;
5396 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5397 planes[j].texture = out->firstbrushside[j].texture;
5398 q3surfaceflags |= planes[j].q3surfaceflags;
5400 // make the colbrush from the planes
5401 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5403 // this whole loop can take a while (e.g. on redstarrepublic4)
5404 CL_KeepaliveMessage(false);
5410 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5416 in = (q3deffect_t *)(mod_base + l->fileofs);
5417 if (l->filelen % sizeof(*in))
5418 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5419 count = l->filelen / sizeof(*in);
5420 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5422 loadmodel->brushq3.data_effects = out;
5423 loadmodel->brushq3.num_effects = count;
5425 for (i = 0;i < count;i++, in++, out++)
5427 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5428 n = LittleLong(in->brushindex);
5429 if (n >= loadmodel->brush.num_brushes)
5431 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5434 out->brushindex = n;
5435 out->unknown = LittleLong(in->unknown);
5439 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5444 in = (q3dvertex_t *)(mod_base + l->fileofs);
5445 if (l->filelen % sizeof(*in))
5446 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5447 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5448 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5449 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5450 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5451 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5452 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5454 for (i = 0;i < count;i++, in++)
5456 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5457 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5458 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5459 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5460 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5461 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5462 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5463 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5464 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5465 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5466 // svector/tvector are calculated later in face loading
5467 if(mod_q3bsp_sRGBlightmaps.integer)
5469 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5470 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5471 // working like this may be odd, but matches q3map2 -gamma 2.2
5472 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5474 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5475 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5476 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5477 // we fix the brightness consistently via lightmapscale
5481 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5482 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5483 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5488 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5490 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5491 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5492 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5496 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5497 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5498 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5501 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5502 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5503 loadmodel->lit = true;
5507 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5513 in = (int *)(mod_base + l->fileofs);
5514 if (l->filelen % sizeof(int[3]))
5515 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5516 count = l->filelen / sizeof(*in);
5518 if(!loadmodel->brushq3.num_vertices)
5521 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5522 loadmodel->brushq3.num_triangles = 0;
5526 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5527 loadmodel->brushq3.num_triangles = count / 3;
5528 loadmodel->brushq3.data_element3i = out;
5530 for (i = 0;i < count;i++, in++, out++)
5532 *out = LittleLong(*in);
5533 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5535 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5541 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5543 q3dlightmap_t *input_pointer;
5561 int mergedrowsxcolumns;
5566 unsigned char *mergedpixels;
5567 unsigned char *mergeddeluxepixels;
5568 unsigned char *mergebuf;
5569 char mapname[MAX_QPATH];
5571 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5574 // defaults for q3bsp
5581 loadmodel->brushq3.lightmapsize = 128;
5583 if (cls.state == ca_dedicated)
5586 if(mod_q3bsp_nolightmaps.integer)
5592 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5593 if (developer_loading.integer)
5594 Con_Printf("Using internal lightmaps\n");
5595 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5596 if (l->filelen % sizeof(*input_pointer))
5597 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5598 count = l->filelen / sizeof(*input_pointer);
5599 for(i = 0; i < count; ++i)
5600 inpixels[i] = input_pointer[i].rgb;
5604 // no internal lightmaps
5605 // try external lightmaps
5606 if (developer_loading.integer)
5607 Con_Printf("Using external lightmaps\n");
5608 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5609 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5613 // using EXTERNAL lightmaps instead
5614 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5616 Mem_Free(inpixels[0]);
5617 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5627 for(count = 1; ; ++count)
5629 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5630 if(!inpixels[count])
5631 break; // we got all of them
5632 if(image_width != size || image_height != size)
5634 Mem_Free(inpixels[count]);
5635 inpixels[count] = NULL;
5636 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);
5642 loadmodel->brushq3.lightmapsize = size;
5643 loadmodel->brushq3.num_originallightmaps = count;
5645 // now check the surfaces to see if any of them index an odd numbered
5646 // lightmap, if so this is not a deluxemapped bsp file
5648 // also check what lightmaps are actually used, because q3map2 sometimes
5649 // (always?) makes an unused one at the end, which
5650 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5651 // reason when only one lightmap is used, which can throw off the
5652 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5653 // to see if the second lightmap is blank, if so it is not deluxemapped.
5654 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5655 // in Mod_Q3BSP_LoadEntities was failed
5656 if (!loadmodel->brushq3.deluxemapping)
5658 loadmodel->brushq3.deluxemapping = !(count & 1);
5659 loadmodel->brushq3.deluxemapping_modelspace = true;
5661 if (loadmodel->brushq3.deluxemapping)
5663 int facecount = faceslump->filelen / sizeof(q3dface_t);
5664 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5665 for (i = 0;i < facecount;i++)
5667 j = LittleLong(faces[i].lightmapindex);
5670 endlightmap = max(endlightmap, j + 1);
5671 if ((j & 1) || j + 1 >= count)
5673 loadmodel->brushq3.deluxemapping = false;
5680 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5681 // reason when only one lightmap is used, which can throw off the
5682 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5683 // to see if the second lightmap is blank, if so it is not deluxemapped.
5685 // further research has shown q3map2 sometimes creates a deluxemap and two
5686 // blank lightmaps, which must be handled properly as well
5687 if (endlightmap == 1 && count > 1)
5690 for (i = 0;i < size*size;i++)
5692 if (c[bytesperpixel*i + rgbmap[0]])
5694 if (c[bytesperpixel*i + rgbmap[1]])
5696 if (c[bytesperpixel*i + rgbmap[2]])
5701 // all pixels in the unused lightmap were black...
5702 loadmodel->brushq3.deluxemapping = false;
5707 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5709 // figure out what the most reasonable merge power is within limits
5711 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5712 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5714 // figure out how big the merged texture has to be
5715 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5716 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5717 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5719 mergedwidth = mergegoal;
5720 mergedheight = mergegoal;
5721 // choose non-square size (2x1 aspect) if only half the space is used;
5722 // this really only happens when the entire set fits in one texture, if
5723 // there are multiple textures, we don't worry about shrinking the last
5724 // one to fit, because the driver prefers the same texture size on
5725 // consecutive draw calls...
5726 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5729 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5730 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5731 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5732 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5733 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5734 loadmodel->brushq3.num_lightmapmergedheightpower++;
5735 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5737 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5738 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5739 powerxy = powerx+powery;
5740 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5742 mergedcolumns = 1 << powerx;
5743 mergedrows = 1 << powery;
5744 mergedrowsxcolumns = 1 << powerxy;
5746 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5747 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5748 if (loadmodel->brushq3.deluxemapping)
5749 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5751 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5752 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5753 for (i = 0;i < count;i++)
5755 // figure out which merged lightmap texture this fits into
5756 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5757 lightmapindex = i >> powerdxy;
5759 // choose the destination address
5760 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5761 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5762 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5763 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);
5765 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5766 for (j = 0;j < size;j++)
5767 for (k = 0;k < size;k++)
5769 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5770 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5771 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5772 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5775 // upload texture if this was the last tile being written to the texture
5776 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5778 if (loadmodel->brushq3.deluxemapping && (i & 1))
5779 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);
5782 if(mod_q3bsp_sRGBlightmaps.integer)
5785 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5787 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5788 // we fix the brightness consistently via lightmapscale
5791 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5792 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);
5796 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5797 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5798 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);
5804 if (mergeddeluxepixels)
5805 Mem_Free(mergeddeluxepixels);
5806 Mem_Free(mergedpixels);
5809 for(i = 0; i < count; ++i)
5810 Mem_Free(inpixels[i]);
5814 typedef struct patchtess_s
5818 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5821 float *originalvertex3f;
5824 #define PATCHTESS_SAME_LODGROUP(a,b) \
5826 (a).lodgroup[0] == (b).lodgroup[0] && \
5827 (a).lodgroup[1] == (b).lodgroup[1] && \
5828 (a).lodgroup[2] == (b).lodgroup[2] && \
5829 (a).lodgroup[3] == (b).lodgroup[3] && \
5830 (a).lodgroup[4] == (b).lodgroup[4] && \
5831 (a).lodgroup[5] == (b).lodgroup[5] \
5834 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5836 q3dface_t *in, *oldin;
5837 msurface_t *out, *oldout;
5838 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;
5839 float lightmaptcbase[2], lightmaptcscale[2];
5840 //int *originalelement3i;
5841 float *originalvertex3f;
5842 //float *originalsvector3f;
5843 //float *originaltvector3f;
5844 float *originalnormal3f;
5845 float *originalcolor4f;
5846 float *originaltexcoordtexture2f;
5847 float *originaltexcoordlightmap2f;
5848 float *surfacecollisionvertex3f;
5849 int *surfacecollisionelement3i;
5851 patchtess_t *patchtess = NULL;
5852 int patchtesscount = 0;
5855 in = (q3dface_t *)(mod_base + l->fileofs);
5856 if (l->filelen % sizeof(*in))
5857 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5858 count = l->filelen / sizeof(*in);
5859 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5861 loadmodel->data_surfaces = out;
5862 loadmodel->num_surfaces = count;
5865 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5873 for (;i < count;i++, in++, out++)
5875 // check face type first
5876 type = LittleLong(in->type);
5877 if (type != Q3FACETYPE_FLAT
5878 && type != Q3FACETYPE_PATCH
5879 && type != Q3FACETYPE_MESH
5880 && type != Q3FACETYPE_FLARE)
5882 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5886 n = LittleLong(in->textureindex);
5887 if (n < 0 || n >= loadmodel->num_textures)
5889 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5892 out->texture = loadmodel->data_textures + n;
5893 n = LittleLong(in->effectindex);
5894 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5896 if (developer_extra.integer)
5897 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5903 out->effect = loadmodel->brushq3.data_effects + n;
5905 if (cls.state != ca_dedicated)
5907 out->lightmaptexture = NULL;
5908 out->deluxemaptexture = r_texture_blanknormalmap;
5909 n = LittleLong(in->lightmapindex);
5912 else if (n >= loadmodel->brushq3.num_originallightmaps)
5914 if(loadmodel->brushq3.num_originallightmaps != 0)
5915 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5920 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5921 if (loadmodel->brushq3.deluxemapping)
5922 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5923 loadmodel->lit = true;
5927 firstvertex = LittleLong(in->firstvertex);
5928 numvertices = LittleLong(in->numvertices);
5929 firstelement = LittleLong(in->firstelement);
5930 numtriangles = LittleLong(in->numelements) / 3;
5931 if (numtriangles * 3 != LittleLong(in->numelements))
5933 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));
5936 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5938 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);
5941 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5943 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);
5948 case Q3FACETYPE_FLAT:
5949 case Q3FACETYPE_MESH:
5950 // no processing necessary
5952 case Q3FACETYPE_PATCH:
5953 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5954 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5955 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))
5957 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5960 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5962 // convert patch to Q3FACETYPE_MESH
5963 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5964 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5965 // bound to user settings
5966 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5967 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5968 // bound to sanity settings
5969 xtess = bound(0, xtess, 1024);
5970 ytess = bound(0, ytess, 1024);
5972 // lower quality collision patches! Same procedure as before, but different cvars
5973 // convert patch to Q3FACETYPE_MESH
5974 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5975 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5976 // bound to user settings
5977 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5978 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5979 // bound to sanity settings
5980 cxtess = bound(0, cxtess, 1024);
5981 cytess = bound(0, cytess, 1024);
5983 // store it for the LOD grouping step
5984 patchtess[patchtesscount].info.xsize = patchsize[0];
5985 patchtess[patchtesscount].info.ysize = patchsize[1];
5986 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5987 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5988 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5989 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5991 patchtess[patchtesscount].surface_id = i;
5992 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5993 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5994 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5995 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5996 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5997 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5998 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
6001 case Q3FACETYPE_FLARE:
6002 if (developer_extra.integer)
6003 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
6007 out->num_vertices = numvertices;
6008 out->num_triangles = numtriangles;
6009 meshvertices += out->num_vertices;
6010 meshtriangles += out->num_triangles;
6013 // Fix patches tesselations so that they make no seams
6017 for(i = 0; i < patchtesscount; ++i)
6019 for(j = i+1; j < patchtesscount; ++j)
6021 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
6024 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
6031 // Calculate resulting number of triangles
6032 collisionvertices = 0;
6033 collisiontriangles = 0;
6034 for(i = 0; i < patchtesscount; ++i)
6036 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
6037 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
6038 numvertices = finalwidth * finalheight;
6039 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6041 oldout[patchtess[i].surface_id].num_vertices = numvertices;
6042 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
6043 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
6044 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
6046 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
6047 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
6048 numvertices = finalwidth * finalheight;
6049 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6051 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
6052 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
6053 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
6054 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
6060 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true);
6061 if (collisiontriangles)
6063 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6064 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6068 collisionvertices = 0;
6069 collisiontriangles = 0;
6070 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6072 if (out->num_vertices < 3 || out->num_triangles < 1)
6075 type = LittleLong(in->type);
6076 firstvertex = LittleLong(in->firstvertex);
6077 firstelement = LittleLong(in->firstelement);
6078 out->num_firstvertex = meshvertices;
6079 out->num_firsttriangle = meshtriangles;
6080 out->num_firstcollisiontriangle = collisiontriangles;
6083 case Q3FACETYPE_FLAT:
6084 case Q3FACETYPE_MESH:
6085 // no processing necessary, except for lightmap merging
6086 for (j = 0;j < out->num_vertices;j++)
6088 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6089 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6090 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6091 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6092 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6093 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6094 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6095 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6096 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6097 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6098 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6099 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6100 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6101 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6103 for (j = 0;j < out->num_triangles*3;j++)
6104 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6106 case Q3FACETYPE_PATCH:
6107 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6108 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6109 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6110 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6111 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6112 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6113 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6115 xtess = ytess = cxtess = cytess = -1;
6116 for(j = 0; j < patchtesscount; ++j)
6117 if(patchtess[j].surface_id == i)
6119 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6120 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6121 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6122 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6127 Con_Errorf("ERROR: patch %d isn't preprocessed?!?\n", i);
6128 xtess = ytess = cxtess = cytess = 0;
6131 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6132 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6133 finalvertices = finalwidth * finalheight;
6134 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6135 type = Q3FACETYPE_MESH;
6136 // generate geometry
6137 // (note: normals are skipped because they get recalculated)
6138 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6139 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6140 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6141 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6142 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6143 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6145 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);
6147 if (developer_extra.integer)
6149 if (out->num_triangles < finaltriangles)
6150 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);
6152 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);
6154 // q3map does not put in collision brushes for curves... ugh
6155 // build the lower quality collision geometry
6156 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6157 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6158 finalvertices = finalwidth * finalheight;
6159 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6161 // store collision geometry for BIH collision tree
6162 out->num_collisionvertices = finalvertices;
6163 out->num_collisiontriangles = finaltriangles;
6164 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6165 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6166 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6167 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6168 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6169 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6171 if (developer_extra.integer)
6172 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);
6174 collisionvertices += finalvertices;
6175 collisiontriangles += out->num_collisiontriangles;
6180 meshvertices += out->num_vertices;
6181 meshtriangles += out->num_triangles;
6182 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6183 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)
6185 if (invalidelements)
6187 Con_Warnf("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);
6188 for (j = 0;j < out->num_triangles * 3;j++)
6190 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6191 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)
6192 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6196 // calculate a bounding box
6197 VectorClear(out->mins);
6198 VectorClear(out->maxs);
6199 if (out->num_vertices)
6201 if (cls.state != ca_dedicated && out->lightmaptexture)
6203 // figure out which part of the merged lightmap this fits into
6204 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6205 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6206 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6207 lightmapindex &= mergewidth * mergeheight - 1;
6208 lightmaptcscale[0] = 1.0f / mergewidth;
6209 lightmaptcscale[1] = 1.0f / mergeheight;
6210 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6211 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6212 // modify the lightmap texcoords to match this region of the merged lightmap
6213 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6215 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6216 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6219 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6220 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6221 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6223 out->mins[0] = min(out->mins[0], v[0]);
6224 out->maxs[0] = max(out->maxs[0], v[0]);
6225 out->mins[1] = min(out->mins[1], v[1]);
6226 out->maxs[1] = max(out->maxs[1], v[1]);
6227 out->mins[2] = min(out->mins[2], v[2]);
6228 out->maxs[2] = max(out->maxs[2], v[2]);
6230 out->mins[0] -= 1.0f;
6231 out->mins[1] -= 1.0f;
6232 out->mins[2] -= 1.0f;
6233 out->maxs[0] += 1.0f;
6234 out->maxs[1] += 1.0f;
6235 out->maxs[2] += 1.0f;
6237 // set lightmap styles for consistency with q1bsp
6238 //out->lightmapinfo->styles[0] = 0;
6239 //out->lightmapinfo->styles[1] = 255;
6240 //out->lightmapinfo->styles[2] = 255;
6241 //out->lightmapinfo->styles[3] = 255;
6246 for (;i < count;i++, out++)
6248 if(out->num_vertices && out->num_triangles)
6250 if(out->num_vertices == 0)
6252 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6253 if(out->num_triangles == 0)
6254 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6256 else if(out->num_triangles == 0)
6257 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)",
6258 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6259 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6260 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6263 // for per pixel lighting
6264 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);
6266 // generate ushort elements array if possible
6267 if (loadmodel->surfmesh.data_element3s)
6268 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6269 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6271 // free the no longer needed vertex data
6272 loadmodel->brushq3.num_vertices = 0;
6273 if (loadmodel->brushq3.data_vertex3f)
6274 Mem_Free(loadmodel->brushq3.data_vertex3f);
6275 loadmodel->brushq3.data_vertex3f = NULL;
6276 loadmodel->brushq3.data_normal3f = NULL;
6277 loadmodel->brushq3.data_texcoordtexture2f = NULL;
6278 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6279 loadmodel->brushq3.data_color4f = NULL;
6280 // free the no longer needed triangle data
6281 loadmodel->brushq3.num_triangles = 0;
6282 if (loadmodel->brushq3.data_element3i)
6283 Mem_Free(loadmodel->brushq3.data_element3i);
6284 loadmodel->brushq3.data_element3i = NULL;
6287 Mem_Free(patchtess);
6290 static void Mod_Q3BSP_LoadModels(lump_t *l)
6294 int i, j, n, c, count;
6296 in = (q3dmodel_t *)(mod_base + l->fileofs);
6297 if (l->filelen % sizeof(*in))
6298 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6299 count = l->filelen / sizeof(*in);
6300 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6302 loadmodel->brushq3.data_models = out;
6303 loadmodel->brushq3.num_models = count;
6305 for (i = 0;i < count;i++, in++, out++)
6307 for (j = 0;j < 3;j++)
6309 out->mins[j] = LittleFloat(in->mins[j]);
6310 out->maxs[j] = LittleFloat(in->maxs[j]);
6312 n = LittleLong(in->firstface);
6313 c = LittleLong(in->numfaces);
6314 if (n < 0 || n + c > loadmodel->num_surfaces)
6315 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6318 n = LittleLong(in->firstbrush);
6319 c = LittleLong(in->numbrushes);
6320 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6321 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6322 out->firstbrush = n;
6323 out->numbrushes = c;
6327 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6333 in = (int *)(mod_base + l->fileofs);
6334 if (l->filelen % sizeof(*in))
6335 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6336 count = l->filelen / sizeof(*in);
6337 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6339 loadmodel->brush.data_leafbrushes = out;
6340 loadmodel->brush.num_leafbrushes = count;
6342 for (i = 0;i < count;i++, in++, out++)
6344 n = LittleLong(*in);
6345 if (n < 0 || n >= loadmodel->brush.num_brushes)
6346 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6351 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6357 in = (int *)(mod_base + l->fileofs);
6358 if (l->filelen % sizeof(*in))
6359 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6360 count = l->filelen / sizeof(*in);
6361 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6363 loadmodel->brush.data_leafsurfaces = out;
6364 loadmodel->brush.num_leafsurfaces = count;
6366 for (i = 0;i < count;i++, in++, out++)
6368 n = LittleLong(*in);
6369 if (n < 0 || n >= loadmodel->num_surfaces)
6370 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6375 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6379 int i, j, n, c, count;
6381 in = (q3dleaf_t *)(mod_base + l->fileofs);
6382 if (l->filelen % sizeof(*in))
6383 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6384 count = l->filelen / sizeof(*in);
6385 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6387 loadmodel->brush.data_leafs = out;
6388 loadmodel->brush.num_leafs = count;
6390 for (i = 0;i < count;i++, in++, out++)
6394 out->clusterindex = LittleLong(in->clusterindex);
6395 out->areaindex = LittleLong(in->areaindex);
6396 for (j = 0;j < 3;j++)
6398 // yes the mins/maxs are ints
6399 out->mins[j] = LittleLong(in->mins[j]) - 1;
6400 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6402 n = LittleLong(in->firstleafface);
6403 c = LittleLong(in->numleaffaces);
6404 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6405 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6406 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6407 out->numleafsurfaces = c;
6408 n = LittleLong(in->firstleafbrush);
6409 c = LittleLong(in->numleafbrushes);
6410 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6411 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6412 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6413 out->numleafbrushes = c;
6417 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6423 in = (q3dnode_t *)(mod_base + l->fileofs);
6424 if (l->filelen % sizeof(*in))
6425 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6426 count = l->filelen / sizeof(*in);
6428 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6429 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6431 loadmodel->brush.data_nodes = out;
6432 loadmodel->brush.num_nodes = count;
6434 for (i = 0;i < count;i++, in++, out++)
6437 n = LittleLong(in->planeindex);
6438 if (n < 0 || n >= loadmodel->brush.num_planes)
6439 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6440 out->plane = loadmodel->brush.data_planes + n;
6441 for (j = 0;j < 2;j++)
6443 n = LittleLong(in->childrenindex[j]);
6446 if (n >= loadmodel->brush.num_nodes)
6447 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6448 out->children[j] = loadmodel->brush.data_nodes + n;
6453 if (n >= loadmodel->brush.num_leafs)
6454 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6455 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6458 for (j = 0;j < 3;j++)
6460 // yes the mins/maxs are ints
6461 out->mins[j] = LittleLong(in->mins[j]) - 1;
6462 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6466 // set the parent pointers
6467 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6470 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6473 q3dlightgrid_t *out;
6477 unsigned char *texturergba, *texturelayer[3], *texturepadding[2];
6478 double lightgridmatrix[4][4];
6480 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6481 if (l->filelen % sizeof(*in))
6482 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6483 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6484 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6485 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6486 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6487 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6488 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6489 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6490 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6491 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6492 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6493 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6494 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6495 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6496 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]);
6497 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]);
6499 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6502 if (l->filelen < count * (int)sizeof(*in))
6504 Con_Errorf("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]);
6505 return; // ignore the grid if we cannot understand it
6507 if (l->filelen != count * (int)sizeof(*in))
6508 Con_Warnf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
6509 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6510 loadmodel->brushq3.data_lightgrid = out;
6511 loadmodel->brushq3.num_lightgrid = count;
6512 // no swapping or validation necessary
6513 memcpy(out, in, count * (int)sizeof(*out));
6515 if(mod_q3bsp_sRGBlightmaps.integer)
6517 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6519 // we fix the brightness consistently via lightmapscale
6523 for(i = 0; i < count; ++i)
6525 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6526 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6527 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6528 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6529 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6530 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6536 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6538 for(i = 0; i < count; ++i)
6540 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6541 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6542 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6543 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6544 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6545 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6554 if (mod_q3bsp_lightgrid_texture.integer)
6556 // build a texture to hold the data for per-pixel sampling
6557 // this has 3 different kinds of data stacked in it:
6559 // bent-normal light color
6560 // bent-normal light dir
6562 texturesize[0] = loadmodel->brushq3.num_lightgrid_isize[0];
6563 texturesize[1] = loadmodel->brushq3.num_lightgrid_isize[1];
6564 texturesize[2] = (loadmodel->brushq3.num_lightgrid_isize[2] + 2) * 3;
6565 texturergba = (unsigned char*)Mem_Alloc(loadmodel->mempool, texturesize[0] * texturesize[1] * texturesize[2] * sizeof(char[4]));
6566 texturelayer[0] = texturergba + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6567 texturelayer[1] = texturelayer[0] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6568 texturelayer[2] = texturelayer[1] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6569 // the light dir layer needs padding above/below it that is a neutral unsigned normal (127,127,127,255)
6570 texturepadding[0] = texturelayer[2] - loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6571 texturepadding[1] = texturelayer[2] + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2] * 4;
6572 for (i = 0; i < texturesize[0] * texturesize[1]; i++)
6574 texturepadding[0][i * 4] = texturepadding[1][i * 4] = 127;
6575 texturepadding[0][i * 4 + 1] = texturepadding[1][i * 4 + 1] = 127;
6576 texturepadding[0][i * 4 + 2] = texturepadding[1][i * 4 + 2] = 127;
6577 texturepadding[0][i * 4 + 3] = texturepadding[1][i * 4 + 3] = 255;
6579 for (i = 0; i < count; i++)
6581 texturelayer[0][i * 4 + 0] = out[i].ambientrgb[0];
6582 texturelayer[0][i * 4 + 1] = out[i].ambientrgb[1];
6583 texturelayer[0][i * 4 + 2] = out[i].ambientrgb[2];
6584 texturelayer[0][i * 4 + 3] = 255;
6585 texturelayer[1][i * 4 + 0] = out[i].diffusergb[0];
6586 texturelayer[1][i * 4 + 1] = out[i].diffusergb[1];
6587 texturelayer[1][i * 4 + 2] = out[i].diffusergb[2];
6588 texturelayer[1][i * 4 + 3] = 255;
6589 // this uses the mod_md3_sin table because the values are
6590 // already in the 0-255 range, the 64+ bias fetches a cosine
6591 // instead of a sine value
6592 texturelayer[2][i * 4 + 0] = (char)((mod_md3_sin[64 + out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6593 texturelayer[2][i * 4 + 1] = (char)((mod_md3_sin[out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6594 texturelayer[2][i * 4 + 2] = (char)((mod_md3_sin[64 + out[i].diffusepitch]) * 127 + 127);
6595 texturelayer[2][i * 4 + 3] = 255;
6600 for (z = 0; z < loadmodel->brushq3.num_lightgrid_isize[2]; z++)
6602 for (y = 0; y < loadmodel->brushq3.num_lightgrid_isize[1]; y++)
6604 for (x = 0; x < loadmodel->brushq3.num_lightgrid_isize[0]; x++)
6606 i = (z * texturesize[1] + y) * texturesize[0] + x;
6607 texturelayer[0][i * 4 + 0] = x * 256 / loadmodel->brushq3.num_lightgrid_isize[0];
6608 texturelayer[0][i * 4 + 1] = y * 256 / loadmodel->brushq3.num_lightgrid_isize[1];
6609 texturelayer[0][i * 4 + 2] = z * 256 / loadmodel->brushq3.num_lightgrid_isize[2];
6614 loadmodel->brushq3.lightgridtexturesize[0] = texturesize[0];
6615 loadmodel->brushq3.lightgridtexturesize[1] = texturesize[1];
6616 loadmodel->brushq3.lightgridtexturesize[2] = texturesize[2];
6617 memset(lightgridmatrix[0], 0, sizeof(lightgridmatrix));
6618 lightgridmatrix[0][0] = loadmodel->brushq3.num_lightgrid_scale[0] / texturesize[0];
6619 lightgridmatrix[1][1] = loadmodel->brushq3.num_lightgrid_scale[1] / texturesize[1];
6620 lightgridmatrix[2][2] = loadmodel->brushq3.num_lightgrid_scale[2] / texturesize[2];
6621 lightgridmatrix[0][3] = -(loadmodel->brushq3.num_lightgrid_imins[0] - 0.5f) / texturesize[0];
6622 lightgridmatrix[1][3] = -(loadmodel->brushq3.num_lightgrid_imins[1] - 0.5f) / texturesize[1];
6623 lightgridmatrix[2][3] = -(loadmodel->brushq3.num_lightgrid_imins[2] - 1.5f) / texturesize[2];
6624 lightgridmatrix[3][3] = 1;
6625 Matrix4x4_FromArrayDoubleD3D(&loadmodel->brushq3.lightgridworldtotexturematrix, lightgridmatrix[0]);
6626 loadmodel->brushq3.lightgridtexture = R_LoadTexture3D(loadmodel->texturepool, "lightgrid", texturesize[0], texturesize[1], texturesize[2], texturergba, TEXTYPE_RGBA, TEXF_CLAMP, 0, NULL);
6627 Mem_Free(texturergba);
6632 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6637 if (l->filelen == 0)
6640 // unvised maps often have cluster indices even without pvs, so check
6641 // leafs to find real number of clusters
6642 loadmodel->brush.num_pvsclusters = 1;
6643 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6644 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6647 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6648 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6649 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6650 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6654 in = (q3dpvs_t *)(mod_base + l->fileofs);
6656 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6658 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6659 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6660 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6661 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6662 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6663 if (l->filelen < totalchains + (int)sizeof(*in))
6664 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);
6666 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6667 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6670 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6672 int i, j, k, index[3];
6673 float transformed[3], blend1, blend2, blend, stylescale = 1;
6674 q3dlightgrid_t *a, *s;
6676 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6677 // LadyHavoc: FIXME: is this true?
6678 stylescale = 1; // added while render
6679 //stylescale = r_refdef.scene.rtlightstylevalue[0];
6681 if (!model->brushq3.num_lightgrid)
6683 ambientcolor[0] = stylescale;
6684 ambientcolor[1] = stylescale;
6685 ambientcolor[2] = stylescale;
6689 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6690 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6691 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6692 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6693 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6694 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6695 index[0] = (int)floor(transformed[0]);
6696 index[1] = (int)floor(transformed[1]);
6697 index[2] = (int)floor(transformed[2]);
6698 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6700 // now lerp the values
6701 VectorClear(diffusenormal);
6702 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6703 for (k = 0;k < 2;k++)
6705 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6706 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6708 for (j = 0;j < 2;j++)
6710 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6711 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6713 for (i = 0;i < 2;i++)
6715 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6716 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6718 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6719 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6720 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6721 // this uses the mod_md3_sin table because the values are
6722 // already in the 0-255 range, the 64+ bias fetches a cosine
6723 // instead of a sine value
6724 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6725 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6726 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6727 //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)));
6732 // normalize the light direction before turning
6733 VectorNormalize(diffusenormal);
6734 //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]);
6737 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3], double endpos[3])
6740 double midf, mid[3];
6746 // find the point distances
6747 mplane_t *plane = node->plane;
6748 if (plane->type < 3)
6750 t1 = p1[plane->type] - plane->dist;
6751 t2 = p2[plane->type] - plane->dist;
6755 t1 = DotProduct (plane->normal, p1) - plane->dist;
6756 t2 = DotProduct (plane->normal, p2) - plane->dist;
6763 node = node->children[1];
6772 node = node->children[0];
6778 midf = t1 / (t1 - t2);
6779 VectorLerp(p1, midf, p2, mid);
6781 // recurse both sides, front side first
6782 // return 2 if empty is followed by solid (hit something)
6783 // do not return 2 if both are solid or both empty,
6784 // or if start is solid and end is empty
6785 // as these degenerate cases usually indicate the eye is in solid and
6786 // should see the target point anyway
6787 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid, endpos);
6790 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2, endpos);
6793 VectorCopy(mid, endpos);
6796 return ((mleaf_t *)node)->clusterindex < 0;
6799 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
6801 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6804 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
6805 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
6809 double tracestart[3], traceend[3], traceendpos[3];
6810 VectorCopy(start, tracestart);
6811 VectorCopy(end, traceend);
6812 VectorCopy(end, traceendpos);
6813 Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend, traceendpos);
6814 return BoxesOverlap(traceendpos, traceendpos, acceptmins, acceptmaxs);
6818 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, int skipmaterialflagsmask)
6821 const bih_leaf_t *leaf;
6822 const bih_node_t *node;
6823 const colbrushf_t *brush;
6826 int nodestackpos = 0;
6827 int nodestack[1024];
6829 memset(trace, 0, sizeof(*trace));
6830 trace->fraction = 1;
6831 trace->hitsupercontentsmask = hitsupercontentsmask;
6832 trace->skipsupercontentsmask = skipsupercontentsmask;
6833 trace->skipmaterialflagsmask = skipmaterialflagsmask;
6835 bih = &model->collision_bih;
6839 nodenum = bih->rootnode;
6840 nodestack[nodestackpos++] = nodenum;
6841 while (nodestackpos)
6843 nodenum = nodestack[--nodestackpos];
6844 node = bih->nodes + nodenum;
6846 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6849 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6851 axis = node->type - BIH_SPLITX;
6852 if (start[axis] >= node->frontmin)
6853 nodestack[nodestackpos++] = node->front;
6854 if (start[axis] <= node->backmax)
6855 nodestack[nodestackpos++] = node->back;
6857 else if (node->type == BIH_UNORDERED)
6859 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6861 leaf = bih->leafs + node->children[axis];
6863 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6869 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6870 Collision_TracePointBrushFloat(trace, start, brush);
6872 case BIH_COLLISIONTRIANGLE:
6873 // collision triangle - skipped because they have no volume
6875 case BIH_RENDERTRIANGLE:
6876 // render triangle - skipped because they have no volume
6884 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, int skipmaterialflagsmask, const bih_t *bih)
6886 const bih_leaf_t *leaf;
6887 const bih_node_t *node;
6888 const colbrushf_t *brush;
6890 const texture_t *texture;
6891 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6892 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6893 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6898 if (VectorCompare(start, end))
6900 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6904 nodenum = bih->rootnode;
6906 memset(trace, 0, sizeof(*trace));
6907 trace->fraction = 1;
6908 trace->hitsupercontentsmask = hitsupercontentsmask;
6909 trace->skipsupercontentsmask = skipsupercontentsmask;
6910 trace->skipmaterialflagsmask = skipmaterialflagsmask;
6913 nodestackline[nodestackpos][0] = start[0];
6914 nodestackline[nodestackpos][1] = start[1];
6915 nodestackline[nodestackpos][2] = start[2];
6916 nodestackline[nodestackpos][3] = end[0];
6917 nodestackline[nodestackpos][4] = end[1];
6918 nodestackline[nodestackpos][5] = end[2];
6919 nodestack[nodestackpos++] = nodenum;
6920 while (nodestackpos)
6922 nodenum = nodestack[--nodestackpos];
6923 node = bih->nodes + nodenum;
6924 VectorCopy(nodestackline[nodestackpos], nodestart);
6925 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6926 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6927 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6928 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6929 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6930 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6931 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6932 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs) && !collision_bih_fullrecursion.integer)
6934 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6936 // recurse children of the split
6937 axis = node->type - BIH_SPLITX;
6938 d1 = node->backmax - nodestart[axis];
6939 d2 = node->backmax - nodeend[axis];
6940 d3 = nodestart[axis] - node->frontmin;
6941 d4 = nodeend[axis] - node->frontmin;
6942 if (collision_bih_fullrecursion.integer)
6943 d1 = d2 = d3 = d4 = 1; // force full recursion
6944 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6946 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;
6947 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;
6948 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;
6949 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6950 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;
6951 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;
6952 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;
6953 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6954 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;
6955 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;
6956 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;
6957 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6958 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6959 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6960 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6961 case 15: /* <<<< */ break;
6964 else if (node->type == BIH_UNORDERED)
6966 // calculate sweep bounds for this node
6967 // copy node bounds into local variables
6968 VectorCopy(node->mins, nodebigmins);
6969 VectorCopy(node->maxs, nodebigmaxs);
6970 // clip line to this node bounds
6971 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); }
6972 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); }
6973 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); }
6974 // some of the line intersected the enlarged node box
6975 // calculate sweep bounds for this node
6976 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6977 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6978 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6979 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6980 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6981 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6982 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6984 leaf = bih->leafs + node->children[axis];
6985 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6990 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6991 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6993 case BIH_COLLISIONTRIANGLE:
6994 if (!mod_q3bsp_curves_collisions.integer)
6996 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6997 texture = model->data_textures + leaf->textureindex;
6998 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);
7000 case BIH_RENDERTRIANGLE:
7001 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7002 texture = model->data_textures + leaf->textureindex;
7003 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);
7011 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, int skipmaterialflagsmask)
7013 if (VectorCompare(start, end))
7015 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7018 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->collision_bih);
7021 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, int skipmaterialflagsmask)
7024 const bih_leaf_t *leaf;
7025 const bih_node_t *node;
7026 const colbrushf_t *brush;
7028 const texture_t *texture;
7029 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
7030 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
7031 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
7032 int axis, nodenum, nodestackpos = 0, nodestack[1024];
7034 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
7036 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
7037 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7039 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7043 bih = &model->collision_bih;
7046 nodenum = bih->rootnode;
7048 // box trace, performed as brush trace
7049 memset(trace, 0, sizeof(*trace));
7050 trace->fraction = 1;
7051 trace->hitsupercontentsmask = hitsupercontentsmask;
7052 trace->skipsupercontentsmask = skipsupercontentsmask;
7053 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7055 // calculate tracebox-like parameters for efficient culling
7056 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
7057 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
7058 VectorSubtract(thisbrush_start->mins, start, startmins);
7059 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
7060 VectorSubtract(thisbrush_end->mins, end, endmins);
7061 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7062 mins[0] = min(startmins[0], endmins[0]);
7063 mins[1] = min(startmins[1], endmins[1]);
7064 mins[2] = min(startmins[2], endmins[2]);
7065 maxs[0] = max(startmaxs[0], endmaxs[0]);
7066 maxs[1] = max(startmaxs[1], endmaxs[1]);
7067 maxs[2] = max(startmaxs[2], endmaxs[2]);
7070 nodestackline[nodestackpos][0] = start[0];
7071 nodestackline[nodestackpos][1] = start[1];
7072 nodestackline[nodestackpos][2] = start[2];
7073 nodestackline[nodestackpos][3] = end[0];
7074 nodestackline[nodestackpos][4] = end[1];
7075 nodestackline[nodestackpos][5] = end[2];
7076 nodestack[nodestackpos++] = nodenum;
7077 while (nodestackpos)
7079 nodenum = nodestack[--nodestackpos];
7080 node = bih->nodes + nodenum;
7081 VectorCopy(nodestackline[nodestackpos], nodestart);
7082 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7083 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7084 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7085 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7086 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7087 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7088 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7089 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7091 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7093 // recurse children of the split
7094 axis = node->type - BIH_SPLITX;
7095 d1 = node->backmax - nodestart[axis] - mins[axis];
7096 d2 = node->backmax - nodeend[axis] - mins[axis];
7097 d3 = nodestart[axis] - node->frontmin + maxs[axis];
7098 d4 = nodeend[axis] - node->frontmin + maxs[axis];
7099 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7101 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;
7102 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;
7103 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;
7104 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7105 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;
7106 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;
7107 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;
7108 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7109 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;
7110 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;
7111 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;
7112 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7113 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7114 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7115 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7116 case 15: /* <<<< */ break;
7119 else if (node->type == BIH_UNORDERED)
7121 // calculate sweep bounds for this node
7122 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7123 VectorSubtract(node->mins, maxs, nodebigmins);
7124 VectorSubtract(node->maxs, mins, nodebigmaxs);
7125 // clip line to this node bounds
7126 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); }
7127 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); }
7128 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); }
7129 // some of the line intersected the enlarged node box
7130 // calculate sweep bounds for this node
7131 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7132 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7133 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7134 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7135 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7136 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7137 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7139 leaf = bih->leafs + node->children[axis];
7140 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7145 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7146 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7148 case BIH_COLLISIONTRIANGLE:
7149 if (!mod_q3bsp_curves_collisions.integer)
7151 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7152 texture = model->data_textures + leaf->textureindex;
7153 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);
7155 case BIH_RENDERTRIANGLE:
7156 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7157 texture = model->data_textures + leaf->textureindex;
7158 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);
7166 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, int skipmaterialflagsmask)
7168 colboxbrushf_t thisbrush_start, thisbrush_end;
7169 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7171 // box trace, performed as brush trace
7172 VectorAdd(start, boxmins, boxstartmins);
7173 VectorAdd(start, boxmaxs, boxstartmaxs);
7174 VectorAdd(end, boxmins, boxendmins);
7175 VectorAdd(end, boxmaxs, boxendmaxs);
7176 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7177 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7178 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7182 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7185 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0, 0);
7186 return trace.startsupercontents;
7189 qboolean Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
7192 Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
7193 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
7196 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, int skipmaterialflagsmask)
7199 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7201 int hitsupercontents;
7202 VectorSet(end, start[0], start[1], model->normalmins[2]);
7204 memset(trace, 0, sizeof(*trace));
7205 trace->fraction = 1;
7206 trace->hitsupercontentsmask = hitsupercontentsmask;
7207 trace->skipsupercontentsmask = skipsupercontentsmask;
7208 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7210 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7211 hitsupercontents = trace->hitsupercontents;
7212 memset(trace, 0, sizeof(*trace));
7213 trace->fraction = 1;
7214 trace->hitsupercontentsmask = hitsupercontentsmask;
7215 trace->skipsupercontentsmask = skipsupercontentsmask;
7216 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7217 trace->startsupercontents = hitsupercontents;
7221 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7224 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7227 VectorSet(end, start[0], start[1], model->normalmins[2]);
7228 memset(&trace, 0, sizeof(trace));
7230 trace.hitsupercontentsmask = hitsupercontentsmask;
7231 trace.skipsupercontentsmask = skipsupercontentsmask;
7232 trace.skipmaterialflagsmask = skipmaterialflagsmask;
7233 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7234 return trace.hitsupercontents;
7240 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, int skipmaterialflagsmask)
7242 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->render_bih);
7246 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
7254 int nummodelbrushes = model->nummodelbrushes;
7255 int nummodelsurfaces = model->nummodelsurfaces;
7257 const int *collisionelement3i;
7258 const float *collisionvertex3f;
7259 const int *renderelement3i;
7260 const float *rendervertex3f;
7261 bih_leaf_t *bihleafs;
7262 bih_node_t *bihnodes;
7264 int *temp_leafsortscratch;
7265 const msurface_t *surface;
7266 const q3mbrush_t *brush;
7268 // find out how many BIH leaf nodes we need
7270 if (userendersurfaces)
7272 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7273 bihnumleafs += surface->num_triangles;
7277 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7278 if (brush->colbrushf)
7280 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7282 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7283 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7285 bihnumleafs += surface->num_collisiontriangles;
7292 // allocate the memory for the BIH leaf nodes
7293 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7295 // now populate the BIH leaf nodes
7298 // add render surfaces
7299 renderelement3i = model->surfmesh.data_element3i;
7300 rendervertex3f = model->surfmesh.data_vertex3f;
7301 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7303 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7305 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7307 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7308 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7309 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7310 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7311 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7312 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7313 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7314 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7315 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7316 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7321 if (!userendersurfaces)
7323 // add collision brushes
7324 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7326 if (!brush->colbrushf)
7328 bihleafs[bihleafindex].type = BIH_BRUSH;
7329 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7330 bihleafs[bihleafindex].surfaceindex = -1;
7331 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7332 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7333 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7337 // add collision surfaces
7338 collisionelement3i = model->brush.data_collisionelement3i;
7339 collisionvertex3f = model->brush.data_collisionvertex3f;
7340 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7342 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7344 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7345 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7346 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7347 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7348 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7349 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7350 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7351 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7352 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7353 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7359 // allocate buffers for the produced and temporary data
7360 bihmaxnodes = bihnumleafs + 1;
7361 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7362 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7363 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7366 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7368 // we're done with the temporary data
7369 Mem_Free(temp_leafsort);
7371 // resize the BIH nodes array if it over-allocated
7372 if (out->maxnodes > out->numnodes)
7374 out->maxnodes = out->numnodes;
7375 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7381 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents)
7383 int supercontents = 0;
7384 if (nativecontents & CONTENTSQ3_SOLID)
7385 supercontents |= SUPERCONTENTS_SOLID;
7386 if (nativecontents & CONTENTSQ3_WATER)
7387 supercontents |= SUPERCONTENTS_WATER;
7388 if (nativecontents & CONTENTSQ3_SLIME)
7389 supercontents |= SUPERCONTENTS_SLIME;
7390 if (nativecontents & CONTENTSQ3_LAVA)
7391 supercontents |= SUPERCONTENTS_LAVA;
7392 if (nativecontents & CONTENTSQ3_BODY)
7393 supercontents |= SUPERCONTENTS_BODY;
7394 if (nativecontents & CONTENTSQ3_CORPSE)
7395 supercontents |= SUPERCONTENTS_CORPSE;
7396 if (nativecontents & CONTENTSQ3_NODROP)
7397 supercontents |= SUPERCONTENTS_NODROP;
7398 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7399 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7400 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7401 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7402 if (nativecontents & CONTENTSQ3_DONOTENTER)
7403 supercontents |= SUPERCONTENTS_DONOTENTER;
7404 if (nativecontents & CONTENTSQ3_BOTCLIP)
7405 supercontents |= SUPERCONTENTS_BOTCLIP;
7406 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7407 supercontents |= SUPERCONTENTS_OPAQUE;
7408 return supercontents;
7411 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents)
7413 int nativecontents = 0;
7414 if (supercontents & SUPERCONTENTS_SOLID)
7415 nativecontents |= CONTENTSQ3_SOLID;
7416 if (supercontents & SUPERCONTENTS_WATER)
7417 nativecontents |= CONTENTSQ3_WATER;
7418 if (supercontents & SUPERCONTENTS_SLIME)
7419 nativecontents |= CONTENTSQ3_SLIME;
7420 if (supercontents & SUPERCONTENTS_LAVA)
7421 nativecontents |= CONTENTSQ3_LAVA;
7422 if (supercontents & SUPERCONTENTS_BODY)
7423 nativecontents |= CONTENTSQ3_BODY;
7424 if (supercontents & SUPERCONTENTS_CORPSE)
7425 nativecontents |= CONTENTSQ3_CORPSE;
7426 if (supercontents & SUPERCONTENTS_NODROP)
7427 nativecontents |= CONTENTSQ3_NODROP;
7428 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7429 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7430 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7431 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7432 if (supercontents & SUPERCONTENTS_DONOTENTER)
7433 nativecontents |= CONTENTSQ3_DONOTENTER;
7434 if (supercontents & SUPERCONTENTS_BOTCLIP)
7435 nativecontents |= CONTENTSQ3_BOTCLIP;
7436 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7437 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7438 return nativecontents;
7441 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7446 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7447 node = node->children[1];
7449 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7450 if (loadmodel->brush.num_leafs < numleafs)
7451 loadmodel->brush.num_leafs = numleafs;
7454 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7457 q3dheader_t *header;
7458 float corner[3], yawradius, modelradius;
7460 mod->modeldatatypestring = "Q3BSP";
7462 mod->type = mod_brushq3;
7463 mod->brush.ishlbsp = false;
7464 mod->brush.isbsp2rmqe = false;
7465 mod->brush.isbsp2 = false;
7466 mod->brush.isq2bsp = false;
7467 mod->brush.isq3bsp = true;
7468 mod->brush.skymasking = true;
7469 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7472 header = (q3dheader_t *)buffer;
7473 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7474 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7476 i = LittleLong(header->version);
7477 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7478 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7480 mod->soundfromcenter = true;
7481 mod->TraceBox = Mod_CollisionBIH_TraceBox;
7482 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
7483 mod->TraceLine = Mod_CollisionBIH_TraceLine;
7484 mod->TracePoint = Mod_CollisionBIH_TracePoint;
7485 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
7486 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7487 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7488 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7489 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7490 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7491 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7492 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7493 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7494 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7495 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7496 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7497 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7498 mod->brush.AmbientSoundLevelsForPoint = NULL;
7499 mod->brush.RoundUpToHullSize = NULL;
7500 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7501 mod->Draw = R_Q1BSP_Draw;
7502 mod->DrawDepth = R_Q1BSP_DrawDepth;
7503 mod->DrawDebug = R_Q1BSP_DrawDebug;
7504 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7505 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7506 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7507 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7508 mod->DrawLight = R_Q1BSP_DrawLight;
7510 mod_base = (unsigned char *)header;
7512 // swap all the lumps
7513 header->ident = LittleLong(header->ident);
7514 header->version = LittleLong(header->version);
7515 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7516 for (i = 0;i < lumps;i++)
7518 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7519 if((char *) bufferend < (char *) buffer + j)
7520 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7521 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7522 if((char *) bufferend < (char *) buffer + j)
7523 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7526 * NO, do NOT clear them!
7527 * they contain actual data referenced by other stuff.
7528 * Instead, before using the advertisements lump, check header->versio
7530 * Sorry, but otherwise it breaks memory of the first lump.
7531 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7533 header->lumps[i].fileofs = 0;
7534 header->lumps[i].filelen = 0;
7538 mod->brush.qw_md4sum = 0;
7539 mod->brush.qw_md4sum2 = 0;
7540 for (i = 0;i < lumps;i++)
7542 if (i == Q3LUMP_ENTITIES)
7544 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7545 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7547 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7549 // all this checksumming can take a while, so let's send keepalives here too
7550 CL_KeepaliveMessage(false);
7553 // allocate a texture pool if we need it
7554 if (mod->texturepool == NULL)
7555 mod->texturepool = R_AllocTexturePool();
7557 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7558 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7559 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7560 if (header->version == Q3BSPVERSION_IG)
7561 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7563 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7564 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7565 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7566 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7567 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7568 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7569 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7570 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7571 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7572 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7573 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7574 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7575 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7576 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7577 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7579 // the MakePortals code works fine on the q3bsp data as well
7580 if (mod_bsp_portalize.integer)
7581 Mod_Q1BSP_MakePortals();
7583 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7584 loadmodel->brush.supportwateralpha = true;
7586 loadmodel->brush.num_leafs = 0;
7587 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7589 if (loadmodel->brush.numsubmodels)
7590 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7593 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7598 // duplicate the basic information
7599 dpsnprintf(name, sizeof(name), "*%i", i);
7600 mod = Mod_FindName(name, loadmodel->name);
7601 // copy the base model to this one
7603 // rename the clone back to its proper name
7604 strlcpy(mod->name, name, sizeof(mod->name));
7605 mod->brush.parentmodel = loadmodel;
7606 // textures and memory belong to the main model
7607 mod->texturepool = NULL;
7608 mod->mempool = NULL;
7609 mod->brush.GetPVS = NULL;
7610 mod->brush.FatPVS = NULL;
7611 mod->brush.BoxTouchingPVS = NULL;
7612 mod->brush.BoxTouchingLeafPVS = NULL;
7613 mod->brush.BoxTouchingVisibleLeafs = NULL;
7614 mod->brush.FindBoxClusters = NULL;
7615 mod->brush.LightPoint = NULL;
7616 mod->brush.AmbientSoundLevelsForPoint = NULL;
7618 mod->brush.submodel = i;
7619 if (loadmodel->brush.submodels)
7620 loadmodel->brush.submodels[i] = mod;
7622 // make the model surface list (used by shadowing/lighting)
7623 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7624 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7625 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7626 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7627 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7628 Mod_MakeSortedSurfaces(mod);
7630 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7631 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7632 // enlarge the bounding box to enclose all geometry of this model,
7633 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7634 // which can in turn mess up the farclip (as well as culling when
7635 // outside the level - an unimportant concern)
7637 //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]);
7638 for (j = 0;j < mod->nummodelsurfaces;j++)
7640 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7641 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7643 if (!surface->num_vertices)
7645 for (k = 0;k < surface->num_vertices;k++, v += 3)
7647 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7648 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7649 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7650 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7651 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7652 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7655 //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]);
7656 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7657 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7658 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7659 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7660 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7661 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7662 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7663 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7664 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7665 mod->yawmins[2] = mod->normalmins[2];
7666 mod->yawmaxs[2] = mod->normalmaxs[2];
7667 mod->radius = modelradius;
7668 mod->radius2 = modelradius * modelradius;
7670 // this gets altered below if sky or water is used
7671 mod->DrawSky = NULL;
7672 mod->DrawAddWaterPlanes = NULL;
7674 for (j = 0;j < mod->nummodelsurfaces;j++)
7675 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7677 if (j < mod->nummodelsurfaces)
7678 mod->DrawSky = R_Q1BSP_DrawSky;
7680 for (j = 0;j < mod->nummodelsurfaces;j++)
7681 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7683 if (j < mod->nummodelsurfaces)
7684 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7686 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7687 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7689 // generate VBOs and other shared data before cloning submodels
7694 if (mod_q3bsp_sRGBlightmaps.integer)
7696 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7698 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7699 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7700 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7701 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7702 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7704 else // if this is NOT set, regular rendering looks right by this requirement anyway
7707 // we want color 1 to do the same as without sRGB
7708 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7709 loadmodel->lightmapscale *= 2.476923f; // fixes max level
7712 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7713 // we need to undo that
7714 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7718 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);
7721 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7723 int i = LittleLong(((int *)buffer)[1]);
7724 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7725 Mod_Q3BSP_Load(mod,buffer, bufferend);
7726 else if (i == Q2BSPVERSION)
7727 Mod_Q2BSP_Load(mod,buffer, bufferend);
7729 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7732 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7734 Host_Error("Mod_MAP_Load: not yet implemented");
7737 typedef struct objvertex_s
7748 static unsigned char nobsp_pvs[1] = {1};
7750 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7752 const char *textbase = (char *)buffer, *text = textbase;
7756 char materialname[MAX_QPATH];
7757 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7758 int index1, index2, index3;
7759 objvertex_t vfirst, vprev, vcurrent;
7762 int numtriangles = 0;
7763 int maxtriangles = 0;
7764 objvertex_t *vertices = NULL;
7766 int maxtextures = 0, numtextures = 0, textureindex = 0;
7767 int maxv = 0, numv = 1;
7768 int maxvt = 0, numvt = 1;
7769 int maxvn = 0, numvn = 1;
7770 char *texturenames = NULL;
7771 float dist, modelradius, modelyawradius, yawradius;
7772 float *obj_v = NULL;
7773 float *obj_vt = NULL;
7774 float *obj_vn = NULL;
7778 objvertex_t *thisvertex = NULL;
7779 int vertexhashindex;
7780 int *vertexhashtable = NULL;
7781 objvertex_t *vertexhashdata = NULL;
7782 objvertex_t *vdata = NULL;
7783 int vertexhashsize = 0;
7784 int vertexhashcount = 0;
7785 skinfile_t *skinfiles = NULL;
7786 unsigned char *data = NULL;
7787 int *submodelfirstsurface;
7788 msurface_t *tempsurface;
7789 msurface_t *tempsurfaces;
7791 memset(&vfirst, 0, sizeof(vfirst));
7792 memset(&vprev, 0, sizeof(vprev));
7793 memset(&vcurrent, 0, sizeof(vcurrent));
7795 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7797 loadmodel->modeldatatypestring = "OBJ";
7799 loadmodel->type = mod_obj;
7800 loadmodel->soundfromcenter = true;
7801 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7802 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7803 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7804 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7805 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7806 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7807 loadmodel->brush.TraceLineOfSight = NULL;
7808 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7809 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7810 loadmodel->brush.GetPVS = NULL;
7811 loadmodel->brush.FatPVS = NULL;
7812 loadmodel->brush.BoxTouchingPVS = NULL;
7813 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7814 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7815 loadmodel->brush.FindBoxClusters = NULL;
7816 loadmodel->brush.LightPoint = NULL;
7817 loadmodel->brush.FindNonSolidLocation = NULL;
7818 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7819 loadmodel->brush.RoundUpToHullSize = NULL;
7820 loadmodel->brush.PointInLeaf = NULL;
7821 loadmodel->Draw = R_Q1BSP_Draw;
7822 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7823 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7824 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7825 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7826 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7827 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7828 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7830 skinfiles = Mod_LoadSkinFiles();
7831 if (loadmodel->numskins < 1)
7832 loadmodel->numskins = 1;
7834 // make skinscenes for the skins (no groups)
7835 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7836 for (i = 0;i < loadmodel->numskins;i++)
7838 loadmodel->skinscenes[i].firstframe = i;
7839 loadmodel->skinscenes[i].framecount = 1;
7840 loadmodel->skinscenes[i].loop = true;
7841 loadmodel->skinscenes[i].framerate = 10;
7847 // we always have model 0, i.e. the first "submodel"
7848 loadmodel->brush.numsubmodels = 1;
7850 // parse the OBJ text now
7853 static char emptyarg[1] = "";
7858 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7859 line[linelen] = text[linelen];
7861 for (argc = 0;argc < 4;argc++)
7862 argv[argc] = emptyarg;
7865 while (*s == ' ' || *s == '\t')
7875 while (*s == ' ' || *s == '\t')
7885 if (argv[0][0] == '#')
7887 if (!strcmp(argv[0], "v"))
7891 maxv = max(maxv * 2, 1024);
7892 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
7894 if(mod_obj_orientation.integer)
7896 obj_v[numv*3+0] = atof(argv[1]);
7897 obj_v[numv*3+2] = atof(argv[2]);
7898 obj_v[numv*3+1] = atof(argv[3]);
7902 obj_v[numv*3+0] = atof(argv[1]);
7903 obj_v[numv*3+1] = atof(argv[2]);
7904 obj_v[numv*3+2] = atof(argv[3]);
7908 else if (!strcmp(argv[0], "vt"))
7912 maxvt = max(maxvt * 2, 1024);
7913 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
7915 obj_vt[numvt*2+0] = atof(argv[1]);
7916 obj_vt[numvt*2+1] = 1-atof(argv[2]);
7919 else if (!strcmp(argv[0], "vn"))
7923 maxvn = max(maxvn * 2, 1024);
7924 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
7926 if(mod_obj_orientation.integer)
7928 obj_vn[numvn*3+0] = atof(argv[1]);
7929 obj_vn[numvn*3+2] = atof(argv[2]);
7930 obj_vn[numvn*3+1] = atof(argv[3]);
7934 obj_vn[numvn*3+0] = atof(argv[1]);
7935 obj_vn[numvn*3+1] = atof(argv[2]);
7936 obj_vn[numvn*3+2] = atof(argv[3]);
7940 else if (!strcmp(argv[0], "f"))
7944 if (maxtextures <= numtextures)
7946 maxtextures = max(maxtextures * 2, 256);
7947 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7949 textureindex = numtextures++;
7950 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7952 for (j = 1;j < argc;j++)
7954 index1 = atoi(argv[j]);
7955 while(argv[j][0] && argv[j][0] != '/')
7959 index2 = atoi(argv[j]);
7960 while(argv[j][0] && argv[j][0] != '/')
7964 index3 = atoi(argv[j]);
7965 // negative refers to a recent vertex
7966 // zero means not specified
7967 // positive means an absolute vertex index
7969 index1 = numv - index1;
7971 index2 = numvt - index2;
7973 index3 = numvn - index3;
7974 vcurrent.nextindex = -1;
7975 vcurrent.textureindex = textureindex;
7976 vcurrent.submodelindex = submodelindex;
7977 if (obj_v && index1 >= 0 && index1 < numv)
7978 VectorCopy(obj_v + 3*index1, vcurrent.v);
7979 if (obj_vt && index2 >= 0 && index2 < numvt)
7980 Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
7981 if (obj_vn && index3 >= 0 && index3 < numvn)
7982 VectorCopy(obj_vn + 3*index3, vcurrent.vn);
7983 if (numtriangles == 0)
7985 VectorCopy(vcurrent.v, mins);
7986 VectorCopy(vcurrent.v, maxs);
7990 mins[0] = min(mins[0], vcurrent.v[0]);
7991 mins[1] = min(mins[1], vcurrent.v[1]);
7992 mins[2] = min(mins[2], vcurrent.v[2]);
7993 maxs[0] = max(maxs[0], vcurrent.v[0]);
7994 maxs[1] = max(maxs[1], vcurrent.v[1]);
7995 maxs[2] = max(maxs[2], vcurrent.v[2]);
8001 if (maxtriangles <= numtriangles)
8003 maxtriangles = max(maxtriangles * 2, 32768);
8004 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8006 if(mod_obj_orientation.integer)
8008 vertices[numtriangles*3+0] = vfirst;
8009 vertices[numtriangles*3+1] = vprev;
8010 vertices[numtriangles*3+2] = vcurrent;
8014 vertices[numtriangles*3+0] = vfirst;
8015 vertices[numtriangles*3+2] = vprev;
8016 vertices[numtriangles*3+1] = vcurrent;
8023 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8025 submodelindex = atof(argv[1]);
8026 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8028 else if (!strcmp(argv[0], "usemtl"))
8030 for (i = 0;i < numtextures;i++)
8031 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8033 if (i < numtextures)
8037 if (maxtextures <= numtextures)
8039 maxtextures = max(maxtextures * 2, 256);
8040 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8042 textureindex = numtextures++;
8043 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8048 // now that we have the OBJ data loaded as-is, we can convert it
8050 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8051 VectorCopy(mins, loadmodel->normalmins);
8052 VectorCopy(maxs, loadmodel->normalmaxs);
8053 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8054 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8055 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8056 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8057 modelradius = modelyawradius + modelradius * modelradius;
8058 modelyawradius = sqrt(modelyawradius);
8059 modelradius = sqrt(modelradius);
8060 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8061 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8062 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8063 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8064 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8065 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8066 loadmodel->radius = modelradius;
8067 loadmodel->radius2 = modelradius * modelradius;
8069 // allocate storage for triangles
8070 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8071 // allocate vertex hash structures to build an optimal vertex subset
8072 vertexhashsize = numtriangles*2;
8073 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8074 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8075 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8076 vertexhashcount = 0;
8078 // gather surface stats for assigning vertex/triangle ranges
8082 loadmodel->num_surfaces = 0;
8083 // allocate storage for the worst case number of surfaces, later we resize
8084 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8085 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8086 tempsurface = tempsurfaces;
8087 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8089 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8090 for (textureindex = 0;textureindex < numtextures;textureindex++)
8092 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8094 thisvertex = vertices + vertexindex;
8095 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8098 // skip the surface creation if there are no triangles for it
8099 if (vertexindex == numtriangles*3)
8101 // create a surface for these vertices
8102 surfacevertices = 0;
8103 surfaceelements = 0;
8104 // we hack in a texture index in the surface to be fixed up later...
8105 tempsurface->texture = (texture_t *)((size_t)textureindex);
8106 // calculate bounds as we go
8107 VectorCopy(thisvertex->v, tempsurface->mins);
8108 VectorCopy(thisvertex->v, tempsurface->maxs);
8109 for (;vertexindex < numtriangles*3;vertexindex++)
8111 thisvertex = vertices + vertexindex;
8112 if (thisvertex->submodelindex != submodelindex)
8114 if (thisvertex->textureindex != textureindex)
8116 // add vertex to surface bounds
8117 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8118 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8119 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8120 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8121 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8122 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8123 // add the vertex if it is not found in the merged set, and
8124 // get its index (triangle element) for the surface
8125 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8126 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8128 vdata = vertexhashdata + i;
8129 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8134 i = vertexhashcount++;
8135 vdata = vertexhashdata + i;
8136 *vdata = *thisvertex;
8137 vdata->nextindex = vertexhashtable[vertexhashindex];
8138 vertexhashtable[vertexhashindex] = i;
8141 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8144 surfacetriangles = surfaceelements / 3;
8145 tempsurface->num_vertices = surfacevertices;
8146 tempsurface->num_triangles = surfacetriangles;
8147 tempsurface->num_firstvertex = firstvertex;
8148 tempsurface->num_firsttriangle = firsttriangle;
8149 firstvertex += tempsurface->num_vertices;
8150 firsttriangle += tempsurface->num_triangles;
8152 loadmodel->num_surfaces++;
8155 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8156 numvertices = firstvertex;
8157 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8158 tempsurfaces = NULL;
8160 // allocate storage for final mesh data
8161 loadmodel->num_textures = numtextures * loadmodel->numskins;
8162 loadmodel->num_texturesperskin = numtextures;
8163 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) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8164 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
8165 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8166 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8167 loadmodel->surfmesh.num_vertices = numvertices;
8168 loadmodel->surfmesh.num_triangles = numtriangles;
8169 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8170 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8171 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8172 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8173 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8175 if (loadmodel->surfmesh.num_vertices <= 65536) {
8176 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8179 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8181 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8182 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8183 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8186 // load the textures
8187 for (textureindex = 0;textureindex < numtextures;textureindex++)
8188 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8189 Mod_FreeSkinFiles(skinfiles);
8191 // set the surface textures to their real values now that we loaded them...
8192 for (i = 0;i < loadmodel->num_surfaces;i++)
8193 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8197 Mem_Free(texturenames);
8201 Mem_Free(vertexhashtable);
8202 Mem_Free(vertexhashdata);
8204 // compute all the mesh information that was not loaded from the file
8205 if (loadmodel->surfmesh.data_element3s)
8206 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8207 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8208 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8209 // generate normals if the file did not have them
8210 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8211 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);
8212 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);
8214 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8215 loadmodel->brush.num_visleafs = 1;
8216 loadmodel->brush.num_leafs = 1;
8217 loadmodel->brush.num_nodes = 0;
8218 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8219 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8220 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8221 loadmodel->brush.num_pvsclusters = 1;
8222 loadmodel->brush.num_pvsclusterbytes = 1;
8223 loadmodel->brush.data_pvsclusters = nobsp_pvs;
8224 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8225 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8226 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
8227 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8228 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8229 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8230 loadmodel->brush.data_leafs->clusterindex = 0;
8231 loadmodel->brush.data_leafs->areaindex = 0;
8232 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8233 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8234 loadmodel->brush.data_leafs->numleafbrushes = 0;
8235 loadmodel->brush.data_leafs->firstleafbrush = NULL;
8236 loadmodel->brush.supportwateralpha = true;
8238 if (loadmodel->brush.numsubmodels)
8239 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8242 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8247 // duplicate the basic information
8248 dpsnprintf(name, sizeof(name), "*%i", i);
8249 mod = Mod_FindName(name, loadmodel->name);
8250 // copy the base model to this one
8252 // rename the clone back to its proper name
8253 strlcpy(mod->name, name, sizeof(mod->name));
8254 mod->brush.parentmodel = loadmodel;
8255 // textures and memory belong to the main model
8256 mod->texturepool = NULL;
8257 mod->mempool = NULL;
8258 mod->brush.GetPVS = NULL;
8259 mod->brush.FatPVS = NULL;
8260 mod->brush.BoxTouchingPVS = NULL;
8261 mod->brush.BoxTouchingLeafPVS = NULL;
8262 mod->brush.BoxTouchingVisibleLeafs = NULL;
8263 mod->brush.FindBoxClusters = NULL;
8264 mod->brush.LightPoint = NULL;
8265 mod->brush.AmbientSoundLevelsForPoint = NULL;
8267 mod->brush.submodel = i;
8268 if (loadmodel->brush.submodels)
8269 loadmodel->brush.submodels[i] = mod;
8271 // make the model surface list (used by shadowing/lighting)
8272 mod->firstmodelsurface = submodelfirstsurface[i];
8273 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8274 mod->firstmodelbrush = 0;
8275 mod->nummodelbrushes = 0;
8276 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8277 Mod_MakeSortedSurfaces(mod);
8279 VectorClear(mod->normalmins);
8280 VectorClear(mod->normalmaxs);
8282 for (j = 0;j < mod->nummodelsurfaces;j++)
8284 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8285 const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8287 if (!surface->num_vertices)
8292 VectorCopy(v3f, mod->normalmins);
8293 VectorCopy(v3f, mod->normalmaxs);
8295 for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8297 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8298 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8299 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8300 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8301 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8302 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8305 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8306 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8307 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8308 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8309 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8310 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8311 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8312 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8313 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8314 mod->yawmins[2] = mod->normalmins[2];
8315 mod->yawmaxs[2] = mod->normalmaxs[2];
8316 mod->radius = modelradius;
8317 mod->radius2 = modelradius * modelradius;
8319 // this gets altered below if sky or water is used
8320 mod->DrawSky = NULL;
8321 mod->DrawAddWaterPlanes = NULL;
8323 for (j = 0;j < mod->nummodelsurfaces;j++)
8324 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8326 if (j < mod->nummodelsurfaces)
8327 mod->DrawSky = R_Q1BSP_DrawSky;
8329 for (j = 0;j < mod->nummodelsurfaces;j++)
8330 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8332 if (j < mod->nummodelsurfaces)
8333 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8335 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8336 mod->render_bih = mod->collision_bih;
8338 // generate VBOs and other shared data before cloning submodels
8343 Mem_Free(submodelfirstsurface);
8345 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);