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 tx = loadmodel->data_textures + i;
1814 // try to load shader or external textures, but first we have to backup the texture_t because shader loading overwrites it even if it fails
1815 backuptex = loadmodel->data_textures[i];
1816 if (name[0] && (Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, loadmodel->data_textures + i, va(vabuf, sizeof(vabuf), "%s/%s", mapname, name), false, false, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL) ||
1817 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, loadmodel->data_textures + i, va(vabuf, sizeof(vabuf), "%s" , name), false, false, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL)))
1819 // set the width/height fields which are used for parsing texcoords in this bsp format
1820 tx->width = mtwidth;
1821 tx->height = mtheight;
1824 // no luck with loading shaders or external textures - restore the in-progress texture loading
1825 loadmodel->data_textures[i] = backuptex;
1827 strlcpy(tx->name, name, sizeof(tx->name));
1828 tx->width = mtwidth;
1829 tx->height = mtheight;
1830 tx->basealpha = 1.0f;
1832 // start out with no animation
1833 tx->currentframe = tx;
1834 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
1836 if (tx->name[0] == '*')
1838 if (!strncmp(tx->name, "*lava", 5))
1840 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1841 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1843 else if (!strncmp(tx->name, "*slime", 6))
1845 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1846 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1850 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1851 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1854 else if (!strncmp(tx->name, "sky", 3))
1856 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1857 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1858 // for the surface traceline we need to hit this surface as a solid...
1859 tx->supercontents |= SUPERCONTENTS_SOLID;
1863 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1864 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1867 if (cls.state != ca_dedicated)
1869 // did not find external texture via shader loading, load it from the bsp or wad3
1870 if (loadmodel->brush.ishlbsp)
1872 // internal texture overrides wad
1873 unsigned char* pixels, * freepixels;
1874 pixels = freepixels = NULL;
1876 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1878 pixels = freepixels = W_GetTextureBGRA(tx->name);
1881 tx->width = image_width;
1882 tx->height = image_height;
1883 tx->materialshaderpass->skinframes[0] = 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);
1886 Mem_Free(freepixels);
1888 else if (!strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1890 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1892 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1893 if (data && image_width == image_height * 2)
1895 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1898 else if (mtdata != NULL)
1899 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1901 else if (mtdata) // texture included
1902 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1903 // if mtdata is NULL, the "missing" texture has already been assigned to this
1904 // LadyHavoc: some Tenebrae textures get replaced by black
1905 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1906 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, 0, 0, 0, false);
1907 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1908 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, 0, 0, 0, false);
1909 tx->currentskinframe = tx->materialshaderpass->skinframes[0];
1912 tx->basematerialflags = MATERIALFLAG_WALL;
1913 if (tx->name[0] == '*')
1915 // LadyHavoc: some turbulent textures should not be affected by wateralpha
1916 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1917 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1918 else if (!strncmp(tx->name,"*lava",5)
1919 || !strncmp(tx->name,"*teleport",9)
1920 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1921 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1923 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1924 if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1925 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1927 else if (tx->name[0] == '{') // fence textures
1929 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1931 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1933 // replace the texture with black
1934 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1936 else if (!strncmp(tx->name, "sky", 3))
1937 tx->basematerialflags = MATERIALFLAG_SKY;
1938 else if (!strcmp(tx->name, "caulk"))
1939 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1940 else if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1941 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1942 tx->currentmaterialflags = tx->basematerialflags;
1944 // duplicate of sky with NOSHADOW
1945 if (tx->basematerialflags & MATERIALFLAG_SKY)
1947 *currentskynoshadowtexture = *tx;
1948 currentskynoshadowtexture->basematerialflags |= MATERIALFLAG_NOSHADOW;
1949 tx->skynoshadowtexture = currentskynoshadowtexture;
1950 currentskynoshadowtexture++;
1954 // sequence the animations
1955 for (i = 0;i < nummiptex;i++)
1957 tx = loadmodel->data_textures + i;
1958 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1961 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1963 Con_Printf("Bad animating texture %s\n", tx->name);
1966 if (tx->anim_total[0] || tx->anim_total[1])
1967 continue; // already sequenced
1969 // find the number of frames in the animation
1970 memset(anims, 0, sizeof(anims));
1971 memset(altanims, 0, sizeof(altanims));
1973 for (j = i;j < nummiptex;j++)
1975 tx2 = loadmodel->data_textures + j;
1976 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1980 if (num >= '0' && num <= '9')
1981 anims[num - '0'] = tx2;
1982 else if (num >= 'a' && num <= 'j')
1983 altanims[num - 'a'] = tx2;
1984 // No need to warn otherwise - we already did above.
1988 for (j = 0;j < 10;j++)
1995 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1998 for (j = 0;j < max;j++)
2002 Con_Printf("Missing frame %i of %s\n", j, tx->name);
2006 for (j = 0;j < altmax;j++)
2010 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
2017 // If we have exactly one frame, something's wrong.
2018 if (max + altmax <= 1)
2020 Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
2025 // if there is no alternate animation, duplicate the primary
2026 // animation into the alternate
2028 for (k = 0;k < 10;k++)
2029 altanims[k] = anims[k];
2035 Con_Printf("Missing frame 0 of %s\n", tx->name);
2037 // however, we can handle this by duplicating the alternate animation into the primary
2039 for (k = 0;k < 10;k++)
2040 anims[k] = altanims[k];
2044 // link together the primary animation
2045 for (j = 0;j < max;j++)
2048 tx2->animated = 1; // q1bsp
2049 tx2->anim_total[0] = max;
2050 tx2->anim_total[1] = altmax;
2051 for (k = 0;k < 10;k++)
2053 tx2->anim_frames[0][k] = anims[k];
2054 tx2->anim_frames[1][k] = altanims[k];
2058 // if there really is an alternate anim...
2059 if (anims[0] != altanims[0])
2061 // link together the alternate animation
2062 for (j = 0;j < altmax;j++)
2065 tx2->animated = 1; // q1bsp
2066 // the primary/alternate are reversed here
2067 tx2->anim_total[0] = altmax;
2068 tx2->anim_total[1] = max;
2069 for (k = 0;k < 10;k++)
2071 tx2->anim_frames[0][k] = altanims[k];
2072 tx2->anim_frames[1][k] = anims[k];
2079 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2082 unsigned char *in, *out, *data, d;
2083 char litfilename[MAX_QPATH];
2084 char dlitfilename[MAX_QPATH];
2085 fs_offset_t filesize;
2086 if (loadmodel->brush.ishlbsp) // LadyHavoc: load the colored lighting data straight
2088 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2089 for (i = 0;i < sb->cursize;i++)
2090 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2092 else // LadyHavoc: bsp version 29 (normal white lighting)
2094 // LadyHavoc: hope is not lost yet, check for a .lit file to load
2095 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2096 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2097 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2098 strlcat (litfilename, ".lit", sizeof (litfilename));
2099 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2100 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2103 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2105 i = LittleLong(((int *)data)[1]);
2108 if (developer_loading.integer)
2109 Con_Printf("loaded %s\n", litfilename);
2110 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2111 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2113 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2116 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2118 i = LittleLong(((int *)data)[1]);
2121 if (developer_loading.integer)
2122 Con_Printf("loaded %s\n", dlitfilename);
2123 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2124 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2125 loadmodel->brushq3.deluxemapping_modelspace = false;
2126 loadmodel->brushq3.deluxemapping = true;
2135 Con_Printf("Unknown .lit file version (%d)\n", i);
2137 else if (filesize == 8)
2138 Con_Print("Empty .lit file, ignoring\n");
2140 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2147 // LadyHavoc: oh well, expand the white lighting data
2150 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2152 out = loadmodel->brushq1.lightdata;
2153 for (i = 0;i < sb->cursize;i++)
2163 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2165 loadmodel->brushq1.num_compressedpvs = 0;
2166 loadmodel->brushq1.data_compressedpvs = NULL;
2169 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2170 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2171 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2174 // used only for HalfLife maps
2175 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2177 char key[128], value[4096];
2181 if (!COM_ParseToken_Simple(&data, false, false, true))
2183 if (com_token[0] != '{')
2187 if (!COM_ParseToken_Simple(&data, false, false, true))
2189 if (com_token[0] == '}')
2190 break; // end of worldspawn
2191 if (com_token[0] == '_')
2192 strlcpy(key, com_token + 1, sizeof(key));
2194 strlcpy(key, com_token, sizeof(key));
2195 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2196 key[strlen(key)-1] = 0;
2197 if (!COM_ParseToken_Simple(&data, false, false, true))
2199 dpsnprintf(value, sizeof(value), "%s", com_token);
2200 if (!strcmp("wad", key)) // for HalfLife maps
2202 if (loadmodel->brush.ishlbsp)
2205 for (i = 0;i < (int)sizeof(value);i++)
2206 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2208 if (i < (int)sizeof(value) && value[i])
2210 for (;i < (int)sizeof(value);i++)
2212 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2213 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2215 else if (value[i] == ';' || value[i] == 0)
2219 W_LoadTextureWadFile(&value[j], false);
2231 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2233 loadmodel->brush.entities = NULL;
2236 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2237 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2238 loadmodel->brush.entities[sb->cursize] = 0;
2239 if (loadmodel->brush.ishlbsp)
2240 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2244 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2248 int structsize = 12;
2250 if (sb->cursize % structsize)
2251 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2252 count = sb->cursize / structsize;
2253 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2255 loadmodel->brushq1.vertexes = out;
2256 loadmodel->brushq1.numvertexes = count;
2258 for ( i=0 ; i<count ; i++, out++)
2260 out->position[0] = MSG_ReadLittleFloat(sb);
2261 out->position[1] = MSG_ReadLittleFloat(sb);
2262 out->position[2] = MSG_ReadLittleFloat(sb);
2266 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2270 int structsize = (48+4*hullinfo->filehulls);
2272 if (sb->cursize % structsize)
2273 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2275 count = sb->cursize / structsize;
2276 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2278 loadmodel->brushq1.submodels = out;
2279 loadmodel->brush.numsubmodels = count;
2281 for (i = 0; i < count; i++, out++)
2283 // spread out the mins / maxs by a pixel
2284 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2285 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2286 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2287 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2288 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2289 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2290 out->origin[0] = MSG_ReadLittleFloat(sb);
2291 out->origin[1] = MSG_ReadLittleFloat(sb);
2292 out->origin[2] = MSG_ReadLittleFloat(sb);
2293 for (j = 0; j < hullinfo->filehulls; j++)
2294 out->headnode[j] = MSG_ReadLittleLong(sb);
2295 out->visleafs = MSG_ReadLittleLong(sb);
2296 out->firstface = MSG_ReadLittleLong(sb);
2297 out->numfaces = MSG_ReadLittleLong(sb);
2301 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2305 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2307 if (sb->cursize % structsize)
2308 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2309 count = sb->cursize / structsize;
2310 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2312 loadmodel->brushq1.edges = out;
2313 loadmodel->brushq1.numedges = count;
2315 for ( i=0 ; i<count ; i++, out++)
2317 if (loadmodel->brush.isbsp2)
2319 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2320 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2324 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2325 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2327 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2329 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);
2330 if(!loadmodel->brushq1.numvertexes)
2331 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2339 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2342 int i, j, k, count, miptex;
2343 int structsize = 40;
2345 if (sb->cursize % structsize)
2346 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2347 count = sb->cursize / structsize;
2348 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2350 loadmodel->brushq1.texinfo = out;
2351 loadmodel->brushq1.numtexinfo = count;
2353 for (i = 0;i < count;i++, out++)
2355 for (k = 0;k < 2;k++)
2356 for (j = 0;j < 4;j++)
2357 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2359 miptex = MSG_ReadLittleLong(sb);
2360 out->q1flags = MSG_ReadLittleLong(sb);
2362 if (out->q1flags & TEX_SPECIAL)
2364 // if texture chosen is NULL or the shader needs a lightmap,
2365 // force to notexture water shader
2366 out->textureindex = loadmodel->num_textures - 1;
2370 // if texture chosen is NULL, force to notexture
2371 out->textureindex = loadmodel->num_textures - 2;
2373 // see if the specified miptex is valid and try to use it instead
2374 if (loadmodel->data_textures)
2376 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2377 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2379 out->textureindex = miptex;
2385 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2390 mins[0] = mins[1] = mins[2] = 9999;
2391 maxs[0] = maxs[1] = maxs[2] = -9999;
2393 for (i = 0;i < numverts;i++)
2395 for (j = 0;j < 3;j++, v++)
2405 #define MAX_SUBDIVPOLYTRIANGLES 4096
2406 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2408 static int subdivpolyverts, subdivpolytriangles;
2409 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2410 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2412 static int subdivpolylookupvert(vec3_t v)
2415 for (i = 0;i < subdivpolyverts;i++)
2416 if (subdivpolyvert[i][0] == v[0]
2417 && subdivpolyvert[i][1] == v[1]
2418 && subdivpolyvert[i][2] == v[2])
2420 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2421 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2422 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2423 return subdivpolyverts++;
2426 static void SubdividePolygon(int numverts, float *verts)
2428 int i, i1, i2, i3, f, b, c, p;
2429 vec3_t mins, maxs, front[256], back[256];
2430 float m, *pv, *cv, dist[256], frac;
2433 Host_Error("SubdividePolygon: ran out of verts in buffer");
2435 BoundPoly(numverts, verts, mins, maxs);
2437 for (i = 0;i < 3;i++)
2439 m = (mins[i] + maxs[i]) * 0.5;
2440 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2441 if (maxs[i] - m < 8)
2443 if (m - mins[i] < 8)
2447 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2448 dist[c] = cv[i] - m;
2451 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2455 VectorCopy(pv, front[f]);
2460 VectorCopy(pv, back[b]);
2463 if (dist[p] == 0 || dist[c] == 0)
2465 if ((dist[p] > 0) != (dist[c] > 0) )
2468 frac = dist[p] / (dist[p] - dist[c]);
2469 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2470 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2471 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2477 SubdividePolygon(f, front[0]);
2478 SubdividePolygon(b, back[0]);
2482 i1 = subdivpolylookupvert(verts);
2483 i2 = subdivpolylookupvert(verts + 3);
2484 for (i = 2;i < numverts;i++)
2486 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2488 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2492 i3 = subdivpolylookupvert(verts + i * 3);
2493 subdivpolyindex[subdivpolytriangles][0] = i1;
2494 subdivpolyindex[subdivpolytriangles][1] = i2;
2495 subdivpolyindex[subdivpolytriangles][2] = i3;
2497 subdivpolytriangles++;
2501 //Breaks a polygon up along axial 64 unit
2502 //boundaries so that turbulent and sky warps
2503 //can be done reasonably.
2504 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2510 subdivpolytriangles = 0;
2511 subdivpolyverts = 0;
2512 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2513 if (subdivpolytriangles < 1)
2514 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2516 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2517 mesh->num_vertices = subdivpolyverts;
2518 mesh->num_triangles = subdivpolytriangles;
2519 mesh->vertex = (surfvertex_t *)(mesh + 1);
2520 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2521 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2523 for (i = 0;i < mesh->num_triangles;i++)
2524 for (j = 0;j < 3;j++)
2525 mesh->index[i*3+j] = subdivpolyindex[i][j];
2527 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2529 VectorCopy(subdivpolyvert[i], v->v);
2530 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2531 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2536 extern cvar_t gl_max_lightmapsize;
2537 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2539 msurface_t *surface;
2540 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2541 float texmins[2], texmaxs[2], val;
2542 rtexture_t *lightmaptexture, *deluxemaptexture;
2544 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2546 if (sb->cursize % structsize)
2547 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2548 count = sb->cursize / structsize;
2549 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2550 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2552 loadmodel->num_surfaces = count;
2554 loadmodel->brushq1.firstrender = true;
2555 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2559 for (surfacenum = 0;surfacenum < count;surfacenum++)
2561 if (loadmodel->brush.isbsp2)
2562 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2564 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2565 totalverts += numedges;
2566 totaltris += numedges - 2;
2569 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
2571 lightmaptexture = NULL;
2572 deluxemaptexture = r_texture_blanknormalmap;
2574 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2575 totallightmapsamples = 0;
2579 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2581 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2582 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2583 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2584 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2585 firstedge = MSG_ReadLittleLong(sb);
2586 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2587 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2588 for (i = 0;i < MAXLIGHTMAPS;i++)
2589 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2590 lightmapoffset = MSG_ReadLittleLong(sb);
2592 // FIXME: validate edges, texinfo, etc?
2593 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)
2594 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2595 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2596 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2597 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2598 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2600 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2601 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2603 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2604 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2605 lightmapoffset = -1;
2607 //surface->flags = surface->texture->flags;
2608 //if (LittleShort(in->side))
2609 // surface->flags |= SURF_PLANEBACK;
2610 //surface->plane = loadmodel->brush.data_planes + planenum;
2612 surface->num_firstvertex = totalverts;
2613 surface->num_vertices = numedges;
2614 surface->num_firsttriangle = totaltris;
2615 surface->num_triangles = numedges - 2;
2616 totalverts += numedges;
2617 totaltris += numedges - 2;
2619 // convert edges back to a normal polygon
2620 for (i = 0;i < surface->num_vertices;i++)
2622 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2624 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2626 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2628 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2629 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2630 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2631 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2632 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2633 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2634 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2635 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2638 for (i = 0;i < surface->num_triangles;i++)
2640 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2641 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2642 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2645 // compile additional data about the surface geometry
2646 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);
2647 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);
2648 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2650 // generate surface extents information
2651 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2652 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2653 for (i = 1;i < surface->num_vertices;i++)
2655 for (j = 0;j < 2;j++)
2657 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2658 texmins[j] = min(texmins[j], val);
2659 texmaxs[j] = max(texmaxs[j], val);
2662 for (i = 0;i < 2;i++)
2664 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2665 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2668 smax = surface->lightmapinfo->extents[0] >> 4;
2669 tmax = surface->lightmapinfo->extents[1] >> 4;
2670 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2671 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2674 surface->lightmaptexture = NULL;
2675 surface->deluxemaptexture = r_texture_blanknormalmap;
2676 if (lightmapoffset == -1)
2678 surface->lightmapinfo->samples = NULL;
2680 // give non-lightmapped water a 1x white lightmap
2681 if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2683 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2684 surface->lightmapinfo->styles[0] = 0;
2685 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2689 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LadyHavoc: HalfLife map (bsp version 30)
2690 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2691 else // LadyHavoc: white lighting (bsp version 29)
2693 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2694 if (loadmodel->brushq1.nmaplightdata)
2695 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2698 // check if we should apply a lightmap to this
2699 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2701 if (ssize > 256 || tsize > 256)
2702 Host_Error("Bad surface extents");
2704 if (lightmapsize < ssize)
2705 lightmapsize = ssize;
2706 if (lightmapsize < tsize)
2707 lightmapsize = tsize;
2709 totallightmapsamples += ssize*tsize;
2711 // force lightmap upload on first time seeing the surface
2713 // additionally this is used by the later code to see if a
2714 // lightmap is needed on this surface (rather than duplicating the
2716 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2717 loadmodel->lit = true;
2721 // small maps (such as ammo boxes especially) don't need big lightmap
2722 // textures, so this code tries to guess a good size based on
2723 // totallightmapsamples (size of the lightmaps lump basically), as well as
2724 // trying to max out the size if there is a lot of lightmap data to store
2725 // additionally, never choose a lightmapsize that is smaller than the
2726 // largest surface encountered (as it would fail)
2728 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2731 // now that we've decided the lightmap texture size, we can do the rest
2732 if (cls.state != ca_dedicated)
2734 int stainmapsize = 0;
2735 mod_alloclightmap_state_t allocState;
2737 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2738 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2740 int iu, iv, lightmapx = 0, lightmapy = 0;
2741 float u, v, ubase, vbase, uscale, vscale;
2743 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2746 smax = surface->lightmapinfo->extents[0] >> 4;
2747 tmax = surface->lightmapinfo->extents[1] >> 4;
2748 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2749 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2750 stainmapsize += ssize * tsize * 3;
2752 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2754 // allocate a texture pool if we need it
2755 if (loadmodel->texturepool == NULL)
2756 loadmodel->texturepool = R_AllocTexturePool();
2757 // could not find room, make a new lightmap
2758 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2759 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2760 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2761 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);
2762 if (loadmodel->brushq1.nmaplightdata)
2763 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);
2765 Mod_AllocLightmap_Reset(&allocState);
2766 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2768 surface->lightmaptexture = lightmaptexture;
2769 surface->deluxemaptexture = deluxemaptexture;
2770 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2771 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2773 uscale = 1.0f / (float)lightmapsize;
2774 vscale = 1.0f / (float)lightmapsize;
2775 ubase = lightmapx * uscale;
2776 vbase = lightmapy * vscale;
2778 for (i = 0;i < surface->num_vertices;i++)
2780 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);
2781 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);
2782 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2783 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2784 // LadyHavoc: calc lightmap data offset for vertex lighting to use
2787 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2791 if (cl_stainmaps.integer)
2793 // allocate stainmaps for permanent marks on walls and clear white
2794 unsigned char *stainsamples = NULL;
2795 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2796 memset(stainsamples, 255, stainmapsize);
2798 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2800 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2802 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2803 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2804 surface->lightmapinfo->stainsamples = stainsamples;
2805 stainsamples += ssize * tsize * 3;
2810 // generate ushort elements array if possible
2811 if (loadmodel->surfmesh.data_element3s)
2812 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2813 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2816 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2819 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2820 node->parent = parent;
2823 // this is a node, recurse to children
2824 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2825 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2826 // combine supercontents of children
2827 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2832 mleaf_t *leaf = (mleaf_t *)node;
2833 // if this is a leaf, calculate supercontents mask from all collidable
2834 // primitives in the leaf (brushes and collision surfaces)
2835 // also flag if the leaf contains any collision surfaces
2836 leaf->combinedsupercontents = 0;
2837 // combine the supercontents values of all brushes in this leaf
2838 for (j = 0;j < leaf->numleafbrushes;j++)
2839 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2840 // check if this leaf contains any collision surfaces (q3 patches)
2841 for (j = 0;j < leaf->numleafsurfaces;j++)
2843 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2844 if (surface->num_collisiontriangles)
2846 leaf->containscollisionsurfaces = true;
2847 leaf->combinedsupercontents |= surface->texture->supercontents;
2853 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2855 int i, j, count, p, child[2];
2857 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2859 if (sb->cursize % structsize)
2860 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2861 count = sb->cursize / structsize;
2863 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2864 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2866 loadmodel->brush.data_nodes = out;
2867 loadmodel->brush.num_nodes = count;
2869 for ( i=0 ; i<count ; i++, out++)
2871 p = MSG_ReadLittleLong(sb);
2872 out->plane = loadmodel->brush.data_planes + p;
2874 if (loadmodel->brush.isbsp2rmqe)
2876 child[0] = MSG_ReadLittleLong(sb);
2877 child[1] = MSG_ReadLittleLong(sb);
2878 out->mins[0] = MSG_ReadLittleShort(sb);
2879 out->mins[1] = MSG_ReadLittleShort(sb);
2880 out->mins[2] = MSG_ReadLittleShort(sb);
2881 out->maxs[0] = MSG_ReadLittleShort(sb);
2882 out->maxs[1] = MSG_ReadLittleShort(sb);
2883 out->maxs[2] = MSG_ReadLittleShort(sb);
2884 out->firstsurface = MSG_ReadLittleLong(sb);
2885 out->numsurfaces = MSG_ReadLittleLong(sb);
2887 else if (loadmodel->brush.isbsp2)
2889 child[0] = MSG_ReadLittleLong(sb);
2890 child[1] = MSG_ReadLittleLong(sb);
2891 out->mins[0] = MSG_ReadLittleFloat(sb);
2892 out->mins[1] = MSG_ReadLittleFloat(sb);
2893 out->mins[2] = MSG_ReadLittleFloat(sb);
2894 out->maxs[0] = MSG_ReadLittleFloat(sb);
2895 out->maxs[1] = MSG_ReadLittleFloat(sb);
2896 out->maxs[2] = MSG_ReadLittleFloat(sb);
2897 out->firstsurface = MSG_ReadLittleLong(sb);
2898 out->numsurfaces = MSG_ReadLittleLong(sb);
2902 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2903 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2904 if (child[0] >= count)
2906 if (child[1] >= count)
2909 out->mins[0] = MSG_ReadLittleShort(sb);
2910 out->mins[1] = MSG_ReadLittleShort(sb);
2911 out->mins[2] = MSG_ReadLittleShort(sb);
2912 out->maxs[0] = MSG_ReadLittleShort(sb);
2913 out->maxs[1] = MSG_ReadLittleShort(sb);
2914 out->maxs[2] = MSG_ReadLittleShort(sb);
2916 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2917 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2920 for (j=0 ; j<2 ; j++)
2922 // LadyHavoc: this code supports broken bsp files produced by
2923 // arguire qbsp which can produce more than 32768 nodes, any value
2924 // below count is assumed to be a node number, any other value is
2925 // assumed to be a leaf number
2929 if (p < loadmodel->brush.num_nodes)
2930 out->children[j] = loadmodel->brush.data_nodes + p;
2933 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2934 // map it to the solid leaf
2935 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2940 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2942 if (p < loadmodel->brush.num_leafs)
2943 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2946 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2947 // map it to the solid leaf
2948 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2954 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2957 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2960 int i, j, count, p, firstmarksurface, nummarksurfaces;
2961 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2963 if (sb->cursize % structsize)
2964 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2965 count = sb->cursize / structsize;
2966 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2968 loadmodel->brush.data_leafs = out;
2969 loadmodel->brush.num_leafs = count;
2970 // get visleafs from the submodel data
2971 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2972 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2973 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2974 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2976 // FIXME: this function could really benefit from some error checking
2977 for ( i=0 ; i<count ; i++, out++)
2979 out->contents = MSG_ReadLittleLong(sb);
2981 out->clusterindex = i - 1;
2982 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2983 out->clusterindex = -1;
2985 p = MSG_ReadLittleLong(sb);
2986 // ignore visofs errors on leaf 0 (solid)
2987 if (p >= 0 && out->clusterindex >= 0)
2989 if (p >= loadmodel->brushq1.num_compressedpvs)
2990 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2992 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);
2995 if (loadmodel->brush.isbsp2rmqe)
2997 out->mins[0] = MSG_ReadLittleShort(sb);
2998 out->mins[1] = MSG_ReadLittleShort(sb);
2999 out->mins[2] = MSG_ReadLittleShort(sb);
3000 out->maxs[0] = MSG_ReadLittleShort(sb);
3001 out->maxs[1] = MSG_ReadLittleShort(sb);
3002 out->maxs[2] = MSG_ReadLittleShort(sb);
3004 firstmarksurface = MSG_ReadLittleLong(sb);
3005 nummarksurfaces = MSG_ReadLittleLong(sb);
3007 else if (loadmodel->brush.isbsp2)
3009 out->mins[0] = MSG_ReadLittleFloat(sb);
3010 out->mins[1] = MSG_ReadLittleFloat(sb);
3011 out->mins[2] = MSG_ReadLittleFloat(sb);
3012 out->maxs[0] = MSG_ReadLittleFloat(sb);
3013 out->maxs[1] = MSG_ReadLittleFloat(sb);
3014 out->maxs[2] = MSG_ReadLittleFloat(sb);
3016 firstmarksurface = MSG_ReadLittleLong(sb);
3017 nummarksurfaces = MSG_ReadLittleLong(sb);
3021 out->mins[0] = MSG_ReadLittleShort(sb);
3022 out->mins[1] = MSG_ReadLittleShort(sb);
3023 out->mins[2] = MSG_ReadLittleShort(sb);
3024 out->maxs[0] = MSG_ReadLittleShort(sb);
3025 out->maxs[1] = MSG_ReadLittleShort(sb);
3026 out->maxs[2] = MSG_ReadLittleShort(sb);
3028 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
3029 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
3032 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
3034 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
3035 out->numleafsurfaces = nummarksurfaces;
3039 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
3040 out->firstleafsurface = NULL;
3041 out->numleafsurfaces = 0;
3044 for (j = 0;j < 4;j++)
3045 out->ambient_sound_level[j] = MSG_ReadByte(sb);
3049 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
3053 const unsigned char *pvs;
3054 // if there's no vis data, assume supported (because everything is visible all the time)
3055 if (!loadmodel->brush.data_pvsclusters)
3057 // check all liquid leafs to see if they can see into empty leafs, if any
3058 // can we can assume this map supports r_wateralpha
3059 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3061 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3063 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3064 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3065 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3072 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3077 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3079 if (sb->cursize % structsize)
3080 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3081 count = sb->cursize / structsize;
3082 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3084 loadmodel->brushq1.clipnodes = out;
3085 loadmodel->brushq1.numclipnodes = count;
3087 for (i = 1; i < MAX_MAP_HULLS; i++)
3089 hull = &loadmodel->brushq1.hulls[i];
3090 hull->clipnodes = out;
3091 hull->firstclipnode = 0;
3092 hull->lastclipnode = count-1;
3093 hull->planes = loadmodel->brush.data_planes;
3094 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3095 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3096 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3097 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3098 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3099 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3100 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3103 for (i=0 ; i<count ; i++, out++)
3105 out->planenum = MSG_ReadLittleLong(sb);
3106 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3107 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3108 if (loadmodel->brush.isbsp2)
3110 out->children[0] = MSG_ReadLittleLong(sb);
3111 out->children[1] = MSG_ReadLittleLong(sb);
3112 if (out->children[0] >= count)
3113 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3114 if (out->children[1] >= count)
3115 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3119 // LadyHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3120 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3121 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3122 if (out->children[0] >= count)
3123 out->children[0] -= 65536;
3124 if (out->children[1] >= count)
3125 out->children[1] -= 65536;
3130 //Duplicate the drawing hull structure as a clipping hull
3131 static void Mod_Q1BSP_MakeHull0(void)
3138 hull = &loadmodel->brushq1.hulls[0];
3140 in = loadmodel->brush.data_nodes;
3141 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3143 hull->clipnodes = out;
3144 hull->firstclipnode = 0;
3145 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3146 hull->planes = loadmodel->brush.data_planes;
3148 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3150 out->planenum = in->plane - loadmodel->brush.data_planes;
3151 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3152 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3156 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3159 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3161 if (sb->cursize % structsize)
3162 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3163 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3164 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3166 if (loadmodel->brush.isbsp2)
3168 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3170 j = MSG_ReadLittleLong(sb);
3171 if (j < 0 || j >= loadmodel->num_surfaces)
3172 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3173 loadmodel->brush.data_leafsurfaces[i] = j;
3178 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3180 j = (unsigned short) MSG_ReadLittleShort(sb);
3181 if (j >= loadmodel->num_surfaces)
3182 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3183 loadmodel->brush.data_leafsurfaces[i] = j;
3188 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3193 if (sb->cursize % structsize)
3194 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3195 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3196 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3198 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3199 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3203 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3207 int structsize = 20;
3209 if (sb->cursize % structsize)
3210 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3211 loadmodel->brush.num_planes = sb->cursize / structsize;
3212 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3214 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3216 out->normal[0] = MSG_ReadLittleFloat(sb);
3217 out->normal[1] = MSG_ReadLittleFloat(sb);
3218 out->normal[2] = MSG_ReadLittleFloat(sb);
3219 out->dist = MSG_ReadLittleFloat(sb);
3220 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3225 // fixes up sky surfaces that have SKY contents behind them, so that they do not cast shadows (e1m5 logo shadow trick).
3226 static void Mod_Q1BSP_AssignNoShadowSkySurfaces(dp_model_t *mod)
3229 msurface_t *surface;
3232 for (i = 0, surface = mod->data_surfaces + mod->firstmodelsurface; i < mod->nummodelsurfaces; i++, surface++)
3234 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3236 // check if the point behind the surface polygon is SOLID or SKY contents
3237 VectorMAMAM(0.5f, surface->mins, 0.5f, surface->maxs, -0.25f, mod->surfmesh.data_normal3f + 3*surface->num_firstvertex, center);
3238 contents = Mod_Q1BSP_PointSuperContents(mod, 0, center);
3239 if (!(contents & SUPERCONTENTS_SOLID))
3240 surface->texture = surface->texture->skynoshadowtexture;
3245 static void Mod_Q1BSP_LoadMapBrushes(void)
3249 int submodel, numbrushes;
3250 qboolean firstbrush;
3251 char *text, *maptext;
3252 char mapfilename[MAX_QPATH];
3253 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3254 strlcat (mapfilename, ".map", sizeof (mapfilename));
3255 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3259 if (!COM_ParseToken_Simple(&data, false, false, true))
3264 if (!COM_ParseToken_Simple(&data, false, false, true))
3266 if (com_token[0] != '{')
3272 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3275 if (!COM_ParseToken_Simple(&data, false, false, true))
3277 if (com_token[0] == '}')
3278 break; // end of entity
3279 if (com_token[0] == '{')
3286 if (submodel > loadmodel->brush.numsubmodels)
3288 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3292 model = loadmodel->brush.submodels[submodel];
3299 if (!COM_ParseToken_Simple(&data, false, false, true))
3301 if (com_token[0] == '}')
3302 break; // end of brush
3303 // each brush face should be this format:
3304 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3305 // FIXME: support hl .map format
3306 for (pointnum = 0;pointnum < 3;pointnum++)
3308 COM_ParseToken_Simple(&data, false, false, true);
3309 for (componentnum = 0;componentnum < 3;componentnum++)
3311 COM_ParseToken_Simple(&data, false, false, true);
3312 point[pointnum][componentnum] = atof(com_token);
3314 COM_ParseToken_Simple(&data, false, false, true);
3316 COM_ParseToken_Simple(&data, false, false, true);
3317 strlcpy(facetexture, com_token, sizeof(facetexture));
3318 COM_ParseToken_Simple(&data, false, false, true);
3319 //scroll_s = atof(com_token);
3320 COM_ParseToken_Simple(&data, false, false, true);
3321 //scroll_t = atof(com_token);
3322 COM_ParseToken_Simple(&data, false, false, true);
3323 //rotate = atof(com_token);
3324 COM_ParseToken_Simple(&data, false, false, true);
3325 //scale_s = atof(com_token);
3326 COM_ParseToken_Simple(&data, false, false, true);
3327 //scale_t = atof(com_token);
3328 TriangleNormal(point[0], point[1], point[2], planenormal);
3329 VectorNormalizeDouble(planenormal);
3330 planedist = DotProduct(point[0], planenormal);
3331 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3341 #define MAX_PORTALPOINTS 64
3343 typedef struct portal_s
3346 mnode_t *nodes[2]; // [0] = front side of plane
3347 struct portal_s *next[2];
3349 double points[3*MAX_PORTALPOINTS];
3350 struct portal_s *chain; // all portals are linked into a list
3354 static memexpandablearray_t portalarray;
3356 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3358 // process only nodes (leafs already had their box calculated)
3362 // calculate children first
3363 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3364 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3366 // make combined bounding box from children
3367 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3368 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3369 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3370 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3371 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3372 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3375 static void Mod_Q1BSP_FinalizePortals(void)
3377 int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3381 mleaf_t *leaf, *endleaf;
3383 // tally up portal and point counts and recalculate bounding boxes for all
3384 // leafs (because qbsp is very sloppy)
3385 leaf = loadmodel->brush.data_leafs;
3386 endleaf = leaf + loadmodel->brush.num_leafs;
3387 if (mod_recalculatenodeboxes.integer)
3389 for (;leaf < endleaf;leaf++)
3391 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3392 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3397 for (portalindex = 0;portalindex < portalrange;portalindex++)
3399 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3402 // note: this check must match the one below or it will usually corrupt memory
3403 // 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
3404 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3407 numpoints += p->numpoints * 2;
3410 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3411 loadmodel->brush.num_portals = numportals;
3412 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3413 loadmodel->brush.num_portalpoints = numpoints;
3414 // clear all leaf portal chains
3415 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3416 loadmodel->brush.data_leafs[i].portals = NULL;
3417 // process all portals in the global portal chain, while freeing them
3418 portal = loadmodel->brush.data_portals;
3419 point = loadmodel->brush.data_portalpoints;
3420 for (portalindex = 0;portalindex < portalrange;portalindex++)
3422 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3425 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3427 // note: this check must match the one above or it will usually corrupt memory
3428 // 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
3429 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3431 // first make the back to front portal(forward portal)
3432 portal->points = point;
3433 portal->numpoints = p->numpoints;
3434 portal->plane.dist = p->plane.dist;
3435 VectorCopy(p->plane.normal, portal->plane.normal);
3436 portal->here = (mleaf_t *)p->nodes[1];
3437 portal->past = (mleaf_t *)p->nodes[0];
3439 for (j = 0;j < portal->numpoints;j++)
3441 VectorCopy(p->points + j*3, point->position);
3444 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3445 PlaneClassify(&portal->plane);
3447 // link into leaf's portal chain
3448 portal->next = portal->here->portals;
3449 portal->here->portals = portal;
3451 // advance to next portal
3454 // then make the front to back portal(backward portal)
3455 portal->points = point;
3456 portal->numpoints = p->numpoints;
3457 portal->plane.dist = -p->plane.dist;
3458 VectorNegate(p->plane.normal, portal->plane.normal);
3459 portal->here = (mleaf_t *)p->nodes[0];
3460 portal->past = (mleaf_t *)p->nodes[1];
3462 for (j = portal->numpoints - 1;j >= 0;j--)
3464 VectorCopy(p->points + j*3, point->position);
3467 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3468 PlaneClassify(&portal->plane);
3470 // link into leaf's portal chain
3471 portal->next = portal->here->portals;
3472 portal->here->portals = portal;
3474 // advance to next portal
3477 // add the portal's polygon points to the leaf bounding boxes
3478 if (mod_recalculatenodeboxes.integer)
3480 for (i = 0;i < 2;i++)
3482 leaf = (mleaf_t *)p->nodes[i];
3483 for (j = 0;j < p->numpoints;j++)
3485 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3486 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3487 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3488 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3489 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3490 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3496 // now recalculate the node bounding boxes from the leafs
3497 if (mod_recalculatenodeboxes.integer)
3498 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3506 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3509 Host_Error("AddPortalToNodes: NULL front node");
3511 Host_Error("AddPortalToNodes: NULL back node");
3512 if (p->nodes[0] || p->nodes[1])
3513 Host_Error("AddPortalToNodes: already included");
3514 // 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
3516 p->nodes[0] = front;
3517 p->next[0] = (portal_t *)front->portals;
3518 front->portals = (mportal_t *)p;
3521 p->next[1] = (portal_t *)back->portals;
3522 back->portals = (mportal_t *)p;
3527 RemovePortalFromNode
3530 static void RemovePortalFromNodes(portal_t *portal)
3534 void **portalpointer;
3536 for (i = 0;i < 2;i++)
3538 node = portal->nodes[i];
3540 portalpointer = (void **) &node->portals;
3543 t = (portal_t *)*portalpointer;
3545 Host_Error("RemovePortalFromNodes: portal not in leaf");
3549 if (portal->nodes[0] == node)
3551 *portalpointer = portal->next[0];
3552 portal->nodes[0] = NULL;
3554 else if (portal->nodes[1] == node)
3556 *portalpointer = portal->next[1];
3557 portal->nodes[1] = NULL;
3560 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3564 if (t->nodes[0] == node)
3565 portalpointer = (void **) &t->next[0];
3566 else if (t->nodes[1] == node)
3567 portalpointer = (void **) &t->next[1];
3569 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3574 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3575 static double *portalpointsbuffer;
3576 static int portalpointsbufferoffset;
3577 static int portalpointsbuffersize;
3578 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3581 mnode_t *front, *back, *other_node;
3582 mplane_t clipplane, *plane;
3583 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3584 int numfrontpoints, numbackpoints;
3585 double *frontpoints, *backpoints;
3587 // if a leaf, we're done
3591 // get some space for our clipping operations to use
3592 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3594 portalpointsbuffersize = portalpointsbufferoffset * 2;
3595 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3597 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3598 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3599 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3600 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3602 plane = node->plane;
3604 front = node->children[0];
3605 back = node->children[1];
3607 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3609 // create the new portal by generating a polygon for the node plane,
3610 // and clipping it by all of the other portals(which came from nodes above this one)
3611 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3612 nodeportal->plane = *plane;
3614 // 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)
3615 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);
3616 nodeportal->numpoints = 4;
3617 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3618 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3620 clipplane = portal->plane;
3621 if (portal->nodes[0] == portal->nodes[1])
3622 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3623 if (portal->nodes[0] == node)
3625 else if (portal->nodes[1] == node)
3627 clipplane.dist = -clipplane.dist;
3628 VectorNegate(clipplane.normal, clipplane.normal);
3633 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3634 side = 0; // hush warning
3637 for (i = 0;i < nodeportal->numpoints*3;i++)
3638 frontpoints[i] = nodeportal->points[i];
3639 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);
3640 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3644 if (nodeportal->numpoints < 3)
3646 Con_Warn("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3647 nodeportal->numpoints = 0;
3649 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3651 Con_Warn("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3652 nodeportal->numpoints = 0;
3655 AddPortalToNodes(nodeportal, front, back);
3657 // split the portals of this node along this node's plane and assign them to the children of this node
3658 // (migrating the portals downward through the tree)
3659 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3661 if (portal->nodes[0] == portal->nodes[1])
3662 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3663 if (portal->nodes[0] == node)
3665 else if (portal->nodes[1] == node)
3669 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3670 side = 0; // hush warning
3672 nextportal = portal->next[side];
3673 if (!portal->numpoints)
3676 other_node = portal->nodes[!side];
3677 RemovePortalFromNodes(portal);
3679 // cut the portal into two portals, one on each side of the node plane
3680 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);
3682 if (!numfrontpoints)
3685 AddPortalToNodes(portal, back, other_node);
3687 AddPortalToNodes(portal, other_node, back);
3693 AddPortalToNodes(portal, front, other_node);
3695 AddPortalToNodes(portal, other_node, front);
3699 // the portal is split
3700 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3701 temp = splitportal->chain;
3702 *splitportal = *portal;
3703 splitportal->chain = temp;
3704 for (i = 0;i < numbackpoints*3;i++)
3705 splitportal->points[i] = backpoints[i];
3706 splitportal->numpoints = numbackpoints;
3707 for (i = 0;i < numfrontpoints*3;i++)
3708 portal->points[i] = frontpoints[i];
3709 portal->numpoints = numfrontpoints;
3713 AddPortalToNodes(portal, front, other_node);
3714 AddPortalToNodes(splitportal, back, other_node);
3718 AddPortalToNodes(portal, other_node, front);
3719 AddPortalToNodes(splitportal, other_node, back);
3723 Mod_Q1BSP_RecursiveNodePortals(front);
3724 Mod_Q1BSP_RecursiveNodePortals(back);
3726 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3729 static void Mod_Q1BSP_MakePortals(void)
3731 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3732 portalpointsbufferoffset = 0;
3733 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3734 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3735 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3736 Mem_Free(portalpointsbuffer);
3737 portalpointsbuffer = NULL;
3738 portalpointsbufferoffset = 0;
3739 portalpointsbuffersize = 0;
3740 Mod_Q1BSP_FinalizePortals();
3741 Mem_ExpandableArray_FreeArray(&portalarray);
3744 //Returns PVS data for a given point
3745 //(note: can return NULL)
3746 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3749 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3751 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3752 if (((mleaf_t *)node)->clusterindex >= 0)
3753 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3758 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)
3762 float d = PlaneDiff(org, node->plane);
3764 node = node->children[0];
3765 else if (d < -radius)
3766 node = node->children[1];
3769 // go down both sides
3770 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3771 node = node->children[1];
3774 // if this leaf is in a cluster, accumulate the pvs bits
3775 if (((mleaf_t *)node)->clusterindex >= 0)
3778 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3779 for (i = 0;i < pvsbytes;i++)
3780 pvsbuffer[i] |= pvs[i];
3784 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3785 //of the given point.
3786 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3788 int bytes = model->brush.num_pvsclusterbytes;
3789 bytes = min(bytes, pvsbufferlength);
3790 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3792 memset(pvsbuffer, 0xFF, bytes);
3796 memset(pvsbuffer, 0, bytes);
3797 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3801 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3806 VectorSubtract(inmaxs, inmins, size);
3807 if (cmodel->brush.ishlbsp)
3810 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3811 else if (size[0] <= 32)
3813 if (size[2] < 54) // pick the nearest of 36 or 72
3814 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3816 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3819 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3824 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3825 else if (size[0] <= 32)
3826 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3828 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3830 VectorCopy(inmins, outmins);
3831 VectorAdd(inmins, hull->clip_size, outmaxs);
3834 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);
3836 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3839 sizebuf_t lumpsb[HEADER_LUMPS];
3841 float dist, modelyawradius, modelradius;
3842 msurface_t *surface;
3843 hullinfo_t hullinfo;
3844 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3845 model_brush_lightstyleinfo_t styleinfo[256];
3846 unsigned char *datapointer;
3849 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3851 mod->type = mod_brushq1;
3853 mod->brush.ishlbsp = false;
3854 mod->brush.isbsp2rmqe = false;
3855 mod->brush.isbsp2 = false;
3856 mod->brush.isq2bsp = false;
3857 mod->brush.isq3bsp = false;
3858 mod->brush.skymasking = true;
3859 i = MSG_ReadLittleLong(&sb);
3863 mod->modeldatatypestring = "Q1BSP";
3866 mod->brush.ishlbsp = true;
3867 mod->modeldatatypestring = "HLBSP";
3869 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3870 mod->brush.isbsp2 = true;
3871 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3872 mod->modeldatatypestring = "Q1BSP2rmqe";
3874 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3875 mod->brush.isbsp2 = true;
3876 mod->modeldatatypestring = "Q1BSP2";
3879 mod->modeldatatypestring = "Unknown BSP";
3880 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);
3884 // fill in hull info
3885 VectorClear (hullinfo.hullsizes[0][0]);
3886 VectorClear (hullinfo.hullsizes[0][1]);
3887 if (mod->brush.ishlbsp)
3889 hullinfo.filehulls = 4;
3890 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3891 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3892 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3893 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3894 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3895 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3899 hullinfo.filehulls = 4;
3900 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3901 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3902 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3903 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3907 for (i = 0; i < HEADER_LUMPS; i++)
3909 int offset = MSG_ReadLittleLong(&sb);
3910 int size = MSG_ReadLittleLong(&sb);
3911 if (offset < 0 || offset + size > sb.cursize)
3912 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);
3913 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3916 mod->soundfromcenter = true;
3917 mod->TraceBox = Mod_Q1BSP_TraceBox;
3918 mod->TraceLine = Mod_Q1BSP_TraceLine;
3919 mod->TracePoint = Mod_Q1BSP_TracePoint;
3920 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3921 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3922 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3923 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3924 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3925 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3926 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3927 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3928 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3929 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3930 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3931 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3932 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3933 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3934 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3935 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3936 mod->Draw = R_Q1BSP_Draw;
3937 mod->DrawDepth = R_Q1BSP_DrawDepth;
3938 mod->DrawDebug = R_Q1BSP_DrawDebug;
3939 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3940 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3941 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3942 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3943 mod->DrawLight = R_Q1BSP_DrawLight;
3947 mod->brush.qw_md4sum = 0;
3948 mod->brush.qw_md4sum2 = 0;
3949 for (i = 0;i < HEADER_LUMPS;i++)
3952 if (i == LUMP_ENTITIES)
3954 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3955 mod->brush.qw_md4sum ^= LittleLong(temp);
3956 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3958 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3961 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3962 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3963 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3964 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3965 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3966 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3967 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3968 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3969 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3970 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3971 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3972 // load submodels before leafs because they contain the number of vis leafs
3973 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3974 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3975 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3976 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3978 for (i = 0; i < HEADER_LUMPS; i++)
3979 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3980 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3982 // check if the map supports transparent water rendering
3983 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3985 // we don't need the compressed pvs data anymore
3986 if (mod->brushq1.data_compressedpvs)
3987 Mem_Free(mod->brushq1.data_compressedpvs);
3988 mod->brushq1.data_compressedpvs = NULL;
3989 mod->brushq1.num_compressedpvs = 0;
3991 Mod_Q1BSP_MakeHull0();
3992 if (mod_bsp_portalize.integer)
3993 Mod_Q1BSP_MakePortals();
3995 mod->numframes = 2; // regular and alternate animation
3998 if (loadmodel->brush.numsubmodels)
3999 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
4001 // LadyHavoc: to clear the fog around the original quake submodel code, I
4003 // first of all, some background info on the submodels:
4004 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
4005 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
4006 // now the weird for loop itself:
4007 // the loop functions in an odd way, on each iteration it sets up the
4008 // current 'mod' model (which despite the confusing code IS the model of
4009 // the number i), at the end of the loop it duplicates the model to become
4010 // the next submodel, and loops back to set up the new submodel.
4012 // LadyHavoc: now the explanation of my sane way (which works identically):
4013 // set up the world model, then on each submodel copy from the world model
4014 // and set up the submodel with the respective model info.
4015 totalstylesurfaces = 0;
4017 for (i = 0;i < mod->brush.numsubmodels;i++)
4019 memset(stylecounts, 0, sizeof(stylecounts));
4020 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4022 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4023 for (j = 0;j < MAXLIGHTMAPS;j++)
4024 stylecounts[surface->lightmapinfo->styles[j]]++;
4026 for (k = 0;k < 255;k++)
4030 totalstylesurfaces += stylecounts[k];
4033 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4034 for (i = 0;i < mod->brush.numsubmodels;i++)
4036 // LadyHavoc: this code was originally at the end of this loop, but
4037 // has been transformed to something more readable at the start here.
4042 // duplicate the basic information
4043 dpsnprintf(name, sizeof(name), "*%i", i);
4044 mod = Mod_FindName(name, loadmodel->name);
4045 // copy the base model to this one
4047 // rename the clone back to its proper name
4048 strlcpy(mod->name, name, sizeof(mod->name));
4049 mod->brush.parentmodel = loadmodel;
4050 // textures and memory belong to the main model
4051 mod->texturepool = NULL;
4052 mod->mempool = NULL;
4053 mod->brush.GetPVS = NULL;
4054 mod->brush.FatPVS = NULL;
4055 mod->brush.BoxTouchingPVS = NULL;
4056 mod->brush.BoxTouchingLeafPVS = NULL;
4057 mod->brush.BoxTouchingVisibleLeafs = NULL;
4058 mod->brush.FindBoxClusters = NULL;
4059 mod->brush.LightPoint = NULL;
4060 mod->brush.AmbientSoundLevelsForPoint = NULL;
4063 mod->brush.submodel = i;
4065 if (loadmodel->brush.submodels)
4066 loadmodel->brush.submodels[i] = mod;
4068 bm = &mod->brushq1.submodels[i];
4070 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4071 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4073 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4074 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4077 mod->firstmodelsurface = bm->firstface;
4078 mod->nummodelsurfaces = bm->numfaces;
4080 // set node/leaf parents for this submodel
4081 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4083 // this has to occur after hull info has been set, as it uses Mod_Q1BSP_PointSuperContents
4084 Mod_Q1BSP_AssignNoShadowSkySurfaces(mod);
4086 // make the model surface list (used by shadowing/lighting)
4087 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4088 Mod_MakeSortedSurfaces(mod);
4090 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4091 // (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)
4092 VectorCopy(bm->mins, mod->normalmins);
4093 VectorCopy(bm->maxs, mod->normalmaxs);
4094 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4095 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4096 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4097 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4098 modelradius = modelyawradius + modelradius * modelradius;
4099 modelyawradius = sqrt(modelyawradius);
4100 modelradius = sqrt(modelradius);
4101 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4102 mod->yawmins[2] = mod->normalmins[2];
4103 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4104 mod->yawmaxs[2] = mod->normalmaxs[2];
4105 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4106 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4107 mod->radius = modelradius;
4108 mod->radius2 = modelradius * modelradius;
4110 // this gets altered below if sky or water is used
4111 mod->DrawSky = NULL;
4112 mod->DrawAddWaterPlanes = NULL;
4114 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4115 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4116 if (mod->nummodelsurfaces)
4118 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4119 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4121 if (j < mod->nummodelsurfaces)
4122 mod->DrawSky = R_Q1BSP_DrawSky;
4124 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4125 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4127 if (j < mod->nummodelsurfaces)
4128 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4130 // build lightstyle update chains
4131 // (used to rapidly mark lightmapupdateflags on many surfaces
4132 // when d_lightstylevalue changes)
4133 memset(stylecounts, 0, sizeof(stylecounts));
4134 for (k = 0;k < mod->nummodelsurfaces;k++)
4136 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4137 for (j = 0;j < MAXLIGHTMAPS;j++)
4138 stylecounts[surface->lightmapinfo->styles[j]]++;
4140 mod->brushq1.num_lightstyles = 0;
4141 for (k = 0;k < 255;k++)
4145 styleinfo[mod->brushq1.num_lightstyles].style = k;
4146 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4147 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4148 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4149 remapstyles[k] = mod->brushq1.num_lightstyles;
4150 mod->brushq1.num_lightstyles++;
4153 for (k = 0;k < mod->nummodelsurfaces;k++)
4155 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4156 for (j = 0;j < MAXLIGHTMAPS;j++)
4158 if (surface->lightmapinfo->styles[j] != 255)
4160 int r = remapstyles[surface->lightmapinfo->styles[j]];
4161 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4165 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4166 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4170 // LadyHavoc: empty submodel(lacrima.bsp has such a glitch)
4171 Con_Warnf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4173 //mod->brushq1.num_visleafs = bm->visleafs;
4175 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4176 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4178 if (mod_q1bsp_polygoncollisions.integer)
4180 mod->collision_bih = mod->render_bih;
4181 // point traces and contents checks still use the bsp tree
4182 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4183 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4184 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4185 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4188 // generate VBOs and other shared data before cloning submodels
4192 Mod_Q1BSP_LoadMapBrushes();
4193 //Mod_Q1BSP_ProcessLightList();
4197 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);
4200 int Mod_Q2BSP_SuperContentsFromNativeContents(int nativecontents)
4202 int supercontents = 0;
4203 if (nativecontents & CONTENTSQ2_SOLID)
4204 supercontents |= SUPERCONTENTS_SOLID;
4205 if (nativecontents & CONTENTSQ2_WATER)
4206 supercontents |= SUPERCONTENTS_WATER;
4207 if (nativecontents & CONTENTSQ2_SLIME)
4208 supercontents |= SUPERCONTENTS_SLIME;
4209 if (nativecontents & CONTENTSQ2_LAVA)
4210 supercontents |= SUPERCONTENTS_LAVA;
4211 if (nativecontents & CONTENTSQ2_MONSTER)
4212 supercontents |= SUPERCONTENTS_BODY;
4213 if (nativecontents & CONTENTSQ2_DEADMONSTER)
4214 supercontents |= SUPERCONTENTS_CORPSE;
4215 if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4216 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4217 if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4218 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4219 if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4220 supercontents |= SUPERCONTENTS_OPAQUE;
4221 return supercontents;
4224 int Mod_Q2BSP_NativeContentsFromSuperContents(int supercontents)
4226 int nativecontents = 0;
4227 if (supercontents & SUPERCONTENTS_SOLID)
4228 nativecontents |= CONTENTSQ2_SOLID;
4229 if (supercontents & SUPERCONTENTS_WATER)
4230 nativecontents |= CONTENTSQ2_WATER;
4231 if (supercontents & SUPERCONTENTS_SLIME)
4232 nativecontents |= CONTENTSQ2_SLIME;
4233 if (supercontents & SUPERCONTENTS_LAVA)
4234 nativecontents |= CONTENTSQ2_LAVA;
4235 if (supercontents & SUPERCONTENTS_BODY)
4236 nativecontents |= CONTENTSQ2_MONSTER;
4237 if (supercontents & SUPERCONTENTS_CORPSE)
4238 nativecontents |= CONTENTSQ2_DEADMONSTER;
4239 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4240 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4241 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4242 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4243 if (!(supercontents & SUPERCONTENTS_OPAQUE))
4244 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4245 return nativecontents;
4248 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4251 loadmodel->brushq1.num_compressedpvs = 0;
4252 loadmodel->brushq1.data_compressedpvs = NULL;
4253 loadmodel->brush.num_pvsclusters = 0;
4254 loadmodel->brush.num_pvsclusterbytes = 0;
4255 loadmodel->brush.data_pvsclusters = NULL;
4260 count = MSG_ReadLittleLong(sb);
4261 loadmodel->brush.num_pvsclusters = count;
4262 loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4263 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4264 for (i = 0;i < count;i++)
4266 int pvsofs = MSG_ReadLittleLong(sb);
4267 /*int phsofs = */MSG_ReadLittleLong(sb);
4268 // decompress the vis data for this cluster
4269 // (note this accesses the underlying data store of sb, which is kind of evil)
4270 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);
4272 // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4273 sb->readcount = sb->cursize;
4276 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4278 int i, j, count, p, child[2];
4280 int structsize = 28;
4282 if (sb->cursize % structsize)
4283 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4284 count = sb->cursize / structsize;
4286 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4287 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4289 loadmodel->brush.data_nodes = out;
4290 loadmodel->brush.num_nodes = count;
4292 for ( i=0 ; i<count ; i++, out++)
4294 p = MSG_ReadLittleLong(sb);
4295 out->plane = loadmodel->brush.data_planes + p;
4296 child[0] = MSG_ReadLittleLong(sb);
4297 child[1] = MSG_ReadLittleLong(sb);
4298 out->mins[0] = MSG_ReadLittleShort(sb);
4299 out->mins[1] = MSG_ReadLittleShort(sb);
4300 out->mins[2] = MSG_ReadLittleShort(sb);
4301 out->maxs[0] = MSG_ReadLittleShort(sb);
4302 out->maxs[1] = MSG_ReadLittleShort(sb);
4303 out->maxs[2] = MSG_ReadLittleShort(sb);
4304 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4305 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4306 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4308 Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4309 out->firstsurface = 0;
4310 out->numsurfaces = 0;
4312 for (j=0 ; j<2 ; j++)
4317 if (p < loadmodel->brush.num_nodes)
4318 out->children[j] = loadmodel->brush.data_nodes + p;
4321 Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4322 // map it to the solid leaf
4323 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4328 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4330 if (p < loadmodel->brush.num_leafs)
4331 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4334 Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4335 // map it to the solid leaf
4336 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4342 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
4345 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4349 int structsize = 76;
4350 int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4351 char filename[MAX_QPATH];
4353 if (sb->cursize % structsize)
4354 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4355 count = sb->cursize / structsize;
4356 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4357 loadmodel->brushq1.texinfo = out;
4358 loadmodel->brushq1.numtexinfo = count;
4359 loadmodel->num_texturesperskin = 0;
4360 loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4362 for (i = 0;i < count;i++, out++)
4365 for (k = 0;k < 2;k++)
4366 for (j = 0;j < 4;j++)
4367 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4369 out->q2flags = MSG_ReadLittleLong(sb);
4370 out->q2value = MSG_ReadLittleLong(sb);
4371 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4372 out->q2texture[31] = 0; // make absolutely sure it is terminated
4373 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4375 // find an existing match for the texture if possible
4376 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4377 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4378 if (!strcmp(filename, loadmodel->data_textures[j].name)
4379 && out->q2flags == loadmodel->data_textures[j].q2flags
4380 && out->q2value == loadmodel->data_textures[j].q2value)
4382 // if we don't find the texture, store the new texture
4383 if (j == loadmodel->num_texturesperskin)
4385 if (loadmodel->num_texturesperskin < maxtextures)
4387 texture_t *tx = loadmodel->data_textures + j;
4388 int q2flags = out->q2flags;
4389 unsigned char *walfile = NULL;
4390 fs_offset_t walfilesize = 0;
4391 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
4392 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4393 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4397 LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4407 tx->q2flags = out->q2flags;
4408 tx->q2value = out->q2value;
4409 // also modify the texture to have the correct contents and such based on flags
4410 // note that we create multiple texture_t structures if q2flags differs
4411 if (q2flags & Q2SURF_LIGHT)
4413 // doesn't mean anything to us
4415 if (q2flags & Q2SURF_SLICK)
4417 // would be nice to support...
4419 if (q2flags & Q2SURF_SKY)
4421 // sky is a rather specific thing
4422 q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4423 tx->basematerialflags = MATERIALFLAG_SKY;
4424 tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4425 tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4427 if (q2flags & Q2SURF_WARP)
4429 // we use a scroll instead of a warp
4430 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4431 // if it's also transparent, we can enable the WATERSHADER
4432 // but we do not set the WATERALPHA flag because we don't
4433 // want to honor r_wateralpha in q2bsp
4434 // (it would go against the artistic intent)
4435 if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4436 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4438 if (q2flags & Q2SURF_TRANS33)
4440 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4441 tx->basealpha = 1.0f / 3.0f;
4442 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4443 if (tx->q2contents & Q2CONTENTS_SOLID)
4444 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4446 if (q2flags & Q2SURF_TRANS66)
4448 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4449 tx->basealpha = 2.0f / 3.0f;
4450 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4451 if (tx->q2contents & Q2CONTENTS_SOLID)
4452 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4454 if ((q2flags & Q2SURF_FLOWING) && tx->materialshaderpass != NULL)
4456 tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4457 if (q2flags & Q2SURF_WARP)
4458 tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
4460 tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
4461 tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
4463 if (q2flags & Q2SURF_ALPHATEST)
4465 // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4466 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4468 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4470 if (!mod_q2bsp_littransparentsurfaces.integer)
4471 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4473 if (q2flags & Q2SURF_NODRAW)
4475 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4477 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4478 tx->q2contents |= Q2CONTENTS_DETAIL;
4479 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4480 tx->q2contents |= Q2CONTENTS_SOLID;
4481 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4483 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(tx->q2contents);
4484 // set the current values to the base values
4485 tx->currentframe = tx;
4486 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
4487 tx->currentmaterialflags = tx->basematerialflags;
4488 loadmodel->num_texturesperskin++;
4489 loadmodel->num_textures = loadmodel->num_texturesperskin;
4493 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4494 j = 0; // use first texture and give up
4497 // store the index we found for this texture
4498 out->textureindex = j;
4501 // realloc the textures array now that we know how many we actually need
4502 loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4504 // now assemble the texture chains
4505 // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier
4506 for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4509 texture_t *t = loadmodel->data_textures + out->textureindex;
4510 t->currentframe = t; // fix the reallocated pointer
4512 // if this is not animated, skip it
4513 // if this is already processed, skip it (part of an existing sequence)
4514 if (out->q2nexttexinfo == 0 || t->animated)
4517 // store the array of frames to use
4518 t->animated = 2; // q2bsp animation
4519 t->anim_total[0] = 0;
4520 t->anim_total[1] = 0;
4521 // gather up to 10 frames (we don't support more)
4522 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)
4524 // detect looping and stop there
4525 if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4527 t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4529 // we could look for the +a sequence here if this is the +0 sequence,
4530 // but it seems that quake2 did not implement that (even though the
4531 // files exist in the baseq2 content)
4533 // write the frame sequence to all the textures involved (just like
4534 // in the q1bsp loader)
4536 // note that this can overwrite the rest of the sequence - so if the
4537 // start of a sequence is found later than the other parts of the
4538 // sequence, it will go back and rewrite them correctly.
4539 for (k = 0;k < t->anim_total[0];k++)
4541 texture_t *txk = t->anim_frames[0][k];
4542 txk->animated = t->animated;
4543 txk->anim_total[0] = t->anim_total[0];
4544 for (l = 0;l < t->anim_total[0];l++)
4545 txk->anim_frames[0][l] = t->anim_frames[0][l];
4550 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4552 // LadyHavoc: this fits exactly the same format that we use in .lit files
4553 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4554 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4557 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4560 int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4561 int structsize = 28;
4563 if (sb->cursize % structsize)
4564 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4565 count = sb->cursize / structsize;
4566 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4568 loadmodel->brush.data_leafs = out;
4569 loadmodel->brush.num_leafs = count;
4571 // FIXME: this function could really benefit from some error checking
4572 for ( i=0 ; i<count ; i++, out++)
4574 out->contents = MSG_ReadLittleLong(sb);
4575 out->clusterindex = MSG_ReadLittleShort(sb);
4576 out->areaindex = MSG_ReadLittleShort(sb);
4577 out->mins[0] = MSG_ReadLittleShort(sb);
4578 out->mins[1] = MSG_ReadLittleShort(sb);
4579 out->mins[2] = MSG_ReadLittleShort(sb);
4580 out->maxs[0] = MSG_ReadLittleShort(sb);
4581 out->maxs[1] = MSG_ReadLittleShort(sb);
4582 out->maxs[2] = MSG_ReadLittleShort(sb);
4584 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4585 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4586 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4587 nummarkbrushes = (unsigned short)MSG_ReadLittleShort(sb);
4589 for (j = 0;j < 4;j++)
4590 out->ambient_sound_level[j] = 0;
4592 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4594 Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4595 out->clusterindex = -1;
4598 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4600 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4601 out->numleafsurfaces = nummarksurfaces;
4605 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4606 out->firstleafsurface = NULL;
4607 out->numleafsurfaces = 0;
4610 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4612 out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4613 out->numleafbrushes = nummarkbrushes;
4617 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4618 out->firstleafbrush = NULL;
4619 out->numleafbrushes = 0;
4624 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4629 if (sb->cursize % structsize)
4630 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4631 loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4632 loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4634 for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4636 j = (unsigned short) MSG_ReadLittleShort(sb);
4637 if (j >= loadmodel->brush.num_brushes)
4638 Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4639 loadmodel->brush.data_leafbrushes[i] = j;
4643 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4645 q3mbrushside_t *out;
4649 if (sb->cursize % structsize)
4650 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4651 count = sb->cursize / structsize;
4652 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4654 loadmodel->brush.data_brushsides = out;
4655 loadmodel->brush.num_brushsides = count;
4657 for (i = 0;i < count;i++, out++)
4659 n = (unsigned short)MSG_ReadLittleShort(sb);
4660 if (n < 0 || n >= loadmodel->brush.num_planes)
4661 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4662 out->plane = loadmodel->brush.data_planes + n;
4663 n = MSG_ReadLittleShort(sb);
4666 if (n >= loadmodel->brushq1.numtexinfo)
4667 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4668 out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4672 //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4673 out->texture = &mod_q1bsp_texture_solid;
4678 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4681 int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4682 colplanef_t *planes;
4683 int structsize = 12;
4684 qboolean brushmissingtextures;
4685 int numbrushesmissingtextures = 0;
4686 int numcreatedtextures = 0;
4688 if (sb->cursize % structsize)
4689 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4690 count = sb->cursize / structsize;
4691 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4693 loadmodel->brush.data_brushes = out;
4694 loadmodel->brush.num_brushes = count;
4699 for (i = 0; i < count; i++, out++)
4701 firstside = MSG_ReadLittleLong(sb);
4702 numsides = MSG_ReadLittleLong(sb);
4703 contents = MSG_ReadLittleLong(sb);
4704 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4705 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4707 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4708 out->numbrushsides = numsides;
4709 // convert the contents to our values
4710 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(contents);
4712 // problem: q2bsp brushes have contents but not a texture
4713 // problem: q2bsp brushsides *may* have a texture or may not
4714 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4715 // solution: nasty hacks
4716 brushmissingtextures = false;
4717 out->texture = NULL;
4718 for (j = 0; j < out->numbrushsides; j++)
4720 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4721 brushmissingtextures = true;
4724 // if we can find a matching texture on a brush side we can use it instead of creating one
4725 if (out->firstbrushside[j].texture->supercontents == supercontents)
4726 out->texture = out->firstbrushside[j].texture;
4729 if (brushmissingtextures || out->texture == NULL)
4731 numbrushesmissingtextures++;
4732 // if we didn't find any appropriate texture (matching contents), we'll have to create one
4733 // we could search earlier ones for a matching one but that can be slow
4734 if (out->texture == NULL)
4736 texture_t *validtexture;
4737 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4738 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4739 validtexture->surfaceflags = 0;
4740 validtexture->supercontents = supercontents;
4741 numcreatedtextures++;
4742 out->texture = validtexture;
4744 // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4745 for (j = 0; j < out->numbrushsides; j++)
4746 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4747 out->firstbrushside[j].texture = out->texture;
4750 // make a colbrush from the brush
4752 // make a list of mplane_t structs to construct a colbrush from
4753 if (maxplanes < out->numbrushsides)
4755 maxplanes = out->numbrushsides;
4758 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4760 for (j = 0;j < out->numbrushsides;j++)
4762 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4763 planes[j].dist = out->firstbrushside[j].plane->dist;
4764 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4765 planes[j].texture = out->firstbrushside[j].texture;
4766 q3surfaceflags |= planes[j].q3surfaceflags;
4768 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4770 // this whole loop can take a while (e.g. on redstarrepublic4)
4771 CL_KeepaliveMessage(false);
4775 if (numcreatedtextures)
4776 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);
4779 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4781 // 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)
4782 sb->readcount = sb->cursize;
4785 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4787 // we currently don't use areas, they represent closable doors as vis blockers
4788 sb->readcount = sb->cursize;
4791 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4793 // we currently don't use areas, they represent closable doors as vis blockers
4794 sb->readcount = sb->cursize;
4797 static void Mod_Q2BSP_LoadSubmodels(sizebuf_t *sb)
4801 int structsize = 48;
4803 if (sb->cursize % structsize)
4804 Host_Error ("Mod_Q2BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
4806 count = sb->cursize / structsize;
4807 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
4809 loadmodel->brushq1.submodels = out;
4810 loadmodel->brush.numsubmodels = count;
4812 // this is identical to the q1 submodel structure except for having 1 hull
4813 for (i = 0; i < count; i++, out++)
4815 // spread out the mins / maxs by a pixel
4816 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
4817 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
4818 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
4819 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
4820 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
4821 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
4822 out->origin[0] = MSG_ReadLittleFloat(sb);
4823 out->origin[1] = MSG_ReadLittleFloat(sb);
4824 out->origin[2] = MSG_ReadLittleFloat(sb);
4825 out->headnode[0] = MSG_ReadLittleLong(sb);
4826 out->firstface = MSG_ReadLittleLong(sb);
4827 out->numfaces = MSG_ReadLittleLong(sb);
4831 static void Mod_Q2BSP_FindSubmodelBrushRange_r(dp_model_t *mod, mnode_t *node, int *first, int *last)
4837 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4838 node = node->children[1];
4840 leaf = (mleaf_t*)node;
4841 for (i = 0;i < leaf->numleafbrushes;i++)
4843 int brushnum = leaf->firstleafbrush[i];
4844 if (*first > brushnum)
4846 if (*last < brushnum)
4851 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4854 sizebuf_t lumpsb[Q2HEADER_LUMPS];
4856 float dist, modelyawradius, modelradius;
4857 msurface_t *surface;
4858 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4859 model_brush_lightstyleinfo_t styleinfo[256];
4860 unsigned char *datapointer;
4863 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4865 mod->type = mod_brushq2;
4867 mod->brush.ishlbsp = false;
4868 mod->brush.isbsp2rmqe = false;
4869 mod->brush.isbsp2 = false;
4870 mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4871 mod->brush.isq3bsp = false;
4872 mod->brush.skymasking = true;
4873 mod->modeldatatypestring = "Q2BSP";
4875 i = MSG_ReadLittleLong(&sb);
4876 if (i != Q2BSPMAGIC)
4877 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4879 i = MSG_ReadLittleLong(&sb);
4880 if (i != Q2BSPVERSION)
4881 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4884 for (i = 0; i < Q2HEADER_LUMPS; i++)
4886 int offset = MSG_ReadLittleLong(&sb);
4887 int size = MSG_ReadLittleLong(&sb);
4888 if (offset < 0 || offset + size > sb.cursize)
4889 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);
4890 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4893 mod->soundfromcenter = true;
4894 mod->TracePoint = Mod_CollisionBIH_TracePoint;
4895 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4896 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4897 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4898 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4899 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4900 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4901 mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4902 mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4903 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
4904 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
4905 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
4906 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
4907 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
4908 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
4909 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
4910 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
4911 mod->brush.AmbientSoundLevelsForPoint = NULL;
4912 mod->brush.RoundUpToHullSize = NULL;
4913 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
4914 mod->Draw = R_Q1BSP_Draw;
4915 mod->DrawDepth = R_Q1BSP_DrawDepth;
4916 mod->DrawDebug = R_Q1BSP_DrawDebug;
4917 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
4918 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
4919 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
4920 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
4921 mod->DrawLight = R_Q1BSP_DrawLight;
4925 mod->brush.qw_md4sum = 0;
4926 mod->brush.qw_md4sum2 = 0;
4927 for (i = 0;i < Q2HEADER_LUMPS;i++)
4930 if (i == Q2LUMP_ENTITIES)
4932 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4933 mod->brush.qw_md4sum ^= LittleLong(temp);
4934 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4936 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4939 // many of these functions are identical to Q1 loaders, so we use those where possible
4940 Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4941 Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4942 Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4943 Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4944 Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4945 Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4946 Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4947 Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4948 Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4949 Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4950 Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4951 Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4952 Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4953 Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4954 Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4955 Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4956 Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4957 Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4958 Mod_Q2BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS]);
4960 for (i = 0; i < Q2HEADER_LUMPS; i++)
4961 if (lumpsb[i].readcount != lumpsb[i].cursize)
4962 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4964 // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4965 // doesn't enable the cvar, just indicates that transparent water is OK
4966 loadmodel->brush.supportwateralpha = true;
4968 // we don't need the compressed pvs data anymore
4969 if (mod->brushq1.data_compressedpvs)
4970 Mem_Free(mod->brushq1.data_compressedpvs);
4971 mod->brushq1.data_compressedpvs = NULL;
4972 mod->brushq1.num_compressedpvs = 0;
4974 // the MakePortals code works fine on the q2bsp data as well
4975 if (mod_bsp_portalize.integer)
4976 Mod_Q1BSP_MakePortals();
4978 mod->numframes = 0; // q2bsp animations are kind of special, frame is unbounded...
4981 if (loadmodel->brush.numsubmodels)
4982 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
4984 totalstylesurfaces = 0;
4986 for (i = 0;i < mod->brush.numsubmodels;i++)
4988 memset(stylecounts, 0, sizeof(stylecounts));
4989 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4991 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4992 for (j = 0;j < MAXLIGHTMAPS;j++)
4993 stylecounts[surface->lightmapinfo->styles[j]]++;
4995 for (k = 0;k < 255;k++)
4999 totalstylesurfaces += stylecounts[k];
5002 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
5003 // set up the world model, then on each submodel copy from the world model
5004 // and set up the submodel with the respective model info.
5006 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
5008 mnode_t *rootnode = NULL;
5009 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
5013 // duplicate the basic information
5014 dpsnprintf(name, sizeof(name), "*%i", i);
5015 mod = Mod_FindName(name, loadmodel->name);
5016 // copy the base model to this one
5018 // rename the clone back to its proper name
5019 strlcpy(mod->name, name, sizeof(mod->name));
5020 mod->brush.parentmodel = loadmodel;
5021 // textures and memory belong to the main model
5022 mod->texturepool = NULL;
5023 mod->mempool = NULL;
5024 mod->brush.GetPVS = NULL;
5025 mod->brush.FatPVS = NULL;
5026 mod->brush.BoxTouchingPVS = NULL;
5027 mod->brush.BoxTouchingLeafPVS = NULL;
5028 mod->brush.BoxTouchingVisibleLeafs = NULL;
5029 mod->brush.FindBoxClusters = NULL;
5030 mod->brush.LightPoint = NULL;
5031 mod->brush.AmbientSoundLevelsForPoint = NULL;
5033 mod->brush.submodel = i;
5034 if (loadmodel->brush.submodels)
5035 loadmodel->brush.submodels[i] = mod;
5037 bm = &mod->brushq1.submodels[i];
5039 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5040 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5042 mod->firstmodelsurface = bm->firstface;
5043 mod->nummodelsurfaces = bm->numfaces;
5045 // set node/leaf parents for this submodel
5046 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5047 // (this happens in base3.bsp)
5048 if (bm->headnode[0] >= 0)
5049 rootnode = mod->brush.data_nodes + bm->headnode[0];
5051 rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5052 Mod_Q1BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5054 // make the model surface list (used by shadowing/lighting)
5055 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
5056 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5057 if (firstbrush <= lastbrush)
5059 mod->firstmodelbrush = firstbrush;
5060 mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5064 mod->firstmodelbrush = 0;
5065 mod->nummodelbrushes = 0;
5067 Mod_MakeSortedSurfaces(mod);
5069 VectorCopy(bm->mins, mod->normalmins);
5070 VectorCopy(bm->maxs, mod->normalmaxs);
5071 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5072 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5073 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5074 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5075 modelradius = modelyawradius + modelradius * modelradius;
5076 modelyawradius = sqrt(modelyawradius);
5077 modelradius = sqrt(modelradius);
5078 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5079 mod->yawmins[2] = mod->normalmins[2];
5080 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
5081 mod->yawmaxs[2] = mod->normalmaxs[2];
5082 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5083 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5084 mod->radius = modelradius;
5085 mod->radius2 = modelradius * modelradius;
5087 // this gets altered below if sky or water is used
5088 mod->DrawSky = NULL;
5089 mod->DrawAddWaterPlanes = NULL;
5091 // scan surfaces for sky and water and flag the submodel as possessing these features or not
5092 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5093 if (mod->nummodelsurfaces)
5095 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5096 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
5098 if (j < mod->nummodelsurfaces)
5099 mod->DrawSky = R_Q1BSP_DrawSky;
5101 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5102 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
5104 if (j < mod->nummodelsurfaces)
5105 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
5107 // build lightstyle update chains
5108 // (used to rapidly mark lightmapupdateflags on many surfaces
5109 // when d_lightstylevalue changes)
5110 memset(stylecounts, 0, sizeof(stylecounts));
5111 for (k = 0;k < mod->nummodelsurfaces;k++)
5113 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5114 for (j = 0;j < MAXLIGHTMAPS;j++)
5115 stylecounts[surface->lightmapinfo->styles[j]]++;
5117 mod->brushq1.num_lightstyles = 0;
5118 for (k = 0;k < 255;k++)
5122 styleinfo[mod->brushq1.num_lightstyles].style = k;
5123 styleinfo[mod->brushq1.num_lightstyles].value = 0;
5124 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5125 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
5126 remapstyles[k] = mod->brushq1.num_lightstyles;
5127 mod->brushq1.num_lightstyles++;
5130 for (k = 0;k < mod->nummodelsurfaces;k++)
5132 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5133 for (j = 0;j < MAXLIGHTMAPS;j++)
5135 if (surface->lightmapinfo->styles[j] != 255)
5137 int r = remapstyles[surface->lightmapinfo->styles[j]];
5138 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
5142 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
5143 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5147 Con_Warnf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5149 //mod->brushq1.num_visleafs = bm->visleafs;
5151 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5152 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5154 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5155 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5157 // generate VBOs and other shared data before cloning submodels
5163 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);
5166 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents);
5167 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents);
5169 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5172 char key[128], value[MAX_INPUTLINE];
5174 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5175 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5176 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5179 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5180 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5181 loadmodel->brush.entities[l->filelen] = 0;
5182 data = loadmodel->brush.entities;
5183 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5184 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5185 loadmodel->brushq3.deluxemapping = false;
5186 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5190 if (!COM_ParseToken_Simple(&data, false, false, true))
5192 if (com_token[0] == '}')
5193 break; // end of worldspawn
5194 if (com_token[0] == '_')
5195 strlcpy(key, com_token + 1, sizeof(key));
5197 strlcpy(key, com_token, sizeof(key));
5198 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5199 key[strlen(key)-1] = 0;
5200 if (!COM_ParseToken_Simple(&data, false, false, true))
5202 strlcpy(value, com_token, sizeof(value));
5203 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5205 #if _MSC_VER >= 1400
5206 #define sscanf sscanf_s
5209 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5210 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5212 VectorSet(v, 64, 64, 128);
5213 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5214 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]);
5215 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5216 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5219 else if (!strcmp("deluxeMaps", key))
5221 if (!strcmp(com_token, "1"))
5223 loadmodel->brushq3.deluxemapping = true;
5224 loadmodel->brushq3.deluxemapping_modelspace = true;
5226 else if (!strcmp(com_token, "2"))
5228 loadmodel->brushq3.deluxemapping = true;
5229 loadmodel->brushq3.deluxemapping_modelspace = false;
5236 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5242 in = (q3dtexture_t *)(mod_base + l->fileofs);
5243 if (l->filelen % sizeof(*in))
5244 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5245 count = l->filelen / sizeof(*in);
5246 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5248 loadmodel->data_textures = out;
5249 loadmodel->num_textures = count;
5250 loadmodel->num_texturesperskin = loadmodel->num_textures;
5252 for (i = 0;i < count;i++)
5254 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5255 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5256 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
5257 // restore the surfaceflags and supercontents
5258 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5259 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5263 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5269 in = (q3dplane_t *)(mod_base + l->fileofs);
5270 if (l->filelen % sizeof(*in))
5271 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5272 count = l->filelen / sizeof(*in);
5273 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5275 loadmodel->brush.data_planes = out;
5276 loadmodel->brush.num_planes = count;
5278 for (i = 0;i < count;i++, in++, out++)
5280 out->normal[0] = LittleFloat(in->normal[0]);
5281 out->normal[1] = LittleFloat(in->normal[1]);
5282 out->normal[2] = LittleFloat(in->normal[2]);
5283 out->dist = LittleFloat(in->dist);
5288 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5291 q3mbrushside_t *out;
5294 in = (q3dbrushside_t *)(mod_base + l->fileofs);
5295 if (l->filelen % sizeof(*in))
5296 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5297 count = l->filelen / sizeof(*in);
5298 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5300 loadmodel->brush.data_brushsides = out;
5301 loadmodel->brush.num_brushsides = count;
5303 for (i = 0;i < count;i++, in++, out++)
5305 n = LittleLong(in->planeindex);
5306 if (n < 0 || n >= loadmodel->brush.num_planes)
5307 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5308 out->plane = loadmodel->brush.data_planes + n;
5309 n = LittleLong(in->textureindex);
5310 if (n < 0 || n >= loadmodel->num_textures)
5311 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5312 out->texture = loadmodel->data_textures + n;
5316 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5318 q3dbrushside_ig_t *in;
5319 q3mbrushside_t *out;
5322 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5323 if (l->filelen % sizeof(*in))
5324 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5325 count = l->filelen / sizeof(*in);
5326 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5328 loadmodel->brush.data_brushsides = out;
5329 loadmodel->brush.num_brushsides = count;
5331 for (i = 0;i < count;i++, in++, out++)
5333 n = LittleLong(in->planeindex);
5334 if (n < 0 || n >= loadmodel->brush.num_planes)
5335 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5336 out->plane = loadmodel->brush.data_planes + n;
5337 n = LittleLong(in->textureindex);
5338 if (n < 0 || n >= loadmodel->num_textures)
5339 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5340 out->texture = loadmodel->data_textures + n;
5344 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5348 int i, j, n, c, count, maxplanes, q3surfaceflags;
5349 colplanef_t *planes;
5351 in = (q3dbrush_t *)(mod_base + l->fileofs);
5352 if (l->filelen % sizeof(*in))
5353 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5354 count = l->filelen / sizeof(*in);
5355 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5357 loadmodel->brush.data_brushes = out;
5358 loadmodel->brush.num_brushes = count;
5363 for (i = 0;i < count;i++, in++, out++)
5365 n = LittleLong(in->firstbrushside);
5366 c = LittleLong(in->numbrushsides);
5367 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5368 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5369 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5370 out->numbrushsides = c;
5371 n = LittleLong(in->textureindex);
5372 if (n < 0 || n >= loadmodel->num_textures)
5373 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5374 out->texture = loadmodel->data_textures + n;
5376 // make a list of mplane_t structs to construct a colbrush from
5377 if (maxplanes < out->numbrushsides)
5379 maxplanes = out->numbrushsides;
5382 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5385 for (j = 0;j < out->numbrushsides;j++)
5387 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5388 planes[j].dist = out->firstbrushside[j].plane->dist;
5389 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5390 planes[j].texture = out->firstbrushside[j].texture;
5391 q3surfaceflags |= planes[j].q3surfaceflags;
5393 // make the colbrush from the planes
5394 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5396 // this whole loop can take a while (e.g. on redstarrepublic4)
5397 CL_KeepaliveMessage(false);
5403 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5409 in = (q3deffect_t *)(mod_base + l->fileofs);
5410 if (l->filelen % sizeof(*in))
5411 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5412 count = l->filelen / sizeof(*in);
5413 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5415 loadmodel->brushq3.data_effects = out;
5416 loadmodel->brushq3.num_effects = count;
5418 for (i = 0;i < count;i++, in++, out++)
5420 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5421 n = LittleLong(in->brushindex);
5422 if (n >= loadmodel->brush.num_brushes)
5424 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5427 out->brushindex = n;
5428 out->unknown = LittleLong(in->unknown);
5432 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5437 in = (q3dvertex_t *)(mod_base + l->fileofs);
5438 if (l->filelen % sizeof(*in))
5439 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5440 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5441 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5442 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5443 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5444 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5445 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5447 for (i = 0;i < count;i++, in++)
5449 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5450 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5451 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5452 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5453 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5454 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5455 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5456 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5457 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5458 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5459 // svector/tvector are calculated later in face loading
5460 if(mod_q3bsp_sRGBlightmaps.integer)
5462 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5463 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5464 // working like this may be odd, but matches q3map2 -gamma 2.2
5465 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5467 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5468 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5469 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5470 // we fix the brightness consistently via lightmapscale
5474 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5475 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5476 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5481 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5483 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5484 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5485 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5489 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5490 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5491 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5494 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5495 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5496 loadmodel->lit = true;
5500 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5506 in = (int *)(mod_base + l->fileofs);
5507 if (l->filelen % sizeof(int[3]))
5508 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5509 count = l->filelen / sizeof(*in);
5511 if(!loadmodel->brushq3.num_vertices)
5514 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5515 loadmodel->brushq3.num_triangles = 0;
5519 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5520 loadmodel->brushq3.num_triangles = count / 3;
5521 loadmodel->brushq3.data_element3i = out;
5523 for (i = 0;i < count;i++, in++, out++)
5525 *out = LittleLong(*in);
5526 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5528 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5534 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5536 q3dlightmap_t *input_pointer;
5554 int mergedrowsxcolumns;
5559 unsigned char *mergedpixels;
5560 unsigned char *mergeddeluxepixels;
5561 unsigned char *mergebuf;
5562 char mapname[MAX_QPATH];
5564 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5567 // defaults for q3bsp
5574 loadmodel->brushq3.lightmapsize = 128;
5576 if (cls.state == ca_dedicated)
5579 if(mod_q3bsp_nolightmaps.integer)
5585 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5586 if (developer_loading.integer)
5587 Con_Printf("Using internal lightmaps\n");
5588 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5589 if (l->filelen % sizeof(*input_pointer))
5590 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5591 count = l->filelen / sizeof(*input_pointer);
5592 for(i = 0; i < count; ++i)
5593 inpixels[i] = input_pointer[i].rgb;
5597 // no internal lightmaps
5598 // try external lightmaps
5599 if (developer_loading.integer)
5600 Con_Printf("Using external lightmaps\n");
5601 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5602 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5606 // using EXTERNAL lightmaps instead
5607 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5609 Mem_Free(inpixels[0]);
5610 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5620 for(count = 1; ; ++count)
5622 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5623 if(!inpixels[count])
5624 break; // we got all of them
5625 if(image_width != size || image_height != size)
5627 Mem_Free(inpixels[count]);
5628 inpixels[count] = NULL;
5629 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);
5635 loadmodel->brushq3.lightmapsize = size;
5636 loadmodel->brushq3.num_originallightmaps = count;
5638 // now check the surfaces to see if any of them index an odd numbered
5639 // lightmap, if so this is not a deluxemapped bsp file
5641 // also check what lightmaps are actually used, because q3map2 sometimes
5642 // (always?) makes an unused one at the end, which
5643 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5644 // reason when only one lightmap is used, which can throw off the
5645 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5646 // to see if the second lightmap is blank, if so it is not deluxemapped.
5647 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5648 // in Mod_Q3BSP_LoadEntities was failed
5649 if (!loadmodel->brushq3.deluxemapping)
5651 loadmodel->brushq3.deluxemapping = !(count & 1);
5652 loadmodel->brushq3.deluxemapping_modelspace = true;
5654 if (loadmodel->brushq3.deluxemapping)
5656 int facecount = faceslump->filelen / sizeof(q3dface_t);
5657 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5658 for (i = 0;i < facecount;i++)
5660 j = LittleLong(faces[i].lightmapindex);
5663 endlightmap = max(endlightmap, j + 1);
5664 if ((j & 1) || j + 1 >= count)
5666 loadmodel->brushq3.deluxemapping = false;
5673 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5674 // reason when only one lightmap is used, which can throw off the
5675 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5676 // to see if the second lightmap is blank, if so it is not deluxemapped.
5678 // further research has shown q3map2 sometimes creates a deluxemap and two
5679 // blank lightmaps, which must be handled properly as well
5680 if (endlightmap == 1 && count > 1)
5683 for (i = 0;i < size*size;i++)
5685 if (c[bytesperpixel*i + rgbmap[0]])
5687 if (c[bytesperpixel*i + rgbmap[1]])
5689 if (c[bytesperpixel*i + rgbmap[2]])
5694 // all pixels in the unused lightmap were black...
5695 loadmodel->brushq3.deluxemapping = false;
5700 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5702 // figure out what the most reasonable merge power is within limits
5704 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5705 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5707 // figure out how big the merged texture has to be
5708 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5709 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5710 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5712 mergedwidth = mergegoal;
5713 mergedheight = mergegoal;
5714 // choose non-square size (2x1 aspect) if only half the space is used;
5715 // this really only happens when the entire set fits in one texture, if
5716 // there are multiple textures, we don't worry about shrinking the last
5717 // one to fit, because the driver prefers the same texture size on
5718 // consecutive draw calls...
5719 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5722 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5723 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5724 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5725 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5726 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5727 loadmodel->brushq3.num_lightmapmergedheightpower++;
5728 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5730 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5731 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5732 powerxy = powerx+powery;
5733 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5735 mergedcolumns = 1 << powerx;
5736 mergedrows = 1 << powery;
5737 mergedrowsxcolumns = 1 << powerxy;
5739 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5740 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5741 if (loadmodel->brushq3.deluxemapping)
5742 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5744 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5745 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5746 for (i = 0;i < count;i++)
5748 // figure out which merged lightmap texture this fits into
5749 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5750 lightmapindex = i >> powerdxy;
5752 // choose the destination address
5753 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5754 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5755 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5756 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);
5758 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5759 for (j = 0;j < size;j++)
5760 for (k = 0;k < size;k++)
5762 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5763 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5764 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5765 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5768 // upload texture if this was the last tile being written to the texture
5769 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5771 if (loadmodel->brushq3.deluxemapping && (i & 1))
5772 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);
5775 if(mod_q3bsp_sRGBlightmaps.integer)
5778 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5780 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5781 // we fix the brightness consistently via lightmapscale
5784 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5785 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);
5789 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5790 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5791 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);
5797 if (mergeddeluxepixels)
5798 Mem_Free(mergeddeluxepixels);
5799 Mem_Free(mergedpixels);
5802 for(i = 0; i < count; ++i)
5803 Mem_Free(inpixels[i]);
5807 typedef struct patchtess_s
5811 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5814 float *originalvertex3f;
5817 #define PATCHTESS_SAME_LODGROUP(a,b) \
5819 (a).lodgroup[0] == (b).lodgroup[0] && \
5820 (a).lodgroup[1] == (b).lodgroup[1] && \
5821 (a).lodgroup[2] == (b).lodgroup[2] && \
5822 (a).lodgroup[3] == (b).lodgroup[3] && \
5823 (a).lodgroup[4] == (b).lodgroup[4] && \
5824 (a).lodgroup[5] == (b).lodgroup[5] \
5827 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5829 q3dface_t *in, *oldin;
5830 msurface_t *out, *oldout;
5831 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;
5832 float lightmaptcbase[2], lightmaptcscale[2];
5833 //int *originalelement3i;
5834 float *originalvertex3f;
5835 //float *originalsvector3f;
5836 //float *originaltvector3f;
5837 float *originalnormal3f;
5838 float *originalcolor4f;
5839 float *originaltexcoordtexture2f;
5840 float *originaltexcoordlightmap2f;
5841 float *surfacecollisionvertex3f;
5842 int *surfacecollisionelement3i;
5844 patchtess_t *patchtess = NULL;
5845 int patchtesscount = 0;
5848 in = (q3dface_t *)(mod_base + l->fileofs);
5849 if (l->filelen % sizeof(*in))
5850 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5851 count = l->filelen / sizeof(*in);
5852 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5854 loadmodel->data_surfaces = out;
5855 loadmodel->num_surfaces = count;
5858 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5866 for (;i < count;i++, in++, out++)
5868 // check face type first
5869 type = LittleLong(in->type);
5870 if (type != Q3FACETYPE_FLAT
5871 && type != Q3FACETYPE_PATCH
5872 && type != Q3FACETYPE_MESH
5873 && type != Q3FACETYPE_FLARE)
5875 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5879 n = LittleLong(in->textureindex);
5880 if (n < 0 || n >= loadmodel->num_textures)
5882 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5885 out->texture = loadmodel->data_textures + n;
5886 n = LittleLong(in->effectindex);
5887 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5889 if (developer_extra.integer)
5890 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5896 out->effect = loadmodel->brushq3.data_effects + n;
5898 if (cls.state != ca_dedicated)
5900 out->lightmaptexture = NULL;
5901 out->deluxemaptexture = r_texture_blanknormalmap;
5902 n = LittleLong(in->lightmapindex);
5905 else if (n >= loadmodel->brushq3.num_originallightmaps)
5907 if(loadmodel->brushq3.num_originallightmaps != 0)
5908 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5913 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5914 if (loadmodel->brushq3.deluxemapping)
5915 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5916 loadmodel->lit = true;
5920 firstvertex = LittleLong(in->firstvertex);
5921 numvertices = LittleLong(in->numvertices);
5922 firstelement = LittleLong(in->firstelement);
5923 numtriangles = LittleLong(in->numelements) / 3;
5924 if (numtriangles * 3 != LittleLong(in->numelements))
5926 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));
5929 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5931 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);
5934 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5936 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);
5941 case Q3FACETYPE_FLAT:
5942 case Q3FACETYPE_MESH:
5943 // no processing necessary
5945 case Q3FACETYPE_PATCH:
5946 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5947 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5948 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))
5950 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5953 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5955 // convert patch to Q3FACETYPE_MESH
5956 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5957 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5958 // bound to user settings
5959 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5960 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5961 // bound to sanity settings
5962 xtess = bound(0, xtess, 1024);
5963 ytess = bound(0, ytess, 1024);
5965 // lower quality collision patches! Same procedure as before, but different cvars
5966 // convert patch to Q3FACETYPE_MESH
5967 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5968 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5969 // bound to user settings
5970 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5971 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5972 // bound to sanity settings
5973 cxtess = bound(0, cxtess, 1024);
5974 cytess = bound(0, cytess, 1024);
5976 // store it for the LOD grouping step
5977 patchtess[patchtesscount].info.xsize = patchsize[0];
5978 patchtess[patchtesscount].info.ysize = patchsize[1];
5979 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5980 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5981 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5982 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5984 patchtess[patchtesscount].surface_id = i;
5985 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5986 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5987 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5988 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5989 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5990 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5991 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5994 case Q3FACETYPE_FLARE:
5995 if (developer_extra.integer)
5996 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
6000 out->num_vertices = numvertices;
6001 out->num_triangles = numtriangles;
6002 meshvertices += out->num_vertices;
6003 meshtriangles += out->num_triangles;
6006 // Fix patches tesselations so that they make no seams
6010 for(i = 0; i < patchtesscount; ++i)
6012 for(j = i+1; j < patchtesscount; ++j)
6014 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
6017 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
6024 // Calculate resulting number of triangles
6025 collisionvertices = 0;
6026 collisiontriangles = 0;
6027 for(i = 0; i < patchtesscount; ++i)
6029 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
6030 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
6031 numvertices = finalwidth * finalheight;
6032 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6034 oldout[patchtess[i].surface_id].num_vertices = numvertices;
6035 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
6036 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
6037 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
6039 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
6040 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
6041 numvertices = finalwidth * finalheight;
6042 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6044 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
6045 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
6046 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
6047 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
6053 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true);
6054 if (collisiontriangles)
6056 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6057 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6061 collisionvertices = 0;
6062 collisiontriangles = 0;
6063 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6065 if (out->num_vertices < 3 || out->num_triangles < 1)
6068 type = LittleLong(in->type);
6069 firstvertex = LittleLong(in->firstvertex);
6070 firstelement = LittleLong(in->firstelement);
6071 out->num_firstvertex = meshvertices;
6072 out->num_firsttriangle = meshtriangles;
6073 out->num_firstcollisiontriangle = collisiontriangles;
6076 case Q3FACETYPE_FLAT:
6077 case Q3FACETYPE_MESH:
6078 // no processing necessary, except for lightmap merging
6079 for (j = 0;j < out->num_vertices;j++)
6081 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6082 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6083 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6084 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6085 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6086 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6087 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6088 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6089 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6090 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6091 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6092 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6093 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6094 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6096 for (j = 0;j < out->num_triangles*3;j++)
6097 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6099 case Q3FACETYPE_PATCH:
6100 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6101 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6102 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6103 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6104 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6105 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6106 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6108 xtess = ytess = cxtess = cytess = -1;
6109 for(j = 0; j < patchtesscount; ++j)
6110 if(patchtess[j].surface_id == i)
6112 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6113 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6114 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6115 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6120 Con_Errorf("ERROR: patch %d isn't preprocessed?!?\n", i);
6121 xtess = ytess = cxtess = cytess = 0;
6124 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6125 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6126 finalvertices = finalwidth * finalheight;
6127 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6128 type = Q3FACETYPE_MESH;
6129 // generate geometry
6130 // (note: normals are skipped because they get recalculated)
6131 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6132 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6133 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6134 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6135 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6136 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6138 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);
6140 if (developer_extra.integer)
6142 if (out->num_triangles < finaltriangles)
6143 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);
6145 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);
6147 // q3map does not put in collision brushes for curves... ugh
6148 // build the lower quality collision geometry
6149 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6150 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6151 finalvertices = finalwidth * finalheight;
6152 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6154 // store collision geometry for BIH collision tree
6155 out->num_collisionvertices = finalvertices;
6156 out->num_collisiontriangles = finaltriangles;
6157 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6158 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6159 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6160 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6161 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6162 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6164 if (developer_extra.integer)
6165 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);
6167 collisionvertices += finalvertices;
6168 collisiontriangles += out->num_collisiontriangles;
6173 meshvertices += out->num_vertices;
6174 meshtriangles += out->num_triangles;
6175 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6176 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)
6178 if (invalidelements)
6180 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);
6181 for (j = 0;j < out->num_triangles * 3;j++)
6183 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6184 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 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6189 // calculate a bounding box
6190 VectorClear(out->mins);
6191 VectorClear(out->maxs);
6192 if (out->num_vertices)
6194 if (cls.state != ca_dedicated && out->lightmaptexture)
6196 // figure out which part of the merged lightmap this fits into
6197 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6198 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6199 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6200 lightmapindex &= mergewidth * mergeheight - 1;
6201 lightmaptcscale[0] = 1.0f / mergewidth;
6202 lightmaptcscale[1] = 1.0f / mergeheight;
6203 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6204 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6205 // modify the lightmap texcoords to match this region of the merged lightmap
6206 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6208 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6209 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6212 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6213 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6214 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6216 out->mins[0] = min(out->mins[0], v[0]);
6217 out->maxs[0] = max(out->maxs[0], v[0]);
6218 out->mins[1] = min(out->mins[1], v[1]);
6219 out->maxs[1] = max(out->maxs[1], v[1]);
6220 out->mins[2] = min(out->mins[2], v[2]);
6221 out->maxs[2] = max(out->maxs[2], v[2]);
6223 out->mins[0] -= 1.0f;
6224 out->mins[1] -= 1.0f;
6225 out->mins[2] -= 1.0f;
6226 out->maxs[0] += 1.0f;
6227 out->maxs[1] += 1.0f;
6228 out->maxs[2] += 1.0f;
6230 // set lightmap styles for consistency with q1bsp
6231 //out->lightmapinfo->styles[0] = 0;
6232 //out->lightmapinfo->styles[1] = 255;
6233 //out->lightmapinfo->styles[2] = 255;
6234 //out->lightmapinfo->styles[3] = 255;
6239 for (;i < count;i++, out++)
6241 if(out->num_vertices && out->num_triangles)
6243 if(out->num_vertices == 0)
6245 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6246 if(out->num_triangles == 0)
6247 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6249 else if(out->num_triangles == 0)
6250 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)",
6251 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6252 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6253 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6256 // for per pixel lighting
6257 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);
6259 // generate ushort elements array if possible
6260 if (loadmodel->surfmesh.data_element3s)
6261 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6262 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6264 // free the no longer needed vertex data
6265 loadmodel->brushq3.num_vertices = 0;
6266 if (loadmodel->brushq3.data_vertex3f)
6267 Mem_Free(loadmodel->brushq3.data_vertex3f);
6268 loadmodel->brushq3.data_vertex3f = NULL;
6269 loadmodel->brushq3.data_normal3f = NULL;
6270 loadmodel->brushq3.data_texcoordtexture2f = NULL;
6271 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6272 loadmodel->brushq3.data_color4f = NULL;
6273 // free the no longer needed triangle data
6274 loadmodel->brushq3.num_triangles = 0;
6275 if (loadmodel->brushq3.data_element3i)
6276 Mem_Free(loadmodel->brushq3.data_element3i);
6277 loadmodel->brushq3.data_element3i = NULL;
6280 Mem_Free(patchtess);
6283 static void Mod_Q3BSP_LoadModels(lump_t *l)
6287 int i, j, n, c, count;
6289 in = (q3dmodel_t *)(mod_base + l->fileofs);
6290 if (l->filelen % sizeof(*in))
6291 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6292 count = l->filelen / sizeof(*in);
6293 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6295 loadmodel->brushq3.data_models = out;
6296 loadmodel->brushq3.num_models = count;
6298 for (i = 0;i < count;i++, in++, out++)
6300 for (j = 0;j < 3;j++)
6302 out->mins[j] = LittleFloat(in->mins[j]);
6303 out->maxs[j] = LittleFloat(in->maxs[j]);
6305 n = LittleLong(in->firstface);
6306 c = LittleLong(in->numfaces);
6307 if (n < 0 || n + c > loadmodel->num_surfaces)
6308 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6311 n = LittleLong(in->firstbrush);
6312 c = LittleLong(in->numbrushes);
6313 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6314 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6315 out->firstbrush = n;
6316 out->numbrushes = c;
6320 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6326 in = (int *)(mod_base + l->fileofs);
6327 if (l->filelen % sizeof(*in))
6328 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6329 count = l->filelen / sizeof(*in);
6330 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6332 loadmodel->brush.data_leafbrushes = out;
6333 loadmodel->brush.num_leafbrushes = count;
6335 for (i = 0;i < count;i++, in++, out++)
6337 n = LittleLong(*in);
6338 if (n < 0 || n >= loadmodel->brush.num_brushes)
6339 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6344 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6350 in = (int *)(mod_base + l->fileofs);
6351 if (l->filelen % sizeof(*in))
6352 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6353 count = l->filelen / sizeof(*in);
6354 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6356 loadmodel->brush.data_leafsurfaces = out;
6357 loadmodel->brush.num_leafsurfaces = count;
6359 for (i = 0;i < count;i++, in++, out++)
6361 n = LittleLong(*in);
6362 if (n < 0 || n >= loadmodel->num_surfaces)
6363 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6368 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6372 int i, j, n, c, count;
6374 in = (q3dleaf_t *)(mod_base + l->fileofs);
6375 if (l->filelen % sizeof(*in))
6376 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6377 count = l->filelen / sizeof(*in);
6378 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6380 loadmodel->brush.data_leafs = out;
6381 loadmodel->brush.num_leafs = count;
6383 for (i = 0;i < count;i++, in++, out++)
6387 out->clusterindex = LittleLong(in->clusterindex);
6388 out->areaindex = LittleLong(in->areaindex);
6389 for (j = 0;j < 3;j++)
6391 // yes the mins/maxs are ints
6392 out->mins[j] = LittleLong(in->mins[j]) - 1;
6393 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6395 n = LittleLong(in->firstleafface);
6396 c = LittleLong(in->numleaffaces);
6397 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6398 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6399 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6400 out->numleafsurfaces = c;
6401 n = LittleLong(in->firstleafbrush);
6402 c = LittleLong(in->numleafbrushes);
6403 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6404 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6405 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6406 out->numleafbrushes = c;
6410 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6416 in = (q3dnode_t *)(mod_base + l->fileofs);
6417 if (l->filelen % sizeof(*in))
6418 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6419 count = l->filelen / sizeof(*in);
6421 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6422 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6424 loadmodel->brush.data_nodes = out;
6425 loadmodel->brush.num_nodes = count;
6427 for (i = 0;i < count;i++, in++, out++)
6430 n = LittleLong(in->planeindex);
6431 if (n < 0 || n >= loadmodel->brush.num_planes)
6432 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6433 out->plane = loadmodel->brush.data_planes + n;
6434 for (j = 0;j < 2;j++)
6436 n = LittleLong(in->childrenindex[j]);
6439 if (n >= loadmodel->brush.num_nodes)
6440 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6441 out->children[j] = loadmodel->brush.data_nodes + n;
6446 if (n >= loadmodel->brush.num_leafs)
6447 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6448 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6451 for (j = 0;j < 3;j++)
6453 // yes the mins/maxs are ints
6454 out->mins[j] = LittleLong(in->mins[j]) - 1;
6455 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6459 // set the parent pointers
6460 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6463 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6466 q3dlightgrid_t *out;
6470 unsigned char *texturergba, *texturelayer[3], *texturepadding[2];
6471 double lightgridmatrix[4][4];
6473 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6474 if (l->filelen % sizeof(*in))
6475 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6476 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6477 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6478 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6479 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6480 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6481 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6482 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6483 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6484 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6485 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6486 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6487 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6488 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6489 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]);
6490 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]);
6492 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6495 if (l->filelen < count * (int)sizeof(*in))
6497 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]);
6498 return; // ignore the grid if we cannot understand it
6500 if (l->filelen != count * (int)sizeof(*in))
6501 Con_Warnf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
6502 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6503 loadmodel->brushq3.data_lightgrid = out;
6504 loadmodel->brushq3.num_lightgrid = count;
6505 // no swapping or validation necessary
6506 memcpy(out, in, count * (int)sizeof(*out));
6508 if(mod_q3bsp_sRGBlightmaps.integer)
6510 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6512 // we fix the brightness consistently via lightmapscale
6516 for(i = 0; i < count; ++i)
6518 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6519 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6520 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6521 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6522 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6523 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6529 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6531 for(i = 0; i < count; ++i)
6533 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6534 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6535 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6536 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6537 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6538 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6547 if (mod_q3bsp_lightgrid_texture.integer)
6549 // build a texture to hold the data for per-pixel sampling
6550 // this has 3 different kinds of data stacked in it:
6552 // bent-normal light color
6553 // bent-normal light dir
6555 texturesize[0] = loadmodel->brushq3.num_lightgrid_isize[0];
6556 texturesize[1] = loadmodel->brushq3.num_lightgrid_isize[1];
6557 texturesize[2] = (loadmodel->brushq3.num_lightgrid_isize[2] + 2) * 3;
6558 texturergba = (unsigned char*)Mem_Alloc(loadmodel->mempool, texturesize[0] * texturesize[1] * texturesize[2] * sizeof(char[4]));
6559 texturelayer[0] = texturergba + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6560 texturelayer[1] = texturelayer[0] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6561 texturelayer[2] = texturelayer[1] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6562 // the light dir layer needs padding above/below it that is a neutral unsigned normal (127,127,127,255)
6563 texturepadding[0] = texturelayer[2] - loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6564 texturepadding[1] = texturelayer[2] + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2] * 4;
6565 for (i = 0; i < texturesize[0] * texturesize[1]; i++)
6567 texturepadding[0][i * 4] = texturepadding[1][i * 4] = 127;
6568 texturepadding[0][i * 4 + 1] = texturepadding[1][i * 4 + 1] = 127;
6569 texturepadding[0][i * 4 + 2] = texturepadding[1][i * 4 + 2] = 127;
6570 texturepadding[0][i * 4 + 3] = texturepadding[1][i * 4 + 3] = 255;
6572 for (i = 0; i < count; i++)
6574 texturelayer[0][i * 4 + 0] = out[i].ambientrgb[0];
6575 texturelayer[0][i * 4 + 1] = out[i].ambientrgb[1];
6576 texturelayer[0][i * 4 + 2] = out[i].ambientrgb[2];
6577 texturelayer[0][i * 4 + 3] = 255;
6578 texturelayer[1][i * 4 + 0] = out[i].diffusergb[0];
6579 texturelayer[1][i * 4 + 1] = out[i].diffusergb[1];
6580 texturelayer[1][i * 4 + 2] = out[i].diffusergb[2];
6581 texturelayer[1][i * 4 + 3] = 255;
6582 // this uses the mod_md3_sin table because the values are
6583 // already in the 0-255 range, the 64+ bias fetches a cosine
6584 // instead of a sine value
6585 texturelayer[2][i * 4 + 0] = (char)((mod_md3_sin[64 + out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6586 texturelayer[2][i * 4 + 1] = (char)((mod_md3_sin[out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6587 texturelayer[2][i * 4 + 2] = (char)((mod_md3_sin[64 + out[i].diffusepitch]) * 127 + 127);
6588 texturelayer[2][i * 4 + 3] = 255;
6593 for (z = 0; z < loadmodel->brushq3.num_lightgrid_isize[2]; z++)
6595 for (y = 0; y < loadmodel->brushq3.num_lightgrid_isize[1]; y++)
6597 for (x = 0; x < loadmodel->brushq3.num_lightgrid_isize[0]; x++)
6599 i = (z * texturesize[1] + y) * texturesize[0] + x;
6600 texturelayer[0][i * 4 + 0] = x * 256 / loadmodel->brushq3.num_lightgrid_isize[0];
6601 texturelayer[0][i * 4 + 1] = y * 256 / loadmodel->brushq3.num_lightgrid_isize[1];
6602 texturelayer[0][i * 4 + 2] = z * 256 / loadmodel->brushq3.num_lightgrid_isize[2];
6607 loadmodel->brushq3.lightgridtexturesize[0] = texturesize[0];
6608 loadmodel->brushq3.lightgridtexturesize[1] = texturesize[1];
6609 loadmodel->brushq3.lightgridtexturesize[2] = texturesize[2];
6610 memset(lightgridmatrix[0], 0, sizeof(lightgridmatrix));
6611 lightgridmatrix[0][0] = loadmodel->brushq3.num_lightgrid_scale[0] / texturesize[0];
6612 lightgridmatrix[1][1] = loadmodel->brushq3.num_lightgrid_scale[1] / texturesize[1];
6613 lightgridmatrix[2][2] = loadmodel->brushq3.num_lightgrid_scale[2] / texturesize[2];
6614 lightgridmatrix[0][3] = -(loadmodel->brushq3.num_lightgrid_imins[0] - 0.5f) / texturesize[0];
6615 lightgridmatrix[1][3] = -(loadmodel->brushq3.num_lightgrid_imins[1] - 0.5f) / texturesize[1];
6616 lightgridmatrix[2][3] = -(loadmodel->brushq3.num_lightgrid_imins[2] - 1.5f) / texturesize[2];
6617 lightgridmatrix[3][3] = 1;
6618 Matrix4x4_FromArrayDoubleD3D(&loadmodel->brushq3.lightgridworldtotexturematrix, lightgridmatrix[0]);
6619 loadmodel->brushq3.lightgridtexture = R_LoadTexture3D(loadmodel->texturepool, "lightgrid", texturesize[0], texturesize[1], texturesize[2], texturergba, TEXTYPE_RGBA, TEXF_CLAMP, 0, NULL);
6620 Mem_Free(texturergba);
6625 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6630 if (l->filelen == 0)
6633 // unvised maps often have cluster indices even without pvs, so check
6634 // leafs to find real number of clusters
6635 loadmodel->brush.num_pvsclusters = 1;
6636 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6637 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6640 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6641 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6642 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6643 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6647 in = (q3dpvs_t *)(mod_base + l->fileofs);
6649 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6651 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6652 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6653 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6654 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6655 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6656 if (l->filelen < totalchains + (int)sizeof(*in))
6657 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);
6659 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6660 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6663 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6665 int i, j, k, index[3];
6666 float transformed[3], blend1, blend2, blend, stylescale = 1;
6667 q3dlightgrid_t *a, *s;
6669 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6670 // LadyHavoc: FIXME: is this true?
6671 stylescale = 1; // added while render
6672 //stylescale = r_refdef.scene.rtlightstylevalue[0];
6674 if (!model->brushq3.num_lightgrid)
6676 ambientcolor[0] = stylescale;
6677 ambientcolor[1] = stylescale;
6678 ambientcolor[2] = stylescale;
6682 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6683 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6684 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6685 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6686 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6687 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6688 index[0] = (int)floor(transformed[0]);
6689 index[1] = (int)floor(transformed[1]);
6690 index[2] = (int)floor(transformed[2]);
6691 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6693 // now lerp the values
6694 VectorClear(diffusenormal);
6695 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6696 for (k = 0;k < 2;k++)
6698 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6699 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6701 for (j = 0;j < 2;j++)
6703 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6704 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6706 for (i = 0;i < 2;i++)
6708 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6709 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6711 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6712 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6713 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6714 // this uses the mod_md3_sin table because the values are
6715 // already in the 0-255 range, the 64+ bias fetches a cosine
6716 // instead of a sine value
6717 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6718 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6719 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6720 //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)));
6725 // normalize the light direction before turning
6726 VectorNormalize(diffusenormal);
6727 //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]);
6730 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3], double endpos[3])
6733 double midf, mid[3];
6739 // find the point distances
6740 mplane_t *plane = node->plane;
6741 if (plane->type < 3)
6743 t1 = p1[plane->type] - plane->dist;
6744 t2 = p2[plane->type] - plane->dist;
6748 t1 = DotProduct (plane->normal, p1) - plane->dist;
6749 t2 = DotProduct (plane->normal, p2) - plane->dist;
6756 node = node->children[1];
6765 node = node->children[0];
6771 midf = t1 / (t1 - t2);
6772 VectorLerp(p1, midf, p2, mid);
6774 // recurse both sides, front side first
6775 // return 2 if empty is followed by solid (hit something)
6776 // do not return 2 if both are solid or both empty,
6777 // or if start is solid and end is empty
6778 // as these degenerate cases usually indicate the eye is in solid and
6779 // should see the target point anyway
6780 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid, endpos);
6783 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2, endpos);
6786 VectorCopy(mid, endpos);
6789 return ((mleaf_t *)node)->clusterindex < 0;
6792 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)
6794 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6797 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
6798 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
6802 double tracestart[3], traceend[3], traceendpos[3];
6803 VectorCopy(start, tracestart);
6804 VectorCopy(end, traceend);
6805 VectorCopy(end, traceendpos);
6806 Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend, traceendpos);
6807 return BoxesOverlap(traceendpos, traceendpos, acceptmins, acceptmaxs);
6811 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)
6814 const bih_leaf_t *leaf;
6815 const bih_node_t *node;
6816 const colbrushf_t *brush;
6819 int nodestackpos = 0;
6820 int nodestack[1024];
6822 memset(trace, 0, sizeof(*trace));
6823 trace->fraction = 1;
6824 trace->hitsupercontentsmask = hitsupercontentsmask;
6825 trace->skipsupercontentsmask = skipsupercontentsmask;
6826 trace->skipmaterialflagsmask = skipmaterialflagsmask;
6828 bih = &model->collision_bih;
6832 nodenum = bih->rootnode;
6833 nodestack[nodestackpos++] = nodenum;
6834 while (nodestackpos)
6836 nodenum = nodestack[--nodestackpos];
6837 node = bih->nodes + nodenum;
6839 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6842 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6844 axis = node->type - BIH_SPLITX;
6845 if (start[axis] >= node->frontmin)
6846 nodestack[nodestackpos++] = node->front;
6847 if (start[axis] <= node->backmax)
6848 nodestack[nodestackpos++] = node->back;
6850 else if (node->type == BIH_UNORDERED)
6852 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6854 leaf = bih->leafs + node->children[axis];
6856 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6862 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6863 Collision_TracePointBrushFloat(trace, start, brush);
6865 case BIH_COLLISIONTRIANGLE:
6866 // collision triangle - skipped because they have no volume
6868 case BIH_RENDERTRIANGLE:
6869 // render triangle - skipped because they have no volume
6877 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)
6879 const bih_leaf_t *leaf;
6880 const bih_node_t *node;
6881 const colbrushf_t *brush;
6883 const texture_t *texture;
6884 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6885 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6886 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6891 if (VectorCompare(start, end))
6893 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6897 nodenum = bih->rootnode;
6899 memset(trace, 0, sizeof(*trace));
6900 trace->fraction = 1;
6901 trace->hitsupercontentsmask = hitsupercontentsmask;
6902 trace->skipsupercontentsmask = skipsupercontentsmask;
6903 trace->skipmaterialflagsmask = skipmaterialflagsmask;
6906 nodestackline[nodestackpos][0] = start[0];
6907 nodestackline[nodestackpos][1] = start[1];
6908 nodestackline[nodestackpos][2] = start[2];
6909 nodestackline[nodestackpos][3] = end[0];
6910 nodestackline[nodestackpos][4] = end[1];
6911 nodestackline[nodestackpos][5] = end[2];
6912 nodestack[nodestackpos++] = nodenum;
6913 while (nodestackpos)
6915 nodenum = nodestack[--nodestackpos];
6916 node = bih->nodes + nodenum;
6917 VectorCopy(nodestackline[nodestackpos], nodestart);
6918 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6919 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6920 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6921 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6922 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6923 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6924 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6925 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs) && !collision_bih_fullrecursion.integer)
6927 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6929 // recurse children of the split
6930 axis = node->type - BIH_SPLITX;
6931 d1 = node->backmax - nodestart[axis];
6932 d2 = node->backmax - nodeend[axis];
6933 d3 = nodestart[axis] - node->frontmin;
6934 d4 = nodeend[axis] - node->frontmin;
6935 if (collision_bih_fullrecursion.integer)
6936 d1 = d2 = d3 = d4 = 1; // force full recursion
6937 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6939 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;
6940 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;
6941 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;
6942 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6943 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;
6944 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;
6945 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;
6946 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6947 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;
6948 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;
6949 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;
6950 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6951 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6952 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6953 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6954 case 15: /* <<<< */ break;
6957 else if (node->type == BIH_UNORDERED)
6959 // calculate sweep bounds for this node
6960 // copy node bounds into local variables
6961 VectorCopy(node->mins, nodebigmins);
6962 VectorCopy(node->maxs, nodebigmaxs);
6963 // clip line to this node bounds
6964 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); }
6965 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); }
6966 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); }
6967 // some of the line intersected the enlarged node box
6968 // calculate sweep bounds for this node
6969 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6970 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6971 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6972 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6973 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6974 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6975 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6977 leaf = bih->leafs + node->children[axis];
6978 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6983 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6984 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6986 case BIH_COLLISIONTRIANGLE:
6987 if (!mod_q3bsp_curves_collisions.integer)
6989 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6990 texture = model->data_textures + leaf->textureindex;
6991 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);
6993 case BIH_RENDERTRIANGLE:
6994 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6995 texture = model->data_textures + leaf->textureindex;
6996 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);
7004 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)
7006 if (VectorCompare(start, end))
7008 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7011 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->collision_bih);
7014 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)
7017 const bih_leaf_t *leaf;
7018 const bih_node_t *node;
7019 const colbrushf_t *brush;
7021 const texture_t *texture;
7022 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
7023 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
7024 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
7025 int axis, nodenum, nodestackpos = 0, nodestack[1024];
7027 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
7029 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
7030 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7032 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7036 bih = &model->collision_bih;
7039 nodenum = bih->rootnode;
7041 // box trace, performed as brush trace
7042 memset(trace, 0, sizeof(*trace));
7043 trace->fraction = 1;
7044 trace->hitsupercontentsmask = hitsupercontentsmask;
7045 trace->skipsupercontentsmask = skipsupercontentsmask;
7046 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7048 // calculate tracebox-like parameters for efficient culling
7049 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
7050 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
7051 VectorSubtract(thisbrush_start->mins, start, startmins);
7052 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
7053 VectorSubtract(thisbrush_end->mins, end, endmins);
7054 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7055 mins[0] = min(startmins[0], endmins[0]);
7056 mins[1] = min(startmins[1], endmins[1]);
7057 mins[2] = min(startmins[2], endmins[2]);
7058 maxs[0] = max(startmaxs[0], endmaxs[0]);
7059 maxs[1] = max(startmaxs[1], endmaxs[1]);
7060 maxs[2] = max(startmaxs[2], endmaxs[2]);
7063 nodestackline[nodestackpos][0] = start[0];
7064 nodestackline[nodestackpos][1] = start[1];
7065 nodestackline[nodestackpos][2] = start[2];
7066 nodestackline[nodestackpos][3] = end[0];
7067 nodestackline[nodestackpos][4] = end[1];
7068 nodestackline[nodestackpos][5] = end[2];
7069 nodestack[nodestackpos++] = nodenum;
7070 while (nodestackpos)
7072 nodenum = nodestack[--nodestackpos];
7073 node = bih->nodes + nodenum;
7074 VectorCopy(nodestackline[nodestackpos], nodestart);
7075 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7076 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7077 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7078 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7079 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7080 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7081 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7082 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7084 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7086 // recurse children of the split
7087 axis = node->type - BIH_SPLITX;
7088 d1 = node->backmax - nodestart[axis] - mins[axis];
7089 d2 = node->backmax - nodeend[axis] - mins[axis];
7090 d3 = nodestart[axis] - node->frontmin + maxs[axis];
7091 d4 = nodeend[axis] - node->frontmin + maxs[axis];
7092 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7094 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;
7095 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;
7096 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;
7097 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7098 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;
7099 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;
7100 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;
7101 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7102 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;
7103 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;
7104 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;
7105 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7106 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7107 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7108 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7109 case 15: /* <<<< */ break;
7112 else if (node->type == BIH_UNORDERED)
7114 // calculate sweep bounds for this node
7115 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7116 VectorSubtract(node->mins, maxs, nodebigmins);
7117 VectorSubtract(node->maxs, mins, nodebigmaxs);
7118 // clip line to this node bounds
7119 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); }
7120 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); }
7121 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); }
7122 // some of the line intersected the enlarged node box
7123 // calculate sweep bounds for this node
7124 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7125 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7126 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7127 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7128 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7129 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7130 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7132 leaf = bih->leafs + node->children[axis];
7133 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7138 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7139 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7141 case BIH_COLLISIONTRIANGLE:
7142 if (!mod_q3bsp_curves_collisions.integer)
7144 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7145 texture = model->data_textures + leaf->textureindex;
7146 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);
7148 case BIH_RENDERTRIANGLE:
7149 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7150 texture = model->data_textures + leaf->textureindex;
7151 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);
7159 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)
7161 colboxbrushf_t thisbrush_start, thisbrush_end;
7162 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7164 // box trace, performed as brush trace
7165 VectorAdd(start, boxmins, boxstartmins);
7166 VectorAdd(start, boxmaxs, boxstartmaxs);
7167 VectorAdd(end, boxmins, boxendmins);
7168 VectorAdd(end, boxmaxs, boxendmaxs);
7169 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7170 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7171 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7175 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7178 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0, 0);
7179 return trace.startsupercontents;
7182 qboolean Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
7185 Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
7186 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
7189 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)
7192 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7194 int hitsupercontents;
7195 VectorSet(end, start[0], start[1], model->normalmins[2]);
7197 memset(trace, 0, sizeof(*trace));
7198 trace->fraction = 1;
7199 trace->hitsupercontentsmask = hitsupercontentsmask;
7200 trace->skipsupercontentsmask = skipsupercontentsmask;
7201 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7203 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7204 hitsupercontents = trace->hitsupercontents;
7205 memset(trace, 0, sizeof(*trace));
7206 trace->fraction = 1;
7207 trace->hitsupercontentsmask = hitsupercontentsmask;
7208 trace->skipsupercontentsmask = skipsupercontentsmask;
7209 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7210 trace->startsupercontents = hitsupercontents;
7214 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7217 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7220 VectorSet(end, start[0], start[1], model->normalmins[2]);
7221 memset(&trace, 0, sizeof(trace));
7223 trace.hitsupercontentsmask = hitsupercontentsmask;
7224 trace.skipsupercontentsmask = skipsupercontentsmask;
7225 trace.skipmaterialflagsmask = skipmaterialflagsmask;
7226 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7227 return trace.hitsupercontents;
7233 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)
7235 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->render_bih);
7239 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
7247 int nummodelbrushes = model->nummodelbrushes;
7248 int nummodelsurfaces = model->nummodelsurfaces;
7250 const int *collisionelement3i;
7251 const float *collisionvertex3f;
7252 const int *renderelement3i;
7253 const float *rendervertex3f;
7254 bih_leaf_t *bihleafs;
7255 bih_node_t *bihnodes;
7257 int *temp_leafsortscratch;
7258 const msurface_t *surface;
7259 const q3mbrush_t *brush;
7261 // find out how many BIH leaf nodes we need
7263 if (userendersurfaces)
7265 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7266 bihnumleafs += surface->num_triangles;
7270 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7271 if (brush->colbrushf)
7273 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7275 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7276 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7278 bihnumleafs += surface->num_collisiontriangles;
7285 // allocate the memory for the BIH leaf nodes
7286 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7288 // now populate the BIH leaf nodes
7291 // add render surfaces
7292 renderelement3i = model->surfmesh.data_element3i;
7293 rendervertex3f = model->surfmesh.data_vertex3f;
7294 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7296 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7298 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7300 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7301 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7302 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7303 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7304 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7305 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7306 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7307 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7308 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7309 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7314 if (!userendersurfaces)
7316 // add collision brushes
7317 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7319 if (!brush->colbrushf)
7321 bihleafs[bihleafindex].type = BIH_BRUSH;
7322 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7323 bihleafs[bihleafindex].surfaceindex = -1;
7324 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7325 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7326 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7330 // add collision surfaces
7331 collisionelement3i = model->brush.data_collisionelement3i;
7332 collisionvertex3f = model->brush.data_collisionvertex3f;
7333 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7335 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7337 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7338 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7339 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7340 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7341 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7342 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7343 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7344 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7345 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7346 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7352 // allocate buffers for the produced and temporary data
7353 bihmaxnodes = bihnumleafs + 1;
7354 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7355 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7356 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7359 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7361 // we're done with the temporary data
7362 Mem_Free(temp_leafsort);
7364 // resize the BIH nodes array if it over-allocated
7365 if (out->maxnodes > out->numnodes)
7367 out->maxnodes = out->numnodes;
7368 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7374 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents)
7376 int supercontents = 0;
7377 if (nativecontents & CONTENTSQ3_SOLID)
7378 supercontents |= SUPERCONTENTS_SOLID;
7379 if (nativecontents & CONTENTSQ3_WATER)
7380 supercontents |= SUPERCONTENTS_WATER;
7381 if (nativecontents & CONTENTSQ3_SLIME)
7382 supercontents |= SUPERCONTENTS_SLIME;
7383 if (nativecontents & CONTENTSQ3_LAVA)
7384 supercontents |= SUPERCONTENTS_LAVA;
7385 if (nativecontents & CONTENTSQ3_BODY)
7386 supercontents |= SUPERCONTENTS_BODY;
7387 if (nativecontents & CONTENTSQ3_CORPSE)
7388 supercontents |= SUPERCONTENTS_CORPSE;
7389 if (nativecontents & CONTENTSQ3_NODROP)
7390 supercontents |= SUPERCONTENTS_NODROP;
7391 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7392 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7393 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7394 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7395 if (nativecontents & CONTENTSQ3_DONOTENTER)
7396 supercontents |= SUPERCONTENTS_DONOTENTER;
7397 if (nativecontents & CONTENTSQ3_BOTCLIP)
7398 supercontents |= SUPERCONTENTS_BOTCLIP;
7399 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7400 supercontents |= SUPERCONTENTS_OPAQUE;
7401 return supercontents;
7404 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents)
7406 int nativecontents = 0;
7407 if (supercontents & SUPERCONTENTS_SOLID)
7408 nativecontents |= CONTENTSQ3_SOLID;
7409 if (supercontents & SUPERCONTENTS_WATER)
7410 nativecontents |= CONTENTSQ3_WATER;
7411 if (supercontents & SUPERCONTENTS_SLIME)
7412 nativecontents |= CONTENTSQ3_SLIME;
7413 if (supercontents & SUPERCONTENTS_LAVA)
7414 nativecontents |= CONTENTSQ3_LAVA;
7415 if (supercontents & SUPERCONTENTS_BODY)
7416 nativecontents |= CONTENTSQ3_BODY;
7417 if (supercontents & SUPERCONTENTS_CORPSE)
7418 nativecontents |= CONTENTSQ3_CORPSE;
7419 if (supercontents & SUPERCONTENTS_NODROP)
7420 nativecontents |= CONTENTSQ3_NODROP;
7421 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7422 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7423 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7424 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7425 if (supercontents & SUPERCONTENTS_DONOTENTER)
7426 nativecontents |= CONTENTSQ3_DONOTENTER;
7427 if (supercontents & SUPERCONTENTS_BOTCLIP)
7428 nativecontents |= CONTENTSQ3_BOTCLIP;
7429 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7430 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7431 return nativecontents;
7434 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7439 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7440 node = node->children[1];
7442 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7443 if (loadmodel->brush.num_leafs < numleafs)
7444 loadmodel->brush.num_leafs = numleafs;
7447 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7450 q3dheader_t *header;
7451 float corner[3], yawradius, modelradius;
7453 mod->modeldatatypestring = "Q3BSP";
7455 mod->type = mod_brushq3;
7456 mod->brush.ishlbsp = false;
7457 mod->brush.isbsp2rmqe = false;
7458 mod->brush.isbsp2 = false;
7459 mod->brush.isq2bsp = false;
7460 mod->brush.isq3bsp = true;
7461 mod->brush.skymasking = true;
7462 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7465 header = (q3dheader_t *)buffer;
7466 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7467 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7469 i = LittleLong(header->version);
7470 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7471 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7473 mod->soundfromcenter = true;
7474 mod->TraceBox = Mod_CollisionBIH_TraceBox;
7475 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
7476 mod->TraceLine = Mod_CollisionBIH_TraceLine;
7477 mod->TracePoint = Mod_CollisionBIH_TracePoint;
7478 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
7479 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7480 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7481 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7482 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7483 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7484 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7485 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7486 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7487 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7488 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7489 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7490 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7491 mod->brush.AmbientSoundLevelsForPoint = NULL;
7492 mod->brush.RoundUpToHullSize = NULL;
7493 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7494 mod->Draw = R_Q1BSP_Draw;
7495 mod->DrawDepth = R_Q1BSP_DrawDepth;
7496 mod->DrawDebug = R_Q1BSP_DrawDebug;
7497 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7498 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7499 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7500 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7501 mod->DrawLight = R_Q1BSP_DrawLight;
7503 mod_base = (unsigned char *)header;
7505 // swap all the lumps
7506 header->ident = LittleLong(header->ident);
7507 header->version = LittleLong(header->version);
7508 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7509 for (i = 0;i < lumps;i++)
7511 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7512 if((char *) bufferend < (char *) buffer + j)
7513 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7514 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7515 if((char *) bufferend < (char *) buffer + j)
7516 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7519 * NO, do NOT clear them!
7520 * they contain actual data referenced by other stuff.
7521 * Instead, before using the advertisements lump, check header->versio
7523 * Sorry, but otherwise it breaks memory of the first lump.
7524 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7526 header->lumps[i].fileofs = 0;
7527 header->lumps[i].filelen = 0;
7531 mod->brush.qw_md4sum = 0;
7532 mod->brush.qw_md4sum2 = 0;
7533 for (i = 0;i < lumps;i++)
7535 if (i == Q3LUMP_ENTITIES)
7537 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7538 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7540 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7542 // all this checksumming can take a while, so let's send keepalives here too
7543 CL_KeepaliveMessage(false);
7546 // allocate a texture pool if we need it
7547 if (mod->texturepool == NULL)
7548 mod->texturepool = R_AllocTexturePool();
7550 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7551 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7552 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7553 if (header->version == Q3BSPVERSION_IG)
7554 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7556 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7557 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7558 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7559 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7560 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7561 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7562 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7563 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7564 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7565 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7566 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7567 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7568 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7569 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7570 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7572 // the MakePortals code works fine on the q3bsp data as well
7573 if (mod_bsp_portalize.integer)
7574 Mod_Q1BSP_MakePortals();
7576 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7577 loadmodel->brush.supportwateralpha = true;
7579 loadmodel->brush.num_leafs = 0;
7580 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7582 if (loadmodel->brush.numsubmodels)
7583 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7586 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7591 // duplicate the basic information
7592 dpsnprintf(name, sizeof(name), "*%i", i);
7593 mod = Mod_FindName(name, loadmodel->name);
7594 // copy the base model to this one
7596 // rename the clone back to its proper name
7597 strlcpy(mod->name, name, sizeof(mod->name));
7598 mod->brush.parentmodel = loadmodel;
7599 // textures and memory belong to the main model
7600 mod->texturepool = NULL;
7601 mod->mempool = NULL;
7602 mod->brush.GetPVS = NULL;
7603 mod->brush.FatPVS = NULL;
7604 mod->brush.BoxTouchingPVS = NULL;
7605 mod->brush.BoxTouchingLeafPVS = NULL;
7606 mod->brush.BoxTouchingVisibleLeafs = NULL;
7607 mod->brush.FindBoxClusters = NULL;
7608 mod->brush.LightPoint = NULL;
7609 mod->brush.AmbientSoundLevelsForPoint = NULL;
7611 mod->brush.submodel = i;
7612 if (loadmodel->brush.submodels)
7613 loadmodel->brush.submodels[i] = mod;
7615 // make the model surface list (used by shadowing/lighting)
7616 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7617 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7618 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7619 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7620 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7621 Mod_MakeSortedSurfaces(mod);
7623 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7624 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7625 // enlarge the bounding box to enclose all geometry of this model,
7626 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7627 // which can in turn mess up the farclip (as well as culling when
7628 // outside the level - an unimportant concern)
7630 //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]);
7631 for (j = 0;j < mod->nummodelsurfaces;j++)
7633 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7634 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7636 if (!surface->num_vertices)
7638 for (k = 0;k < surface->num_vertices;k++, v += 3)
7640 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7641 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7642 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7643 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7644 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7645 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7648 //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]);
7649 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7650 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7651 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7652 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7653 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7654 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7655 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7656 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7657 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7658 mod->yawmins[2] = mod->normalmins[2];
7659 mod->yawmaxs[2] = mod->normalmaxs[2];
7660 mod->radius = modelradius;
7661 mod->radius2 = modelradius * modelradius;
7663 // this gets altered below if sky or water is used
7664 mod->DrawSky = NULL;
7665 mod->DrawAddWaterPlanes = NULL;
7667 for (j = 0;j < mod->nummodelsurfaces;j++)
7668 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7670 if (j < mod->nummodelsurfaces)
7671 mod->DrawSky = R_Q1BSP_DrawSky;
7673 for (j = 0;j < mod->nummodelsurfaces;j++)
7674 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7676 if (j < mod->nummodelsurfaces)
7677 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7679 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7680 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7682 // generate VBOs and other shared data before cloning submodels
7687 if (mod_q3bsp_sRGBlightmaps.integer)
7689 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7691 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7692 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7693 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7694 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7695 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7697 else // if this is NOT set, regular rendering looks right by this requirement anyway
7700 // we want color 1 to do the same as without sRGB
7701 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7702 loadmodel->lightmapscale *= 2.476923f; // fixes max level
7705 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7706 // we need to undo that
7707 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7711 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);
7714 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7716 int i = LittleLong(((int *)buffer)[1]);
7717 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7718 Mod_Q3BSP_Load(mod,buffer, bufferend);
7719 else if (i == Q2BSPVERSION)
7720 Mod_Q2BSP_Load(mod,buffer, bufferend);
7722 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7725 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7727 Host_Error("Mod_MAP_Load: not yet implemented");
7730 typedef struct objvertex_s
7741 static unsigned char nobsp_pvs[1] = {1};
7743 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7745 const char *textbase = (char *)buffer, *text = textbase;
7749 char materialname[MAX_QPATH];
7750 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7751 int index1, index2, index3;
7752 objvertex_t vfirst, vprev, vcurrent;
7755 int numtriangles = 0;
7756 int maxtriangles = 0;
7757 objvertex_t *vertices = NULL;
7759 int maxtextures = 0, numtextures = 0, textureindex = 0;
7760 int maxv = 0, numv = 1;
7761 int maxvt = 0, numvt = 1;
7762 int maxvn = 0, numvn = 1;
7763 char *texturenames = NULL;
7764 float dist, modelradius, modelyawradius, yawradius;
7765 float *obj_v = NULL;
7766 float *obj_vt = NULL;
7767 float *obj_vn = NULL;
7771 objvertex_t *thisvertex = NULL;
7772 int vertexhashindex;
7773 int *vertexhashtable = NULL;
7774 objvertex_t *vertexhashdata = NULL;
7775 objvertex_t *vdata = NULL;
7776 int vertexhashsize = 0;
7777 int vertexhashcount = 0;
7778 skinfile_t *skinfiles = NULL;
7779 unsigned char *data = NULL;
7780 int *submodelfirstsurface;
7781 msurface_t *tempsurface;
7782 msurface_t *tempsurfaces;
7784 memset(&vfirst, 0, sizeof(vfirst));
7785 memset(&vprev, 0, sizeof(vprev));
7786 memset(&vcurrent, 0, sizeof(vcurrent));
7788 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7790 loadmodel->modeldatatypestring = "OBJ";
7792 loadmodel->type = mod_obj;
7793 loadmodel->soundfromcenter = true;
7794 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7795 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7796 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7797 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7798 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7799 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7800 loadmodel->brush.TraceLineOfSight = NULL;
7801 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7802 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7803 loadmodel->brush.GetPVS = NULL;
7804 loadmodel->brush.FatPVS = NULL;
7805 loadmodel->brush.BoxTouchingPVS = NULL;
7806 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7807 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7808 loadmodel->brush.FindBoxClusters = NULL;
7809 loadmodel->brush.LightPoint = NULL;
7810 loadmodel->brush.FindNonSolidLocation = NULL;
7811 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7812 loadmodel->brush.RoundUpToHullSize = NULL;
7813 loadmodel->brush.PointInLeaf = NULL;
7814 loadmodel->Draw = R_Q1BSP_Draw;
7815 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7816 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7817 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7818 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7819 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7820 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7821 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7823 skinfiles = Mod_LoadSkinFiles();
7824 if (loadmodel->numskins < 1)
7825 loadmodel->numskins = 1;
7827 // make skinscenes for the skins (no groups)
7828 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7829 for (i = 0;i < loadmodel->numskins;i++)
7831 loadmodel->skinscenes[i].firstframe = i;
7832 loadmodel->skinscenes[i].framecount = 1;
7833 loadmodel->skinscenes[i].loop = true;
7834 loadmodel->skinscenes[i].framerate = 10;
7840 // we always have model 0, i.e. the first "submodel"
7841 loadmodel->brush.numsubmodels = 1;
7843 // parse the OBJ text now
7846 static char emptyarg[1] = "";
7851 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7852 line[linelen] = text[linelen];
7854 for (argc = 0;argc < 4;argc++)
7855 argv[argc] = emptyarg;
7858 while (*s == ' ' || *s == '\t')
7868 while (*s == ' ' || *s == '\t')
7878 if (argv[0][0] == '#')
7880 if (!strcmp(argv[0], "v"))
7884 maxv = max(maxv * 2, 1024);
7885 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
7887 if(mod_obj_orientation.integer)
7889 obj_v[numv*3+0] = atof(argv[1]);
7890 obj_v[numv*3+2] = atof(argv[2]);
7891 obj_v[numv*3+1] = atof(argv[3]);
7895 obj_v[numv*3+0] = atof(argv[1]);
7896 obj_v[numv*3+1] = atof(argv[2]);
7897 obj_v[numv*3+2] = atof(argv[3]);
7901 else if (!strcmp(argv[0], "vt"))
7905 maxvt = max(maxvt * 2, 1024);
7906 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
7908 obj_vt[numvt*2+0] = atof(argv[1]);
7909 obj_vt[numvt*2+1] = 1-atof(argv[2]);
7912 else if (!strcmp(argv[0], "vn"))
7916 maxvn = max(maxvn * 2, 1024);
7917 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
7919 if(mod_obj_orientation.integer)
7921 obj_vn[numvn*3+0] = atof(argv[1]);
7922 obj_vn[numvn*3+2] = atof(argv[2]);
7923 obj_vn[numvn*3+1] = atof(argv[3]);
7927 obj_vn[numvn*3+0] = atof(argv[1]);
7928 obj_vn[numvn*3+1] = atof(argv[2]);
7929 obj_vn[numvn*3+2] = atof(argv[3]);
7933 else if (!strcmp(argv[0], "f"))
7937 if (maxtextures <= numtextures)
7939 maxtextures = max(maxtextures * 2, 256);
7940 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7942 textureindex = numtextures++;
7943 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7945 for (j = 1;j < argc;j++)
7947 index1 = atoi(argv[j]);
7948 while(argv[j][0] && argv[j][0] != '/')
7952 index2 = atoi(argv[j]);
7953 while(argv[j][0] && argv[j][0] != '/')
7957 index3 = atoi(argv[j]);
7958 // negative refers to a recent vertex
7959 // zero means not specified
7960 // positive means an absolute vertex index
7962 index1 = numv - index1;
7964 index2 = numvt - index2;
7966 index3 = numvn - index3;
7967 vcurrent.nextindex = -1;
7968 vcurrent.textureindex = textureindex;
7969 vcurrent.submodelindex = submodelindex;
7970 if (obj_v && index1 >= 0 && index1 < numv)
7971 VectorCopy(obj_v + 3*index1, vcurrent.v);
7972 if (obj_vt && index2 >= 0 && index2 < numvt)
7973 Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
7974 if (obj_vn && index3 >= 0 && index3 < numvn)
7975 VectorCopy(obj_vn + 3*index3, vcurrent.vn);
7976 if (numtriangles == 0)
7978 VectorCopy(vcurrent.v, mins);
7979 VectorCopy(vcurrent.v, maxs);
7983 mins[0] = min(mins[0], vcurrent.v[0]);
7984 mins[1] = min(mins[1], vcurrent.v[1]);
7985 mins[2] = min(mins[2], vcurrent.v[2]);
7986 maxs[0] = max(maxs[0], vcurrent.v[0]);
7987 maxs[1] = max(maxs[1], vcurrent.v[1]);
7988 maxs[2] = max(maxs[2], vcurrent.v[2]);
7994 if (maxtriangles <= numtriangles)
7996 maxtriangles = max(maxtriangles * 2, 32768);
7997 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7999 if(mod_obj_orientation.integer)
8001 vertices[numtriangles*3+0] = vfirst;
8002 vertices[numtriangles*3+1] = vprev;
8003 vertices[numtriangles*3+2] = vcurrent;
8007 vertices[numtriangles*3+0] = vfirst;
8008 vertices[numtriangles*3+2] = vprev;
8009 vertices[numtriangles*3+1] = vcurrent;
8016 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8018 submodelindex = atof(argv[1]);
8019 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8021 else if (!strcmp(argv[0], "usemtl"))
8023 for (i = 0;i < numtextures;i++)
8024 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8026 if (i < numtextures)
8030 if (maxtextures <= numtextures)
8032 maxtextures = max(maxtextures * 2, 256);
8033 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8035 textureindex = numtextures++;
8036 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8041 // now that we have the OBJ data loaded as-is, we can convert it
8043 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8044 VectorCopy(mins, loadmodel->normalmins);
8045 VectorCopy(maxs, loadmodel->normalmaxs);
8046 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8047 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8048 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8049 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8050 modelradius = modelyawradius + modelradius * modelradius;
8051 modelyawradius = sqrt(modelyawradius);
8052 modelradius = sqrt(modelradius);
8053 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8054 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8055 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8056 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8057 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8058 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8059 loadmodel->radius = modelradius;
8060 loadmodel->radius2 = modelradius * modelradius;
8062 // allocate storage for triangles
8063 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8064 // allocate vertex hash structures to build an optimal vertex subset
8065 vertexhashsize = numtriangles*2;
8066 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8067 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8068 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8069 vertexhashcount = 0;
8071 // gather surface stats for assigning vertex/triangle ranges
8075 loadmodel->num_surfaces = 0;
8076 // allocate storage for the worst case number of surfaces, later we resize
8077 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8078 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8079 tempsurface = tempsurfaces;
8080 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8082 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8083 for (textureindex = 0;textureindex < numtextures;textureindex++)
8085 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8087 thisvertex = vertices + vertexindex;
8088 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8091 // skip the surface creation if there are no triangles for it
8092 if (vertexindex == numtriangles*3)
8094 // create a surface for these vertices
8095 surfacevertices = 0;
8096 surfaceelements = 0;
8097 // we hack in a texture index in the surface to be fixed up later...
8098 tempsurface->texture = (texture_t *)((size_t)textureindex);
8099 // calculate bounds as we go
8100 VectorCopy(thisvertex->v, tempsurface->mins);
8101 VectorCopy(thisvertex->v, tempsurface->maxs);
8102 for (;vertexindex < numtriangles*3;vertexindex++)
8104 thisvertex = vertices + vertexindex;
8105 if (thisvertex->submodelindex != submodelindex)
8107 if (thisvertex->textureindex != textureindex)
8109 // add vertex to surface bounds
8110 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8111 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8112 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8113 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8114 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8115 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8116 // add the vertex if it is not found in the merged set, and
8117 // get its index (triangle element) for the surface
8118 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8119 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8121 vdata = vertexhashdata + i;
8122 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8127 i = vertexhashcount++;
8128 vdata = vertexhashdata + i;
8129 *vdata = *thisvertex;
8130 vdata->nextindex = vertexhashtable[vertexhashindex];
8131 vertexhashtable[vertexhashindex] = i;
8134 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8137 surfacetriangles = surfaceelements / 3;
8138 tempsurface->num_vertices = surfacevertices;
8139 tempsurface->num_triangles = surfacetriangles;
8140 tempsurface->num_firstvertex = firstvertex;
8141 tempsurface->num_firsttriangle = firsttriangle;
8142 firstvertex += tempsurface->num_vertices;
8143 firsttriangle += tempsurface->num_triangles;
8145 loadmodel->num_surfaces++;
8148 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8149 numvertices = firstvertex;
8150 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8151 tempsurfaces = NULL;
8153 // allocate storage for final mesh data
8154 loadmodel->num_textures = numtextures * loadmodel->numskins;
8155 loadmodel->num_texturesperskin = numtextures;
8156 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 *));
8157 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
8158 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8159 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8160 loadmodel->surfmesh.num_vertices = numvertices;
8161 loadmodel->surfmesh.num_triangles = numtriangles;
8162 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8163 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8164 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8165 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8166 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8168 if (loadmodel->surfmesh.num_vertices <= 65536) {
8169 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8172 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8174 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8175 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8176 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8179 // load the textures
8180 for (textureindex = 0;textureindex < numtextures;textureindex++)
8181 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8182 Mod_FreeSkinFiles(skinfiles);
8184 // set the surface textures to their real values now that we loaded them...
8185 for (i = 0;i < loadmodel->num_surfaces;i++)
8186 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8190 Mem_Free(texturenames);
8194 Mem_Free(vertexhashtable);
8195 Mem_Free(vertexhashdata);
8197 // compute all the mesh information that was not loaded from the file
8198 if (loadmodel->surfmesh.data_element3s)
8199 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8200 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8201 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8202 // generate normals if the file did not have them
8203 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8204 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);
8205 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);
8207 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8208 loadmodel->brush.num_visleafs = 1;
8209 loadmodel->brush.num_leafs = 1;
8210 loadmodel->brush.num_nodes = 0;
8211 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8212 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8213 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8214 loadmodel->brush.num_pvsclusters = 1;
8215 loadmodel->brush.num_pvsclusterbytes = 1;
8216 loadmodel->brush.data_pvsclusters = nobsp_pvs;
8217 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8218 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8219 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
8220 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8221 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8222 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8223 loadmodel->brush.data_leafs->clusterindex = 0;
8224 loadmodel->brush.data_leafs->areaindex = 0;
8225 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8226 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8227 loadmodel->brush.data_leafs->numleafbrushes = 0;
8228 loadmodel->brush.data_leafs->firstleafbrush = NULL;
8229 loadmodel->brush.supportwateralpha = true;
8231 if (loadmodel->brush.numsubmodels)
8232 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8235 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8240 // duplicate the basic information
8241 dpsnprintf(name, sizeof(name), "*%i", i);
8242 mod = Mod_FindName(name, loadmodel->name);
8243 // copy the base model to this one
8245 // rename the clone back to its proper name
8246 strlcpy(mod->name, name, sizeof(mod->name));
8247 mod->brush.parentmodel = loadmodel;
8248 // textures and memory belong to the main model
8249 mod->texturepool = NULL;
8250 mod->mempool = NULL;
8251 mod->brush.GetPVS = NULL;
8252 mod->brush.FatPVS = NULL;
8253 mod->brush.BoxTouchingPVS = NULL;
8254 mod->brush.BoxTouchingLeafPVS = NULL;
8255 mod->brush.BoxTouchingVisibleLeafs = NULL;
8256 mod->brush.FindBoxClusters = NULL;
8257 mod->brush.LightPoint = NULL;
8258 mod->brush.AmbientSoundLevelsForPoint = NULL;
8260 mod->brush.submodel = i;
8261 if (loadmodel->brush.submodels)
8262 loadmodel->brush.submodels[i] = mod;
8264 // make the model surface list (used by shadowing/lighting)
8265 mod->firstmodelsurface = submodelfirstsurface[i];
8266 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8267 mod->firstmodelbrush = 0;
8268 mod->nummodelbrushes = 0;
8269 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8270 Mod_MakeSortedSurfaces(mod);
8272 VectorClear(mod->normalmins);
8273 VectorClear(mod->normalmaxs);
8275 for (j = 0;j < mod->nummodelsurfaces;j++)
8277 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8278 const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8280 if (!surface->num_vertices)
8285 VectorCopy(v3f, mod->normalmins);
8286 VectorCopy(v3f, mod->normalmaxs);
8288 for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8290 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8291 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8292 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8293 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8294 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8295 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8298 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8299 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8300 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8301 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8302 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8303 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8304 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8305 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8306 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8307 mod->yawmins[2] = mod->normalmins[2];
8308 mod->yawmaxs[2] = mod->normalmaxs[2];
8309 mod->radius = modelradius;
8310 mod->radius2 = modelradius * modelradius;
8312 // this gets altered below if sky or water is used
8313 mod->DrawSky = NULL;
8314 mod->DrawAddWaterPlanes = NULL;
8316 for (j = 0;j < mod->nummodelsurfaces;j++)
8317 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8319 if (j < mod->nummodelsurfaces)
8320 mod->DrawSky = R_Q1BSP_DrawSky;
8322 for (j = 0;j < mod->nummodelsurfaces;j++)
8323 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8325 if (j < mod->nummodelsurfaces)
8326 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8328 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8329 mod->render_bih = mod->collision_bih;
8331 // generate VBOs and other shared data before cloning submodels
8336 Mem_Free(submodelfirstsurface);
8338 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);