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_collision_bih = {CVAR_CLIENT | CVAR_SERVER, "mod_collision_bih", "1", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
69 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"};
71 static texture_t mod_q1bsp_texture_solid;
72 static texture_t mod_q1bsp_texture_sky;
73 static texture_t mod_q1bsp_texture_lava;
74 static texture_t mod_q1bsp_texture_slime;
75 static texture_t mod_q1bsp_texture_water;
77 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);
79 void Mod_BrushInit(void)
81 // Cvar_RegisterVariable(&r_subdivide_size);
82 Cvar_RegisterVariable(&mod_bsp_portalize);
83 Cvar_RegisterVariable(&r_novis);
84 Cvar_RegisterVariable(&r_nosurftextures);
85 Cvar_RegisterVariable(&r_subdivisions_tolerance);
86 Cvar_RegisterVariable(&r_subdivisions_mintess);
87 Cvar_RegisterVariable(&r_subdivisions_maxtess);
88 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
89 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
90 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
91 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
92 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
93 Cvar_RegisterVariable(&r_trippy);
94 Cvar_RegisterVariable(&r_fxaa);
95 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
96 Cvar_RegisterVariable(&mod_obj_orientation);
97 Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
98 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
99 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
100 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
101 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
102 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
103 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
104 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
105 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
106 Cvar_RegisterVariable(&mod_q3bsp_lightgrid_texture);
107 Cvar_RegisterVariable(&mod_q3bsp_lightgrid_world_surfaces);
108 Cvar_RegisterVariable(&mod_q3bsp_lightgrid_bsp_surfaces);
109 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
110 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
111 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
112 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
113 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
114 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
115 Cvar_RegisterVariable(&mod_q3shader_default_refractive_index);
116 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
117 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
118 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
119 Cvar_RegisterVariable(&mod_collision_bih);
120 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
122 // these games were made for older DP engines and are no longer
123 // maintained; use this hack to show their textures properly
124 if(gamemode == GAME_NEXUIZ)
125 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
127 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
128 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
129 mod_q1bsp_texture_solid.surfaceflags = 0;
130 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
132 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
133 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
134 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
135 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
137 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
138 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
139 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
140 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
142 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
143 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
144 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
145 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
147 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
148 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
149 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
150 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
153 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
160 // LadyHavoc: modified to start at first clip node,
161 // in other words: first node of the (sub)model
162 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
164 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
166 return (mleaf_t *)node;
169 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
173 leaf = Mod_Q1BSP_PointInLeaf(model, p);
176 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
179 memcpy(out, leaf->ambient_sound_level, i);
185 memset(out, 0, outsize);
188 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
191 int nodestackindex = 0;
192 mnode_t *node, *nodestack[1024];
193 if (!model->brush.num_pvsclusters)
195 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
201 // node - recurse down the BSP tree
202 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
206 return -1; // ERROR: NAN bounding box!
207 // box is on one side of plane, take that path
208 node = node->children[sides-1];
212 // box crosses plane, take one path and remember the other
213 if (nodestackindex < 1024)
214 nodestack[nodestackindex++] = node->children[0];
215 node = node->children[1];
221 // leaf - add clusterindex to list
222 if (numclusters < maxclusters)
223 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
227 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
231 if (nodestackindex < 1024)
232 nodestack[nodestackindex++] = node->children[0];
233 node = node->children[1];
238 // leaf - add clusterindex to list
239 if (numclusters < maxclusters)
240 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
245 // try another path we didn't take earlier
246 if (nodestackindex == 0)
248 node = nodestack[--nodestackindex];
250 // return number of clusters found (even if more than the maxclusters)
254 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
256 int nodestackindex = 0;
257 mnode_t *node, *nodestack[1024];
258 if (!model->brush.num_pvsclusters)
260 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
266 // node - recurse down the BSP tree
267 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
271 return -1; // ERROR: NAN bounding box!
272 // box is on one side of plane, take that path
273 node = node->children[sides-1];
277 // box crosses plane, take one path and remember the other
278 if (nodestackindex < 1024)
279 nodestack[nodestackindex++] = node->children[0];
280 node = node->children[1];
286 // leaf - check cluster bit
287 int clusterindex = ((mleaf_t *)node)->clusterindex;
288 if (CHECKPVSBIT(pvs, clusterindex))
290 // it is visible, return immediately with the news
295 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
299 if (nodestackindex < 1024)
300 nodestack[nodestackindex++] = node->children[0];
301 node = node->children[1];
306 // leaf - check cluster bit
307 int clusterindex = ((mleaf_t *)node)->clusterindex;
308 if (CHECKPVSBIT(pvs, clusterindex))
310 // it is visible, return immediately with the news
316 // nothing to see here, try another path we didn't take earlier
317 if (nodestackindex == 0)
319 node = nodestack[--nodestackindex];
325 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
327 int nodestackindex = 0;
328 mnode_t *node, *nodestack[1024];
329 if (!model->brush.num_leafs)
331 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
337 // node - recurse down the BSP tree
338 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
342 return -1; // ERROR: NAN bounding box!
343 // box is on one side of plane, take that path
344 node = node->children[sides-1];
348 // box crosses plane, take one path and remember the other
349 if (nodestackindex < 1024)
350 nodestack[nodestackindex++] = node->children[0];
351 node = node->children[1];
357 // leaf - check cluster bit
358 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
359 if (CHECKPVSBIT(pvs, clusterindex))
361 // it is visible, return immediately with the news
366 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
370 if (nodestackindex < 1024)
371 nodestack[nodestackindex++] = node->children[0];
372 node = node->children[1];
377 // leaf - check cluster bit
378 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
379 if (CHECKPVSBIT(pvs, clusterindex))
381 // it is visible, return immediately with the news
387 // nothing to see here, try another path we didn't take earlier
388 if (nodestackindex == 0)
390 node = nodestack[--nodestackindex];
396 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
398 int nodestackindex = 0;
399 mnode_t *node, *nodestack[1024];
400 if (!model->brush.num_leafs)
402 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
408 // node - recurse down the BSP tree
409 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
413 return -1; // ERROR: NAN bounding box!
414 // box is on one side of plane, take that path
415 node = node->children[sides-1];
419 // box crosses plane, take one path and remember the other
420 if (nodestackindex < 1024)
421 nodestack[nodestackindex++] = node->children[0];
422 node = node->children[1];
428 // leaf - check if it is visible
429 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
431 // it is visible, return immediately with the news
436 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
440 if (nodestackindex < 1024)
441 nodestack[nodestackindex++] = node->children[0];
442 node = node->children[1];
447 // leaf - check if it is visible
448 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
450 // it is visible, return immediately with the news
456 // nothing to see here, try another path we didn't take earlier
457 if (nodestackindex == 0)
459 node = nodestack[--nodestackindex];
465 typedef struct findnonsolidlocationinfo_s
468 vec3_t absmin, absmax;
474 findnonsolidlocationinfo_t;
476 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
479 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
481 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
482 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
483 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
484 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
485 VectorSubtract(vert[1], vert[0], edge[0]);
486 VectorSubtract(vert[2], vert[1], edge[1]);
487 CrossProduct(edge[1], edge[0], facenormal);
488 if (facenormal[0] || facenormal[1] || facenormal[2])
490 VectorNormalize(facenormal);
491 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
492 if (f <= info->bestdist && f >= -info->bestdist)
494 VectorSubtract(vert[0], vert[2], edge[2]);
495 VectorNormalize(edge[0]);
496 VectorNormalize(edge[1]);
497 VectorNormalize(edge[2]);
498 CrossProduct(facenormal, edge[0], edgenormal[0]);
499 CrossProduct(facenormal, edge[1], edgenormal[1]);
500 CrossProduct(facenormal, edge[2], edgenormal[2]);
502 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
503 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
504 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
506 // we got lucky, the center is within the face
507 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
511 if (info->bestdist > dist)
513 info->bestdist = dist;
514 VectorScale(facenormal, (info->radius - -dist), info->nudge);
519 if (info->bestdist > dist)
521 info->bestdist = dist;
522 VectorScale(facenormal, (info->radius - dist), info->nudge);
528 // check which edge or vertex the center is nearest
529 for (i = 0;i < 3;i++)
531 f = DotProduct(info->center, edge[i]);
532 if (f >= DotProduct(vert[0], edge[i])
533 && f <= DotProduct(vert[1], edge[i]))
536 VectorMA(info->center, -f, edge[i], point);
537 dist = sqrt(DotProduct(point, point));
538 if (info->bestdist > dist)
540 info->bestdist = dist;
541 VectorScale(point, (info->radius / dist), info->nudge);
543 // skip both vertex checks
544 // (both are further away than this edge)
549 // not on edge, check first vertex of edge
550 VectorSubtract(info->center, vert[i], point);
551 dist = sqrt(DotProduct(point, point));
552 if (info->bestdist > dist)
554 info->bestdist = dist;
555 VectorScale(point, (info->radius / dist), info->nudge);
564 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
566 int surfacenum, k, *mark;
568 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
570 surface = info->model->data_surfaces + *mark;
571 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
573 if(surface->deprecatedq3num_bboxstride > 0)
576 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
577 for(i = 0; i < cnt; ++i)
579 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
581 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
583 tri = i * surface->deprecatedq3num_bboxstride + k;
584 if(tri >= surface->num_triangles)
586 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
593 for (k = 0;k < surface->num_triangles;k++)
595 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
602 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
606 float f = PlaneDiff(info->center, node->plane);
607 if (f >= -info->bestdist)
608 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
609 if (f <= info->bestdist)
610 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
614 if (((mleaf_t *)node)->numleafsurfaces)
615 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
619 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
622 findnonsolidlocationinfo_t info;
628 VectorCopy(in, info.center);
629 info.radius = radius;
634 VectorClear(info.nudge);
635 info.bestdist = radius;
636 VectorCopy(info.center, info.absmin);
637 VectorCopy(info.center, info.absmax);
638 info.absmin[0] -= info.radius + 1;
639 info.absmin[1] -= info.radius + 1;
640 info.absmin[2] -= info.radius + 1;
641 info.absmax[0] += info.radius + 1;
642 info.absmax[1] += info.radius + 1;
643 info.absmax[2] += info.radius + 1;
644 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
645 VectorAdd(info.center, info.nudge, info.center);
647 while (info.bestdist < radius && ++i < 10);
648 VectorCopy(info.center, out);
651 int Mod_Q1BSP_SuperContentsFromNativeContents(int nativecontents)
653 switch(nativecontents)
658 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
660 return SUPERCONTENTS_WATER;
662 return SUPERCONTENTS_SLIME;
664 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
666 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
671 int Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents)
673 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
674 return CONTENTS_SOLID;
675 if (supercontents & SUPERCONTENTS_SKY)
677 if (supercontents & SUPERCONTENTS_LAVA)
678 return CONTENTS_LAVA;
679 if (supercontents & SUPERCONTENTS_SLIME)
680 return CONTENTS_SLIME;
681 if (supercontents & SUPERCONTENTS_WATER)
682 return CONTENTS_WATER;
683 return CONTENTS_EMPTY;
686 typedef struct RecursiveHullCheckTraceInfo_s
688 // the hull we're tracing through
691 // the trace structure to fill in
694 // start, end, and end - start (in model space)
699 RecursiveHullCheckTraceInfo_t;
701 // 1/32 epsilon to keep floating point happy
702 #define DIST_EPSILON (0.03125)
704 #define HULLCHECKSTATE_EMPTY 0
705 #define HULLCHECKSTATE_SOLID 1
706 #define HULLCHECKSTATE_DONE 2
708 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
710 // status variables, these don't need to be saved on the stack when
711 // recursing... but are because this should be thread-safe
712 // (note: tracing against a bbox is not thread-safe, yet)
717 // variables that need to be stored on the stack when recursing
722 // keep looping until we hit a leaf
725 // find the point distances
726 node = t->hull->clipnodes + num;
727 plane = t->hull->planes + node->planenum;
729 // axial planes can be calculated more quickly without the DotProduct
732 t1 = p1[plane->type] - plane->dist;
733 t2 = p2[plane->type] - plane->dist;
737 t1 = DotProduct (plane->normal, p1) - plane->dist;
738 t2 = DotProduct (plane->normal, p2) - plane->dist;
741 // negative plane distances indicate children[1] (behind plane)
745 // if the line starts and ends on the same side of the plane, recurse
746 // into that child instantly
747 if (p1side == p2side)
749 #if COLLISIONPARANOID >= 3
755 // loop back and process the start child
756 num = node->children[p1side];
760 // find the midpoint where the line crosses the plane, use the
761 // original line for best accuracy
762 #if COLLISIONPARANOID >= 3
767 t1 = t->start[plane->type] - plane->dist;
768 t2 = t->end[plane->type] - plane->dist;
772 t1 = DotProduct (plane->normal, t->start) - plane->dist;
773 t2 = DotProduct (plane->normal, t->end) - plane->dist;
775 midf = t1 / (t1 - t2);
776 midf = bound(p1f, midf, p2f);
777 VectorMA(t->start, midf, t->dist, mid);
779 // we now have a mid point, essentially splitting the line into
780 // the segments in the near child and the far child, we can now
781 // recurse those in order and get their results
783 // recurse both sides, front side first
784 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
785 // if this side is not empty, return what it is (solid or done)
786 if (ret != HULLCHECKSTATE_EMPTY)
789 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
790 // if other side is not solid, return what it is (empty or done)
791 if (ret != HULLCHECKSTATE_SOLID)
794 // front is air and back is solid, this is the impact point...
796 // copy the plane information, flipping it if needed
799 t->trace->plane.dist = -plane->dist;
800 VectorNegate (plane->normal, t->trace->plane.normal);
804 t->trace->plane.dist = plane->dist;
805 VectorCopy (plane->normal, t->trace->plane.normal);
808 // calculate the return fraction which is nudged off the surface a bit
809 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
810 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
811 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
812 t->trace->fraction = bound(0, midf, 1);
814 #if COLLISIONPARANOID >= 3
817 return HULLCHECKSTATE_DONE;
821 // we reached a leaf contents
824 num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
825 if (!t->trace->startfound)
827 t->trace->startfound = true;
828 t->trace->startsupercontents |= num;
830 if (num & SUPERCONTENTS_LIQUIDSMASK)
831 t->trace->inwater = true;
833 t->trace->inopen = true;
834 if (num & SUPERCONTENTS_SOLID)
835 t->trace->hittexture = &mod_q1bsp_texture_solid;
836 else if (num & SUPERCONTENTS_SKY)
837 t->trace->hittexture = &mod_q1bsp_texture_sky;
838 else if (num & SUPERCONTENTS_LAVA)
839 t->trace->hittexture = &mod_q1bsp_texture_lava;
840 else if (num & SUPERCONTENTS_SLIME)
841 t->trace->hittexture = &mod_q1bsp_texture_slime;
843 t->trace->hittexture = &mod_q1bsp_texture_water;
844 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
845 t->trace->hitsupercontents = num;
846 if (num & t->trace->hitsupercontentsmask)
848 // if the first leaf is solid, set startsolid
849 if (t->trace->allsolid)
850 t->trace->startsolid = true;
851 #if COLLISIONPARANOID >= 3
854 return HULLCHECKSTATE_SOLID;
858 t->trace->allsolid = false;
859 #if COLLISIONPARANOID >= 3
862 return HULLCHECKSTATE_EMPTY;
866 //#if COLLISIONPARANOID < 2
867 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
870 mclipnode_t *nodes = t->hull->clipnodes;
871 mplane_t *planes = t->hull->planes;
873 VectorCopy(t->start, point);
876 plane = planes + nodes[num].planenum;
877 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
879 num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
880 t->trace->startsupercontents |= num;
881 if (num & SUPERCONTENTS_LIQUIDSMASK)
882 t->trace->inwater = true;
884 t->trace->inopen = true;
885 if (num & t->trace->hitsupercontentsmask)
887 t->trace->allsolid = t->trace->startsolid = true;
888 return HULLCHECKSTATE_SOLID;
892 t->trace->allsolid = t->trace->startsolid = false;
893 return HULLCHECKSTATE_EMPTY;
898 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)
900 RecursiveHullCheckTraceInfo_t rhc;
902 memset(&rhc, 0, sizeof(rhc));
903 memset(trace, 0, sizeof(trace_t));
905 rhc.trace->fraction = 1;
906 rhc.trace->allsolid = true;
907 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
908 VectorCopy(start, rhc.start);
909 VectorCopy(start, rhc.end);
910 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
913 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);
915 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)
917 RecursiveHullCheckTraceInfo_t rhc;
919 if (VectorCompare(start, end))
921 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
925 // 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...
926 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
928 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
932 memset(&rhc, 0, sizeof(rhc));
933 memset(trace, 0, sizeof(trace_t));
935 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
936 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
937 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
938 rhc.trace->fraction = 1;
939 rhc.trace->allsolid = true;
940 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
941 VectorCopy(start, rhc.start);
942 VectorCopy(end, rhc.end);
943 VectorSubtract(rhc.end, rhc.start, rhc.dist);
944 #if COLLISIONPARANOID >= 2
945 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]);
946 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
951 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
952 memset(&testtrace, 0, sizeof(trace_t));
953 rhc.trace = &testtrace;
954 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
955 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
956 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
957 rhc.trace->fraction = 1;
958 rhc.trace->allsolid = true;
959 VectorCopy(test, rhc.start);
960 VectorCopy(test, rhc.end);
961 VectorClear(rhc.dist);
962 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
963 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
964 if (!trace->startsolid && testtrace.startsolid)
965 Con_Printf(" - ended in solid!\n");
969 if (VectorLength2(rhc.dist))
970 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
972 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
976 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)
978 // this function currently only supports same size start and end
980 RecursiveHullCheckTraceInfo_t rhc;
982 if (VectorCompare(boxmins, boxmaxs))
984 if (VectorCompare(start, end))
985 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
987 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
991 memset(&rhc, 0, sizeof(rhc));
992 memset(trace, 0, sizeof(trace_t));
994 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
995 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
996 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
997 rhc.trace->fraction = 1;
998 rhc.trace->allsolid = true;
999 VectorSubtract(boxmaxs, boxmins, boxsize);
1001 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1002 else if (model->brush.ishlbsp)
1004 // LadyHavoc: this has to have a minor tolerance (the .1) because of
1005 // minor float precision errors from the box being transformed around
1006 if (boxsize[0] < 32.1)
1008 if (boxsize[2] < 54) // pick the nearest of 36 or 72
1009 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
1011 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
1014 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1018 // LadyHavoc: this has to have a minor tolerance (the .1) because of
1019 // minor float precision errors from the box being transformed around
1020 if (boxsize[0] < 32.1)
1021 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1023 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1025 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1026 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1027 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1028 #if COLLISIONPARANOID >= 2
1029 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]);
1030 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1035 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1036 memset(&testtrace, 0, sizeof(trace_t));
1037 rhc.trace = &testtrace;
1038 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1039 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1040 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1041 rhc.trace->fraction = 1;
1042 rhc.trace->allsolid = true;
1043 VectorCopy(test, rhc.start);
1044 VectorCopy(test, rhc.end);
1045 VectorClear(rhc.dist);
1046 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1047 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1048 if (!trace->startsolid && testtrace.startsolid)
1049 Con_Printf(" - ended in solid!\n");
1053 if (VectorLength2(rhc.dist))
1054 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1056 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1060 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1062 int num = model->brushq1.hulls[0].firstclipnode;
1064 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1065 mplane_t *planes = model->brushq1.hulls[0].planes;
1068 plane = planes + nodes[num].planenum;
1069 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1071 return Mod_Q1BSP_SuperContentsFromNativeContents(num);
1074 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)
1078 colplanef_t cbox_planes[6];
1080 cbox.hasaabbplanes = true;
1081 cbox.supercontents = boxsupercontents;
1084 cbox.numtriangles = 0;
1085 cbox.planes = cbox_planes;
1087 cbox.elements = NULL;
1095 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];
1096 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];
1097 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];
1098 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];
1099 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];
1100 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];
1101 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1102 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1103 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1104 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1105 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1106 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1107 memset(trace, 0, sizeof(trace_t));
1108 trace->hitsupercontentsmask = hitsupercontentsmask;
1109 trace->skipsupercontentsmask = skipsupercontentsmask;
1110 trace->skipmaterialflagsmask = skipmaterialflagsmask;
1111 trace->fraction = 1;
1112 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1114 RecursiveHullCheckTraceInfo_t rhc;
1115 static hull_t box_hull;
1116 static mclipnode_t box_clipnodes[6];
1117 static mplane_t box_planes[6];
1118 // fill in a default trace
1119 memset(&rhc, 0, sizeof(rhc));
1120 memset(trace, 0, sizeof(trace_t));
1121 //To keep everything totally uniform, bounding boxes are turned into small
1122 //BSP trees instead of being compared directly.
1123 // create a temp hull from bounding box sizes
1124 box_planes[0].dist = cmaxs[0] - mins[0];
1125 box_planes[1].dist = cmins[0] - maxs[0];
1126 box_planes[2].dist = cmaxs[1] - mins[1];
1127 box_planes[3].dist = cmins[1] - maxs[1];
1128 box_planes[4].dist = cmaxs[2] - mins[2];
1129 box_planes[5].dist = cmins[2] - maxs[2];
1130 #if COLLISIONPARANOID >= 3
1131 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]);
1134 if (box_hull.clipnodes == NULL)
1138 //Set up the planes and clipnodes so that the six floats of a bounding box
1139 //can just be stored out and get a proper hull_t structure.
1141 box_hull.clipnodes = box_clipnodes;
1142 box_hull.planes = box_planes;
1143 box_hull.firstclipnode = 0;
1144 box_hull.lastclipnode = 5;
1146 for (i = 0;i < 6;i++)
1148 box_clipnodes[i].planenum = i;
1152 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1154 box_clipnodes[i].children[side^1] = i + 1;
1156 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1158 box_planes[i].type = i>>1;
1159 box_planes[i].normal[i>>1] = 1;
1163 // trace a line through the generated clipping hull
1164 //rhc.boxsupercontents = boxsupercontents;
1165 rhc.hull = &box_hull;
1167 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1168 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1169 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1170 rhc.trace->fraction = 1;
1171 rhc.trace->allsolid = true;
1172 VectorCopy(start, rhc.start);
1173 VectorCopy(end, rhc.end);
1174 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1175 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1176 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1177 if (rhc.trace->startsupercontents)
1178 rhc.trace->startsupercontents = boxsupercontents;
1182 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)
1184 memset(trace, 0, sizeof(trace_t));
1185 trace->fraction = 1;
1186 trace->hitsupercontentsmask = hitsupercontentsmask;
1187 trace->skipsupercontentsmask = skipsupercontentsmask;
1188 trace->skipmaterialflagsmask = skipmaterialflagsmask;
1189 if (BoxesOverlap(start, start, cmins, cmaxs))
1191 trace->startsupercontents |= boxsupercontents;
1192 if ((hitsupercontentsmask & boxsupercontents) && !(skipsupercontentsmask & boxsupercontents))
1194 trace->startsolid = true;
1195 trace->allsolid = true;
1200 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)
1203 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
1204 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
1207 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)
1211 float mid, distz = endz - startz;
1215 switch (node->plane->type)
1218 node = node->children[x < node->plane->dist];
1219 continue; // loop back and process the new node
1221 node = node->children[y < node->plane->dist];
1222 continue; // loop back and process the new node
1224 side = startz < node->plane->dist;
1225 if ((endz < node->plane->dist) == side)
1227 node = node->children[side];
1228 continue; // loop back and process the new node
1230 // found an intersection
1231 mid = node->plane->dist;
1234 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1235 front += startz * node->plane->normal[2];
1236 back += endz * node->plane->normal[2];
1237 side = front < node->plane->dist;
1238 if ((back < node->plane->dist) == side)
1240 node = node->children[side];
1241 continue; // loop back and process the new node
1243 // found an intersection
1244 mid = startz + distz * (front - node->plane->dist) / (front - back);
1248 // go down front side
1249 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1250 return true; // hit something
1252 // check for impact on this node
1253 if (node->numsurfaces)
1256 int dsi, dti, lmwidth, lmheight;
1258 msurface_t *surface;
1259 unsigned char *lightmap;
1260 int maps, line3, size3;
1263 float scale, w, w00, w01, w10, w11;
1265 surface = model->data_surfaces + node->firstsurface;
1266 for (i = 0;i < node->numsurfaces;i++, surface++)
1268 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1269 continue; // no lightmaps
1271 // location we want to sample in the lightmap
1272 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;
1273 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;
1276 // thanks to jitspoe for pointing out that this int cast was
1277 // rounding toward zero, so we floor it
1278 dsi = (int)floor(ds);
1279 dti = (int)floor(dt);
1280 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1281 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1284 // we have to tolerate a position of lmwidth-1 for some rare
1285 // cases - in which case the sampling position still gets
1286 // clamped but the color gets interpolated to that edge.
1287 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1289 // in the rare cases where we're sampling slightly off
1290 // the polygon, clamp the sampling position (we can still
1291 // interpolate outside it, where it becomes extrapolation)
1296 if (dsi > lmwidth-2)
1298 if (dti > lmheight-2)
1301 // calculate bilinear interpolation factors
1302 // and also multiply by fixedpoint conversion factors to
1303 // compensate for lightmaps being 0-255 (as 0-2), we use
1304 // r_refdef.scene.rtlightstylevalue here which is already
1305 // 0.000-2.148 range
1306 // (if we used r_refdef.scene.lightstylevalue this
1307 // divisor would be 32768 rather than 128)
1310 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1311 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1312 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1313 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1315 // values for pointer math
1316 line3 = lmwidth * 3; // LadyHavoc: *3 for colored lighting
1317 size3 = lmwidth * lmheight * 3; // LadyHavoc: *3 for colored lighting
1319 // look up the pixel
1320 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LadyHavoc: *3 for colored lighting
1322 // bilinear filter each lightmap style, and sum them
1323 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1325 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1326 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1327 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1328 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1329 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1333 return true; // success
1338 // go down back side
1339 node = node->children[side ^ 1];
1341 distz = endz - startz;
1342 // loop back and process the new node
1345 // did not hit anything
1349 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1351 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1352 VectorSet(diffusenormal, 0, 0, 1);
1354 if (!model->brushq1.lightdata)
1356 VectorSet(ambientcolor, 1, 1, 1);
1357 VectorSet(diffusecolor, 0, 0, 0);
1361 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);
1364 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1369 const msurface_t *surface;
1374 float edgenormal[3];
1381 surface = model->data_surfaces + node->firstsurface;
1382 for (i = 0;i < node->numsurfaces;i++, surface++)
1384 // skip surfaces whose bounding box does not include the point
1385 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1387 // skip faces with contents we don't care about
1388 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1390 // ignore surfaces matching the skipsupercontentsmask (this is rare)
1391 if (t->trace->skipsupercontentsmask & surface->texture->supercontents)
1393 // skip surfaces matching the skipmaterialflagsmask (e.g. MATERIALFLAG_NOSHADOW)
1394 if (t->trace->skipmaterialflagsmask & surface->texture->currentmaterialflags)
1396 // get the surface normal - since it is flat we know any vertex normal will suffice
1397 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1399 if (DotProduct(t->dist, normal) > 0)
1401 // iterate edges and see if the point is outside one of them
1402 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1404 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1405 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1406 VectorSubtract(v0, v1, edgedir);
1407 CrossProduct(edgedir, normal, edgenormal);
1408 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1411 // if the point is outside one of the edges, it is not within the surface
1412 if (j < surface->num_vertices)
1415 // we hit a surface, this is the impact point...
1416 VectorCopy(normal, t->trace->plane.normal);
1417 t->trace->plane.dist = DotProduct(normal, p);
1419 // calculate the return fraction which is nudged off the surface a bit
1420 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1421 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1422 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1423 t->trace->fraction = bound(0, midf, 1);
1425 t->trace->hittexture = surface->texture->currentframe;
1426 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1427 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1428 return surface->texture->currentframe;
1433 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])
1435 const mplane_t *plane;
1438 double midf, mid[3];
1439 const mleaf_t *leaf;
1443 plane = node->plane;
1444 if (plane->type < 3)
1446 t1 = p1[plane->type] - plane->dist;
1447 t2 = p2[plane->type] - plane->dist;
1451 t1 = DotProduct (plane->normal, p1) - plane->dist;
1452 t2 = DotProduct (plane->normal, p2) - plane->dist;
1458 node = node->children[1];
1467 node = node->children[0];
1473 // the line intersects, find intersection point
1474 // LadyHavoc: this uses the original trace for maximum accuracy
1475 if (plane->type < 3)
1477 t1 = t->start[plane->type] - plane->dist;
1478 t2 = t->end[plane->type] - plane->dist;
1482 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1483 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1486 midf = t1 / (t1 - t2);
1487 VectorMA(t->start, midf, t->dist, mid);
1489 // recurse both sides, front side first, return if we hit a surface
1490 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1491 return HULLCHECKSTATE_DONE;
1493 // test each surface on the node
1494 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1495 if (t->trace->hittexture)
1496 return HULLCHECKSTATE_DONE;
1498 // recurse back side
1499 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1501 leaf = (const mleaf_t *)node;
1502 side = Mod_Q1BSP_SuperContentsFromNativeContents(leaf->contents);
1503 if (!t->trace->startfound)
1505 t->trace->startfound = true;
1506 t->trace->startsupercontents |= side;
1508 if (side & SUPERCONTENTS_LIQUIDSMASK)
1509 t->trace->inwater = true;
1511 t->trace->inopen = true;
1512 if (side & t->trace->hitsupercontentsmask)
1514 // if the first leaf is solid, set startsolid
1515 if (t->trace->allsolid)
1516 t->trace->startsolid = true;
1517 return HULLCHECKSTATE_SOLID;
1521 t->trace->allsolid = false;
1522 return HULLCHECKSTATE_EMPTY;
1526 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)
1528 RecursiveHullCheckTraceInfo_t rhc;
1530 memset(&rhc, 0, sizeof(rhc));
1531 memset(trace, 0, sizeof(trace_t));
1533 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1534 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1535 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1536 rhc.trace->fraction = 1;
1537 rhc.trace->allsolid = true;
1538 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1539 VectorCopy(start, rhc.start);
1540 VectorCopy(end, rhc.end);
1541 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1542 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1543 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1546 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1549 unsigned char *outstart = out;
1550 while (out < outend)
1554 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));
1564 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));
1567 for (c = *in++;c > 0;c--)
1571 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));
1582 R_Q1BSP_LoadSplitSky
1584 A sky texture is 256*128, with the right side being a masked overlay
1587 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1592 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1593 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1595 // allocate a texture pool if we need it
1596 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1597 loadmodel->texturepool = R_AllocTexturePool();
1599 if (bytesperpixel == 4)
1601 for (y = 0;y < h;y++)
1603 for (x = 0;x < w;x++)
1605 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1606 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1612 // make an average value for the back to avoid
1613 // a fringe on the top level
1622 for (y = 0;y < h;y++)
1624 for (x = 0;x < w;x++)
1626 p = src[x*width+y+w];
1627 r += palette_rgb[p][0];
1628 g += palette_rgb[p][1];
1629 b += palette_rgb[p][2];
1632 bgra.b[2] = r/(w*h);
1633 bgra.b[1] = g/(w*h);
1634 bgra.b[0] = b/(w*h);
1636 for (y = 0;y < h;y++)
1638 for (x = 0;x < w;x++)
1640 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1642 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1647 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, 0, 0, 0, vid.sRGB3D);
1648 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, 0, 0, 0, vid.sRGB3D);
1649 Mem_Free(solidpixels);
1650 Mem_Free(alphapixels);
1653 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1655 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0, firstskynoshadowtexture = 0;
1656 skinframe_t *skinframemissing;
1657 texture_t *tx, *tx2, *anims[10], *altanims[10], *currentskynoshadowtexture;
1658 texture_t backuptex;
1659 unsigned char *data, *mtdata;
1661 char mapname[MAX_QPATH], name[MAX_QPATH];
1662 unsigned char zeroopaque[4], zerotrans[4];
1665 Vector4Set(zeroopaque, 0, 0, 0, 255);
1666 Vector4Set(zerotrans, 0, 0, 0, 128);
1668 loadmodel->data_textures = NULL;
1670 // add two slots for notexture walls and notexture liquids, and duplicate
1671 // all sky textures; sky surfaces can be shadow-casting or not, the surface
1672 // loading will choose according to the contents behind the surface
1673 // (necessary to support e1m5 logo shadow which has a SKY contents brush,
1674 // while correctly treating sky textures as occluders in other situations).
1679 nummiptex = MSG_ReadLittleLong(sb);
1680 loadmodel->num_textures = nummiptex + 2;
1681 // save the position so we can go back to it
1682 watermark = sb->readcount;
1683 for (i = 0; i < nummiptex; i++)
1685 doffset = MSG_ReadLittleLong(sb);
1686 if (r_nosurftextures.integer)
1690 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1694 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1696 // copy name, but only up to 16 characters
1697 // (the output buffer can hold more than this, but the input buffer is
1699 for (j = 0; j < 16; j++)
1700 name[j] = MSG_ReadByte(&miptexsb);
1702 // pretty up the buffer (replacing any trailing garbage with 0)
1703 for (j = (int)strlen(name); j < 16; j++)
1706 if (!strncmp(name, "sky", 3))
1710 // bump it back to where we started parsing
1711 sb->readcount = (int)watermark;
1713 firstskynoshadowtexture = loadmodel->num_textures;
1714 loadmodel->num_textures += numsky;
1718 loadmodel->num_textures = 2;
1719 firstskynoshadowtexture = loadmodel->num_textures;
1721 loadmodel->num_texturesperskin = loadmodel->num_textures;
1723 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1725 // we'll be writing to these in parallel for sky textures
1726 currentskynoshadowtexture = loadmodel->data_textures + firstskynoshadowtexture;
1728 // fill out all slots with notexture
1729 skinframemissing = R_SkinFrame_LoadMissing();
1730 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1732 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1735 tx->basealpha = 1.0f;
1736 tx->materialshaderpass = tx->shaderpasses[0] = Mod_CreateShaderPass(loadmodel->mempool, skinframemissing);
1737 tx->materialshaderpass->skinframes[0] = skinframemissing;
1738 tx->currentskinframe = skinframemissing;
1739 tx->basematerialflags = MATERIALFLAG_WALL;
1740 if (i == loadmodel->num_textures - 1)
1742 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1743 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1744 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1748 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1749 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1751 tx->currentframe = tx;
1753 // clear water settings
1756 tx->refractive_index = mod_q3shader_default_refractive_index.value;
1757 tx->refractfactor = 1;
1758 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1759 tx->reflectfactor = 1;
1760 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1761 tx->r_water_wateralpha = 1;
1762 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1763 tx->offsetscale = 1;
1765 tx->specularscalemod = 1;
1766 tx->specularpowermod = 1;
1767 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1768 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1769 // JUST GREP FOR "specularscalemod = 1".
1774 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1778 s = loadmodel->name;
1779 if (!strncasecmp(s, "maps/", 5))
1781 FS_StripExtension(s, mapname, sizeof(mapname));
1783 // LadyHavoc: mostly rewritten map texture loader
1784 for (i = 0;i < nummiptex;i++)
1786 doffset = MSG_ReadLittleLong(sb);
1787 if (r_nosurftextures.integer)
1791 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1795 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1797 // copy name, but only up to 16 characters
1798 // (the output buffer can hold more than this, but the input buffer is
1800 for (j = 0;j < 16;j++)
1801 name[j] = MSG_ReadByte(&miptexsb);
1803 // pretty up the buffer (replacing any trailing garbage with 0)
1804 for (j = (int)strlen(name);j < 16;j++)
1809 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1810 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1813 mtwidth = MSG_ReadLittleLong(&miptexsb);
1814 mtheight = MSG_ReadLittleLong(&miptexsb);
1816 j = MSG_ReadLittleLong(&miptexsb);
1820 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1822 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1825 mtdata = miptexsb.data + j;
1828 if ((mtwidth & 15) || (mtheight & 15))
1829 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1831 // LadyHavoc: force all names to lowercase
1832 for (j = 0;name[j];j++)
1833 if (name[j] >= 'A' && name[j] <= 'Z')
1834 name[j] += 'a' - 'A';
1836 // LadyHavoc: backup the texture_t because q3 shader loading overwrites it
1837 backuptex = loadmodel->data_textures[i];
1838 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, loadmodel->data_textures + i, name, false, false, 0, MATERIALFLAG_WALL))
1840 loadmodel->data_textures[i] = backuptex;
1842 tx = loadmodel->data_textures + i;
1843 strlcpy(tx->name, name, sizeof(tx->name));
1844 tx->width = mtwidth;
1845 tx->height = mtheight;
1846 tx->basealpha = 1.0f;
1848 // start out with no animation
1849 tx->currentframe = tx;
1850 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
1852 if (tx->name[0] == '*')
1854 if (!strncmp(tx->name, "*lava", 5))
1856 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1857 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1859 else if (!strncmp(tx->name, "*slime", 6))
1861 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1862 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1866 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1867 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1870 else if (!strncmp(tx->name, "sky", 3))
1872 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1873 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1874 // for the surface traceline we need to hit this surface as a solid...
1875 tx->supercontents |= SUPERCONTENTS_SOLID;
1879 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1880 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1883 if (cls.state != ca_dedicated)
1885 // LadyHavoc: HL sky textures are entirely different than quake
1886 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1888 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1890 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1891 if (data && image_width == image_height * 2)
1893 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1896 else if (mtdata != NULL)
1897 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1901 skinframe_t *skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false, false);
1903 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false, false);
1905 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1908 // did not find external texture, load it from the bsp or wad3
1909 if (loadmodel->brush.ishlbsp)
1911 // internal texture overrides wad
1912 unsigned char *pixels, *freepixels;
1913 pixels = freepixels = NULL;
1915 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1917 pixels = freepixels = W_GetTextureBGRA(tx->name);
1920 tx->width = image_width;
1921 tx->height = image_height;
1922 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, image_width, image_height, CRC_Block(pixels, image_width * image_height * 4), true);
1925 Mem_Free(freepixels);
1927 else if (mtdata) // texture included
1928 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1930 // if skinframe is still NULL the "missing" texture has already been assigned to this
1932 tx->materialshaderpass->skinframes[0] = skinframe;
1934 // LadyHavoc: some Tenebrae textures get replaced by black
1935 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1936 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, 0, 0, 0, false);
1937 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1938 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, 0, 0, 0, false);
1939 tx->currentskinframe = tx->materialshaderpass->skinframes[0];
1942 tx->basematerialflags = MATERIALFLAG_WALL;
1943 if (tx->name[0] == '*')
1945 // LadyHavoc: some turbulent textures should not be affected by wateralpha
1946 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1947 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1948 else if (!strncmp(tx->name,"*lava",5)
1949 || !strncmp(tx->name,"*teleport",9)
1950 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1951 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1953 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1954 if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1955 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1957 else if (tx->name[0] == '{') // fence textures
1959 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1961 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1963 // replace the texture with black
1964 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1966 else if (!strncmp(tx->name, "sky", 3))
1967 tx->basematerialflags = MATERIALFLAG_SKY;
1968 else if (!strcmp(tx->name, "caulk"))
1969 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1970 else if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1971 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1972 tx->currentmaterialflags = tx->basematerialflags;
1974 // duplicate of sky with NOSHADOW
1975 if (tx->basematerialflags & MATERIALFLAG_SKY)
1977 *currentskynoshadowtexture = *tx;
1978 currentskynoshadowtexture->basematerialflags |= MATERIALFLAG_NOSHADOW;
1979 tx->skynoshadowtexture = currentskynoshadowtexture;
1980 currentskynoshadowtexture++;
1984 // sequence the animations
1985 for (i = 0;i < nummiptex;i++)
1987 tx = loadmodel->data_textures + i;
1988 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1991 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1993 Con_Printf("Bad animating texture %s\n", tx->name);
1996 if (tx->anim_total[0] || tx->anim_total[1])
1997 continue; // already sequenced
1999 // find the number of frames in the animation
2000 memset(anims, 0, sizeof(anims));
2001 memset(altanims, 0, sizeof(altanims));
2003 for (j = i;j < nummiptex;j++)
2005 tx2 = loadmodel->data_textures + j;
2006 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
2010 if (num >= '0' && num <= '9')
2011 anims[num - '0'] = tx2;
2012 else if (num >= 'a' && num <= 'j')
2013 altanims[num - 'a'] = tx2;
2014 // No need to warn otherwise - we already did above.
2018 for (j = 0;j < 10;j++)
2025 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
2028 for (j = 0;j < max;j++)
2032 Con_Printf("Missing frame %i of %s\n", j, tx->name);
2036 for (j = 0;j < altmax;j++)
2040 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
2047 // If we have exactly one frame, something's wrong.
2048 if (max + altmax <= 1)
2050 Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
2055 // if there is no alternate animation, duplicate the primary
2056 // animation into the alternate
2058 for (k = 0;k < 10;k++)
2059 altanims[k] = anims[k];
2065 Con_Printf("Missing frame 0 of %s\n", tx->name);
2067 // however, we can handle this by duplicating the alternate animation into the primary
2069 for (k = 0;k < 10;k++)
2070 anims[k] = altanims[k];
2074 // link together the primary animation
2075 for (j = 0;j < max;j++)
2078 tx2->animated = 1; // q1bsp
2079 tx2->anim_total[0] = max;
2080 tx2->anim_total[1] = altmax;
2081 for (k = 0;k < 10;k++)
2083 tx2->anim_frames[0][k] = anims[k];
2084 tx2->anim_frames[1][k] = altanims[k];
2088 // if there really is an alternate anim...
2089 if (anims[0] != altanims[0])
2091 // link together the alternate animation
2092 for (j = 0;j < altmax;j++)
2095 tx2->animated = 1; // q1bsp
2096 // the primary/alternate are reversed here
2097 tx2->anim_total[0] = altmax;
2098 tx2->anim_total[1] = max;
2099 for (k = 0;k < 10;k++)
2101 tx2->anim_frames[0][k] = altanims[k];
2102 tx2->anim_frames[1][k] = anims[k];
2109 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2112 unsigned char *in, *out, *data, d;
2113 char litfilename[MAX_QPATH];
2114 char dlitfilename[MAX_QPATH];
2115 fs_offset_t filesize;
2116 if (loadmodel->brush.ishlbsp) // LadyHavoc: load the colored lighting data straight
2118 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2119 for (i = 0;i < sb->cursize;i++)
2120 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2122 else // LadyHavoc: bsp version 29 (normal white lighting)
2124 // LadyHavoc: hope is not lost yet, check for a .lit file to load
2125 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2126 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2127 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2128 strlcat (litfilename, ".lit", sizeof (litfilename));
2129 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2130 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2133 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2135 i = LittleLong(((int *)data)[1]);
2138 if (developer_loading.integer)
2139 Con_Printf("loaded %s\n", litfilename);
2140 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2141 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2143 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2146 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2148 i = LittleLong(((int *)data)[1]);
2151 if (developer_loading.integer)
2152 Con_Printf("loaded %s\n", dlitfilename);
2153 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2154 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2155 loadmodel->brushq3.deluxemapping_modelspace = false;
2156 loadmodel->brushq3.deluxemapping = true;
2165 Con_Printf("Unknown .lit file version (%d)\n", i);
2167 else if (filesize == 8)
2168 Con_Print("Empty .lit file, ignoring\n");
2170 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2177 // LadyHavoc: oh well, expand the white lighting data
2180 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2182 out = loadmodel->brushq1.lightdata;
2183 for (i = 0;i < sb->cursize;i++)
2193 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2195 loadmodel->brushq1.num_compressedpvs = 0;
2196 loadmodel->brushq1.data_compressedpvs = NULL;
2199 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2200 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2201 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2204 // used only for HalfLife maps
2205 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2207 char key[128], value[4096];
2211 if (!COM_ParseToken_Simple(&data, false, false, true))
2213 if (com_token[0] != '{')
2217 if (!COM_ParseToken_Simple(&data, false, false, true))
2219 if (com_token[0] == '}')
2220 break; // end of worldspawn
2221 if (com_token[0] == '_')
2222 strlcpy(key, com_token + 1, sizeof(key));
2224 strlcpy(key, com_token, sizeof(key));
2225 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2226 key[strlen(key)-1] = 0;
2227 if (!COM_ParseToken_Simple(&data, false, false, true))
2229 dpsnprintf(value, sizeof(value), "%s", com_token);
2230 if (!strcmp("wad", key)) // for HalfLife maps
2232 if (loadmodel->brush.ishlbsp)
2235 for (i = 0;i < (int)sizeof(value);i++)
2236 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2238 if (i < (int)sizeof(value) && value[i])
2240 for (;i < (int)sizeof(value);i++)
2242 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2243 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2245 else if (value[i] == ';' || value[i] == 0)
2249 W_LoadTextureWadFile(&value[j], false);
2261 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2263 loadmodel->brush.entities = NULL;
2266 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2267 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2268 loadmodel->brush.entities[sb->cursize] = 0;
2269 if (loadmodel->brush.ishlbsp)
2270 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2274 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2278 int structsize = 12;
2280 if (sb->cursize % structsize)
2281 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2282 count = sb->cursize / structsize;
2283 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2285 loadmodel->brushq1.vertexes = out;
2286 loadmodel->brushq1.numvertexes = count;
2288 for ( i=0 ; i<count ; i++, out++)
2290 out->position[0] = MSG_ReadLittleFloat(sb);
2291 out->position[1] = MSG_ReadLittleFloat(sb);
2292 out->position[2] = MSG_ReadLittleFloat(sb);
2296 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2300 int structsize = (48+4*hullinfo->filehulls);
2302 if (sb->cursize % structsize)
2303 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2305 count = sb->cursize / structsize;
2306 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2308 loadmodel->brushq1.submodels = out;
2309 loadmodel->brush.numsubmodels = count;
2311 for (i = 0; i < count; i++, out++)
2313 // spread out the mins / maxs by a pixel
2314 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2315 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2316 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2317 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2318 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2319 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2320 out->origin[0] = MSG_ReadLittleFloat(sb);
2321 out->origin[1] = MSG_ReadLittleFloat(sb);
2322 out->origin[2] = MSG_ReadLittleFloat(sb);
2323 for (j = 0; j < hullinfo->filehulls; j++)
2324 out->headnode[j] = MSG_ReadLittleLong(sb);
2325 out->visleafs = MSG_ReadLittleLong(sb);
2326 out->firstface = MSG_ReadLittleLong(sb);
2327 out->numfaces = MSG_ReadLittleLong(sb);
2331 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2335 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2337 if (sb->cursize % structsize)
2338 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2339 count = sb->cursize / structsize;
2340 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2342 loadmodel->brushq1.edges = out;
2343 loadmodel->brushq1.numedges = count;
2345 for ( i=0 ; i<count ; i++, out++)
2347 if (loadmodel->brush.isbsp2)
2349 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2350 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2354 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2355 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2357 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2359 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);
2360 if(!loadmodel->brushq1.numvertexes)
2361 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2369 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2372 int i, j, k, count, miptex;
2373 int structsize = 40;
2375 if (sb->cursize % structsize)
2376 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2377 count = sb->cursize / structsize;
2378 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2380 loadmodel->brushq1.texinfo = out;
2381 loadmodel->brushq1.numtexinfo = count;
2383 for (i = 0;i < count;i++, out++)
2385 for (k = 0;k < 2;k++)
2386 for (j = 0;j < 4;j++)
2387 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2389 miptex = MSG_ReadLittleLong(sb);
2390 out->q1flags = MSG_ReadLittleLong(sb);
2392 if (out->q1flags & TEX_SPECIAL)
2394 // if texture chosen is NULL or the shader needs a lightmap,
2395 // force to notexture water shader
2396 out->textureindex = loadmodel->num_textures - 1;
2400 // if texture chosen is NULL, force to notexture
2401 out->textureindex = loadmodel->num_textures - 2;
2403 // see if the specified miptex is valid and try to use it instead
2404 if (loadmodel->data_textures)
2406 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2407 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2409 out->textureindex = miptex;
2415 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2420 mins[0] = mins[1] = mins[2] = 9999;
2421 maxs[0] = maxs[1] = maxs[2] = -9999;
2423 for (i = 0;i < numverts;i++)
2425 for (j = 0;j < 3;j++, v++)
2435 #define MAX_SUBDIVPOLYTRIANGLES 4096
2436 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2438 static int subdivpolyverts, subdivpolytriangles;
2439 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2440 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2442 static int subdivpolylookupvert(vec3_t v)
2445 for (i = 0;i < subdivpolyverts;i++)
2446 if (subdivpolyvert[i][0] == v[0]
2447 && subdivpolyvert[i][1] == v[1]
2448 && subdivpolyvert[i][2] == v[2])
2450 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2451 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2452 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2453 return subdivpolyverts++;
2456 static void SubdividePolygon(int numverts, float *verts)
2458 int i, i1, i2, i3, f, b, c, p;
2459 vec3_t mins, maxs, front[256], back[256];
2460 float m, *pv, *cv, dist[256], frac;
2463 Host_Error("SubdividePolygon: ran out of verts in buffer");
2465 BoundPoly(numverts, verts, mins, maxs);
2467 for (i = 0;i < 3;i++)
2469 m = (mins[i] + maxs[i]) * 0.5;
2470 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2471 if (maxs[i] - m < 8)
2473 if (m - mins[i] < 8)
2477 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2478 dist[c] = cv[i] - m;
2481 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2485 VectorCopy(pv, front[f]);
2490 VectorCopy(pv, back[b]);
2493 if (dist[p] == 0 || dist[c] == 0)
2495 if ((dist[p] > 0) != (dist[c] > 0) )
2498 frac = dist[p] / (dist[p] - dist[c]);
2499 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2500 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2501 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2507 SubdividePolygon(f, front[0]);
2508 SubdividePolygon(b, back[0]);
2512 i1 = subdivpolylookupvert(verts);
2513 i2 = subdivpolylookupvert(verts + 3);
2514 for (i = 2;i < numverts;i++)
2516 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2518 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2522 i3 = subdivpolylookupvert(verts + i * 3);
2523 subdivpolyindex[subdivpolytriangles][0] = i1;
2524 subdivpolyindex[subdivpolytriangles][1] = i2;
2525 subdivpolyindex[subdivpolytriangles][2] = i3;
2527 subdivpolytriangles++;
2531 //Breaks a polygon up along axial 64 unit
2532 //boundaries so that turbulent and sky warps
2533 //can be done reasonably.
2534 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2540 subdivpolytriangles = 0;
2541 subdivpolyverts = 0;
2542 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2543 if (subdivpolytriangles < 1)
2544 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2546 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2547 mesh->num_vertices = subdivpolyverts;
2548 mesh->num_triangles = subdivpolytriangles;
2549 mesh->vertex = (surfvertex_t *)(mesh + 1);
2550 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2551 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2553 for (i = 0;i < mesh->num_triangles;i++)
2554 for (j = 0;j < 3;j++)
2555 mesh->index[i*3+j] = subdivpolyindex[i][j];
2557 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2559 VectorCopy(subdivpolyvert[i], v->v);
2560 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2561 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2566 extern cvar_t gl_max_lightmapsize;
2567 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2569 msurface_t *surface;
2570 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2571 float texmins[2], texmaxs[2], val;
2572 rtexture_t *lightmaptexture, *deluxemaptexture;
2574 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2576 if (sb->cursize % structsize)
2577 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2578 count = sb->cursize / structsize;
2579 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2580 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2582 loadmodel->num_surfaces = count;
2584 loadmodel->brushq1.firstrender = true;
2585 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2589 for (surfacenum = 0;surfacenum < count;surfacenum++)
2591 if (loadmodel->brush.isbsp2)
2592 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2594 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2595 totalverts += numedges;
2596 totaltris += numedges - 2;
2599 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
2601 lightmaptexture = NULL;
2602 deluxemaptexture = r_texture_blanknormalmap;
2604 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2605 totallightmapsamples = 0;
2609 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2611 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2612 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2613 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2614 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2615 firstedge = MSG_ReadLittleLong(sb);
2616 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2617 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2618 for (i = 0;i < MAXLIGHTMAPS;i++)
2619 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2620 lightmapoffset = MSG_ReadLittleLong(sb);
2622 // FIXME: validate edges, texinfo, etc?
2623 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)
2624 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2625 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2626 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2627 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2628 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2630 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2631 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2633 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2634 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2635 lightmapoffset = -1;
2637 //surface->flags = surface->texture->flags;
2638 //if (LittleShort(in->side))
2639 // surface->flags |= SURF_PLANEBACK;
2640 //surface->plane = loadmodel->brush.data_planes + planenum;
2642 surface->num_firstvertex = totalverts;
2643 surface->num_vertices = numedges;
2644 surface->num_firsttriangle = totaltris;
2645 surface->num_triangles = numedges - 2;
2646 totalverts += numedges;
2647 totaltris += numedges - 2;
2649 // convert edges back to a normal polygon
2650 for (i = 0;i < surface->num_vertices;i++)
2652 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2654 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2656 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2658 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2659 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2660 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2661 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2662 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2663 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2664 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2665 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2668 for (i = 0;i < surface->num_triangles;i++)
2670 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2671 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2672 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2675 // compile additional data about the surface geometry
2676 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);
2677 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);
2678 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2680 // generate surface extents information
2681 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2682 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2683 for (i = 1;i < surface->num_vertices;i++)
2685 for (j = 0;j < 2;j++)
2687 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2688 texmins[j] = min(texmins[j], val);
2689 texmaxs[j] = max(texmaxs[j], val);
2692 for (i = 0;i < 2;i++)
2694 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2695 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2698 smax = surface->lightmapinfo->extents[0] >> 4;
2699 tmax = surface->lightmapinfo->extents[1] >> 4;
2700 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2701 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2704 surface->lightmaptexture = NULL;
2705 surface->deluxemaptexture = r_texture_blanknormalmap;
2706 if (lightmapoffset == -1)
2708 surface->lightmapinfo->samples = NULL;
2710 // give non-lightmapped water a 1x white lightmap
2711 if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2713 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2714 surface->lightmapinfo->styles[0] = 0;
2715 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2719 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LadyHavoc: HalfLife map (bsp version 30)
2720 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2721 else // LadyHavoc: white lighting (bsp version 29)
2723 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2724 if (loadmodel->brushq1.nmaplightdata)
2725 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2728 // check if we should apply a lightmap to this
2729 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2731 if (ssize > 256 || tsize > 256)
2732 Host_Error("Bad surface extents");
2734 if (lightmapsize < ssize)
2735 lightmapsize = ssize;
2736 if (lightmapsize < tsize)
2737 lightmapsize = tsize;
2739 totallightmapsamples += ssize*tsize;
2741 // force lightmap upload on first time seeing the surface
2743 // additionally this is used by the later code to see if a
2744 // lightmap is needed on this surface (rather than duplicating the
2746 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2747 loadmodel->lit = true;
2751 // small maps (such as ammo boxes especially) don't need big lightmap
2752 // textures, so this code tries to guess a good size based on
2753 // totallightmapsamples (size of the lightmaps lump basically), as well as
2754 // trying to max out the size if there is a lot of lightmap data to store
2755 // additionally, never choose a lightmapsize that is smaller than the
2756 // largest surface encountered (as it would fail)
2758 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2761 // now that we've decided the lightmap texture size, we can do the rest
2762 if (cls.state != ca_dedicated)
2764 int stainmapsize = 0;
2765 mod_alloclightmap_state_t allocState;
2767 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2768 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2770 int iu, iv, lightmapx = 0, lightmapy = 0;
2771 float u, v, ubase, vbase, uscale, vscale;
2773 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2776 smax = surface->lightmapinfo->extents[0] >> 4;
2777 tmax = surface->lightmapinfo->extents[1] >> 4;
2778 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2779 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2780 stainmapsize += ssize * tsize * 3;
2782 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2784 // allocate a texture pool if we need it
2785 if (loadmodel->texturepool == NULL)
2786 loadmodel->texturepool = R_AllocTexturePool();
2787 // could not find room, make a new lightmap
2788 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2789 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2790 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2791 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);
2792 if (loadmodel->brushq1.nmaplightdata)
2793 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);
2795 Mod_AllocLightmap_Reset(&allocState);
2796 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2798 surface->lightmaptexture = lightmaptexture;
2799 surface->deluxemaptexture = deluxemaptexture;
2800 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2801 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2803 uscale = 1.0f / (float)lightmapsize;
2804 vscale = 1.0f / (float)lightmapsize;
2805 ubase = lightmapx * uscale;
2806 vbase = lightmapy * vscale;
2808 for (i = 0;i < surface->num_vertices;i++)
2810 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);
2811 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);
2812 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2813 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2814 // LadyHavoc: calc lightmap data offset for vertex lighting to use
2817 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2821 if (cl_stainmaps.integer)
2823 // allocate stainmaps for permanent marks on walls and clear white
2824 unsigned char *stainsamples = NULL;
2825 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2826 memset(stainsamples, 255, stainmapsize);
2828 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2830 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2832 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2833 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2834 surface->lightmapinfo->stainsamples = stainsamples;
2835 stainsamples += ssize * tsize * 3;
2840 // generate ushort elements array if possible
2841 if (loadmodel->surfmesh.data_element3s)
2842 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2843 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2846 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2849 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2850 node->parent = parent;
2853 // this is a node, recurse to children
2854 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2855 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2856 // combine supercontents of children
2857 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2862 mleaf_t *leaf = (mleaf_t *)node;
2863 // if this is a leaf, calculate supercontents mask from all collidable
2864 // primitives in the leaf (brushes and collision surfaces)
2865 // also flag if the leaf contains any collision surfaces
2866 leaf->combinedsupercontents = 0;
2867 // combine the supercontents values of all brushes in this leaf
2868 for (j = 0;j < leaf->numleafbrushes;j++)
2869 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2870 // check if this leaf contains any collision surfaces (q3 patches)
2871 for (j = 0;j < leaf->numleafsurfaces;j++)
2873 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2874 if (surface->num_collisiontriangles)
2876 leaf->containscollisionsurfaces = true;
2877 leaf->combinedsupercontents |= surface->texture->supercontents;
2883 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2885 int i, j, count, p, child[2];
2887 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2889 if (sb->cursize % structsize)
2890 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2891 count = sb->cursize / structsize;
2893 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2894 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2896 loadmodel->brush.data_nodes = out;
2897 loadmodel->brush.num_nodes = count;
2899 for ( i=0 ; i<count ; i++, out++)
2901 p = MSG_ReadLittleLong(sb);
2902 out->plane = loadmodel->brush.data_planes + p;
2904 if (loadmodel->brush.isbsp2rmqe)
2906 child[0] = MSG_ReadLittleLong(sb);
2907 child[1] = MSG_ReadLittleLong(sb);
2908 out->mins[0] = MSG_ReadLittleShort(sb);
2909 out->mins[1] = MSG_ReadLittleShort(sb);
2910 out->mins[2] = MSG_ReadLittleShort(sb);
2911 out->maxs[0] = MSG_ReadLittleShort(sb);
2912 out->maxs[1] = MSG_ReadLittleShort(sb);
2913 out->maxs[2] = MSG_ReadLittleShort(sb);
2914 out->firstsurface = MSG_ReadLittleLong(sb);
2915 out->numsurfaces = MSG_ReadLittleLong(sb);
2917 else if (loadmodel->brush.isbsp2)
2919 child[0] = MSG_ReadLittleLong(sb);
2920 child[1] = MSG_ReadLittleLong(sb);
2921 out->mins[0] = MSG_ReadLittleFloat(sb);
2922 out->mins[1] = MSG_ReadLittleFloat(sb);
2923 out->mins[2] = MSG_ReadLittleFloat(sb);
2924 out->maxs[0] = MSG_ReadLittleFloat(sb);
2925 out->maxs[1] = MSG_ReadLittleFloat(sb);
2926 out->maxs[2] = MSG_ReadLittleFloat(sb);
2927 out->firstsurface = MSG_ReadLittleLong(sb);
2928 out->numsurfaces = MSG_ReadLittleLong(sb);
2932 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2933 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2934 if (child[0] >= count)
2936 if (child[1] >= count)
2939 out->mins[0] = MSG_ReadLittleShort(sb);
2940 out->mins[1] = MSG_ReadLittleShort(sb);
2941 out->mins[2] = MSG_ReadLittleShort(sb);
2942 out->maxs[0] = MSG_ReadLittleShort(sb);
2943 out->maxs[1] = MSG_ReadLittleShort(sb);
2944 out->maxs[2] = MSG_ReadLittleShort(sb);
2946 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2947 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2950 for (j=0 ; j<2 ; j++)
2952 // LadyHavoc: this code supports broken bsp files produced by
2953 // arguire qbsp which can produce more than 32768 nodes, any value
2954 // below count is assumed to be a node number, any other value is
2955 // assumed to be a leaf number
2959 if (p < loadmodel->brush.num_nodes)
2960 out->children[j] = loadmodel->brush.data_nodes + p;
2963 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2964 // map it to the solid leaf
2965 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2970 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2972 if (p < loadmodel->brush.num_leafs)
2973 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2976 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2977 // map it to the solid leaf
2978 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2984 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2987 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2990 int i, j, count, p, firstmarksurface, nummarksurfaces;
2991 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2993 if (sb->cursize % structsize)
2994 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2995 count = sb->cursize / structsize;
2996 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2998 loadmodel->brush.data_leafs = out;
2999 loadmodel->brush.num_leafs = count;
3000 // get visleafs from the submodel data
3001 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
3002 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
3003 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
3004 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
3006 // FIXME: this function could really benefit from some error checking
3007 for ( i=0 ; i<count ; i++, out++)
3009 out->contents = MSG_ReadLittleLong(sb);
3011 out->clusterindex = i - 1;
3012 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
3013 out->clusterindex = -1;
3015 p = MSG_ReadLittleLong(sb);
3016 // ignore visofs errors on leaf 0 (solid)
3017 if (p >= 0 && out->clusterindex >= 0)
3019 if (p >= loadmodel->brushq1.num_compressedpvs)
3020 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
3022 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);
3025 if (loadmodel->brush.isbsp2rmqe)
3027 out->mins[0] = MSG_ReadLittleShort(sb);
3028 out->mins[1] = MSG_ReadLittleShort(sb);
3029 out->mins[2] = MSG_ReadLittleShort(sb);
3030 out->maxs[0] = MSG_ReadLittleShort(sb);
3031 out->maxs[1] = MSG_ReadLittleShort(sb);
3032 out->maxs[2] = MSG_ReadLittleShort(sb);
3034 firstmarksurface = MSG_ReadLittleLong(sb);
3035 nummarksurfaces = MSG_ReadLittleLong(sb);
3037 else if (loadmodel->brush.isbsp2)
3039 out->mins[0] = MSG_ReadLittleFloat(sb);
3040 out->mins[1] = MSG_ReadLittleFloat(sb);
3041 out->mins[2] = MSG_ReadLittleFloat(sb);
3042 out->maxs[0] = MSG_ReadLittleFloat(sb);
3043 out->maxs[1] = MSG_ReadLittleFloat(sb);
3044 out->maxs[2] = MSG_ReadLittleFloat(sb);
3046 firstmarksurface = MSG_ReadLittleLong(sb);
3047 nummarksurfaces = MSG_ReadLittleLong(sb);
3051 out->mins[0] = MSG_ReadLittleShort(sb);
3052 out->mins[1] = MSG_ReadLittleShort(sb);
3053 out->mins[2] = MSG_ReadLittleShort(sb);
3054 out->maxs[0] = MSG_ReadLittleShort(sb);
3055 out->maxs[1] = MSG_ReadLittleShort(sb);
3056 out->maxs[2] = MSG_ReadLittleShort(sb);
3058 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
3059 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
3062 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
3064 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
3065 out->numleafsurfaces = nummarksurfaces;
3069 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
3070 out->firstleafsurface = NULL;
3071 out->numleafsurfaces = 0;
3074 for (j = 0;j < 4;j++)
3075 out->ambient_sound_level[j] = MSG_ReadByte(sb);
3079 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
3083 const unsigned char *pvs;
3084 // if there's no vis data, assume supported (because everything is visible all the time)
3085 if (!loadmodel->brush.data_pvsclusters)
3087 // check all liquid leafs to see if they can see into empty leafs, if any
3088 // can we can assume this map supports r_wateralpha
3089 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3091 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3093 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3094 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3095 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3102 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3107 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3109 if (sb->cursize % structsize)
3110 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3111 count = sb->cursize / structsize;
3112 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3114 loadmodel->brushq1.clipnodes = out;
3115 loadmodel->brushq1.numclipnodes = count;
3117 for (i = 1; i < MAX_MAP_HULLS; i++)
3119 hull = &loadmodel->brushq1.hulls[i];
3120 hull->clipnodes = out;
3121 hull->firstclipnode = 0;
3122 hull->lastclipnode = count-1;
3123 hull->planes = loadmodel->brush.data_planes;
3124 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3125 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3126 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3127 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3128 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3129 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3130 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3133 for (i=0 ; i<count ; i++, out++)
3135 out->planenum = MSG_ReadLittleLong(sb);
3136 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3137 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3138 if (loadmodel->brush.isbsp2)
3140 out->children[0] = MSG_ReadLittleLong(sb);
3141 out->children[1] = MSG_ReadLittleLong(sb);
3142 if (out->children[0] >= count)
3143 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3144 if (out->children[1] >= count)
3145 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3149 // LadyHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3150 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3151 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3152 if (out->children[0] >= count)
3153 out->children[0] -= 65536;
3154 if (out->children[1] >= count)
3155 out->children[1] -= 65536;
3160 //Duplicate the drawing hull structure as a clipping hull
3161 static void Mod_Q1BSP_MakeHull0(void)
3168 hull = &loadmodel->brushq1.hulls[0];
3170 in = loadmodel->brush.data_nodes;
3171 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3173 hull->clipnodes = out;
3174 hull->firstclipnode = 0;
3175 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3176 hull->planes = loadmodel->brush.data_planes;
3178 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3180 out->planenum = in->plane - loadmodel->brush.data_planes;
3181 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3182 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3186 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3189 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3191 if (sb->cursize % structsize)
3192 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3193 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3194 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3196 if (loadmodel->brush.isbsp2)
3198 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3200 j = MSG_ReadLittleLong(sb);
3201 if (j < 0 || j >= loadmodel->num_surfaces)
3202 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3203 loadmodel->brush.data_leafsurfaces[i] = j;
3208 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3210 j = (unsigned short) MSG_ReadLittleShort(sb);
3211 if (j >= loadmodel->num_surfaces)
3212 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3213 loadmodel->brush.data_leafsurfaces[i] = j;
3218 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3223 if (sb->cursize % structsize)
3224 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3225 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3226 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3228 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3229 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3233 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3237 int structsize = 20;
3239 if (sb->cursize % structsize)
3240 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3241 loadmodel->brush.num_planes = sb->cursize / structsize;
3242 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3244 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3246 out->normal[0] = MSG_ReadLittleFloat(sb);
3247 out->normal[1] = MSG_ReadLittleFloat(sb);
3248 out->normal[2] = MSG_ReadLittleFloat(sb);
3249 out->dist = MSG_ReadLittleFloat(sb);
3250 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3255 // fixes up sky surfaces that have SKY contents behind them, so that they do not cast shadows (e1m5 logo shadow trick).
3256 static void Mod_Q1BSP_AssignNoShadowSkySurfaces(dp_model_t *mod)
3259 msurface_t *surface;
3262 for (i = 0, surface = mod->data_surfaces + mod->firstmodelsurface; i < mod->nummodelsurfaces; i++, surface++)
3264 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3266 // check if the point behind the surface polygon is SOLID or SKY contents
3267 VectorMAMAM(0.5f, surface->mins, 0.5f, surface->maxs, -0.25f, mod->surfmesh.data_normal3f + 3*surface->num_firstvertex, center);
3268 contents = Mod_Q1BSP_PointSuperContents(mod, 0, center);
3269 if (!(contents & SUPERCONTENTS_SOLID))
3270 surface->texture = surface->texture->skynoshadowtexture;
3275 static void Mod_Q1BSP_LoadMapBrushes(void)
3279 int submodel, numbrushes;
3280 qboolean firstbrush;
3281 char *text, *maptext;
3282 char mapfilename[MAX_QPATH];
3283 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3284 strlcat (mapfilename, ".map", sizeof (mapfilename));
3285 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3289 if (!COM_ParseToken_Simple(&data, false, false, true))
3294 if (!COM_ParseToken_Simple(&data, false, false, true))
3296 if (com_token[0] != '{')
3302 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3305 if (!COM_ParseToken_Simple(&data, false, false, true))
3307 if (com_token[0] == '}')
3308 break; // end of entity
3309 if (com_token[0] == '{')
3316 if (submodel > loadmodel->brush.numsubmodels)
3318 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3322 model = loadmodel->brush.submodels[submodel];
3329 if (!COM_ParseToken_Simple(&data, false, false, true))
3331 if (com_token[0] == '}')
3332 break; // end of brush
3333 // each brush face should be this format:
3334 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3335 // FIXME: support hl .map format
3336 for (pointnum = 0;pointnum < 3;pointnum++)
3338 COM_ParseToken_Simple(&data, false, false, true);
3339 for (componentnum = 0;componentnum < 3;componentnum++)
3341 COM_ParseToken_Simple(&data, false, false, true);
3342 point[pointnum][componentnum] = atof(com_token);
3344 COM_ParseToken_Simple(&data, false, false, true);
3346 COM_ParseToken_Simple(&data, false, false, true);
3347 strlcpy(facetexture, com_token, sizeof(facetexture));
3348 COM_ParseToken_Simple(&data, false, false, true);
3349 //scroll_s = atof(com_token);
3350 COM_ParseToken_Simple(&data, false, false, true);
3351 //scroll_t = atof(com_token);
3352 COM_ParseToken_Simple(&data, false, false, true);
3353 //rotate = atof(com_token);
3354 COM_ParseToken_Simple(&data, false, false, true);
3355 //scale_s = atof(com_token);
3356 COM_ParseToken_Simple(&data, false, false, true);
3357 //scale_t = atof(com_token);
3358 TriangleNormal(point[0], point[1], point[2], planenormal);
3359 VectorNormalizeDouble(planenormal);
3360 planedist = DotProduct(point[0], planenormal);
3361 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3371 #define MAX_PORTALPOINTS 64
3373 typedef struct portal_s
3376 mnode_t *nodes[2]; // [0] = front side of plane
3377 struct portal_s *next[2];
3379 double points[3*MAX_PORTALPOINTS];
3380 struct portal_s *chain; // all portals are linked into a list
3384 static memexpandablearray_t portalarray;
3386 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3388 // process only nodes (leafs already had their box calculated)
3392 // calculate children first
3393 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3394 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3396 // make combined bounding box from children
3397 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3398 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3399 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3400 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3401 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3402 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3405 static void Mod_Q1BSP_FinalizePortals(void)
3407 int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3411 mleaf_t *leaf, *endleaf;
3413 // tally up portal and point counts and recalculate bounding boxes for all
3414 // leafs (because qbsp is very sloppy)
3415 leaf = loadmodel->brush.data_leafs;
3416 endleaf = leaf + loadmodel->brush.num_leafs;
3417 if (mod_recalculatenodeboxes.integer)
3419 for (;leaf < endleaf;leaf++)
3421 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3422 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3427 for (portalindex = 0;portalindex < portalrange;portalindex++)
3429 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3432 // note: this check must match the one below or it will usually corrupt memory
3433 // 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
3434 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3437 numpoints += p->numpoints * 2;
3440 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3441 loadmodel->brush.num_portals = numportals;
3442 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3443 loadmodel->brush.num_portalpoints = numpoints;
3444 // clear all leaf portal chains
3445 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3446 loadmodel->brush.data_leafs[i].portals = NULL;
3447 // process all portals in the global portal chain, while freeing them
3448 portal = loadmodel->brush.data_portals;
3449 point = loadmodel->brush.data_portalpoints;
3450 for (portalindex = 0;portalindex < portalrange;portalindex++)
3452 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3455 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3457 // note: this check must match the one above or it will usually corrupt memory
3458 // 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
3459 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3461 // first make the back to front portal(forward portal)
3462 portal->points = point;
3463 portal->numpoints = p->numpoints;
3464 portal->plane.dist = p->plane.dist;
3465 VectorCopy(p->plane.normal, portal->plane.normal);
3466 portal->here = (mleaf_t *)p->nodes[1];
3467 portal->past = (mleaf_t *)p->nodes[0];
3469 for (j = 0;j < portal->numpoints;j++)
3471 VectorCopy(p->points + j*3, point->position);
3474 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3475 PlaneClassify(&portal->plane);
3477 // link into leaf's portal chain
3478 portal->next = portal->here->portals;
3479 portal->here->portals = portal;
3481 // advance to next portal
3484 // then make the front to back portal(backward portal)
3485 portal->points = point;
3486 portal->numpoints = p->numpoints;
3487 portal->plane.dist = -p->plane.dist;
3488 VectorNegate(p->plane.normal, portal->plane.normal);
3489 portal->here = (mleaf_t *)p->nodes[0];
3490 portal->past = (mleaf_t *)p->nodes[1];
3492 for (j = portal->numpoints - 1;j >= 0;j--)
3494 VectorCopy(p->points + j*3, point->position);
3497 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3498 PlaneClassify(&portal->plane);
3500 // link into leaf's portal chain
3501 portal->next = portal->here->portals;
3502 portal->here->portals = portal;
3504 // advance to next portal
3507 // add the portal's polygon points to the leaf bounding boxes
3508 if (mod_recalculatenodeboxes.integer)
3510 for (i = 0;i < 2;i++)
3512 leaf = (mleaf_t *)p->nodes[i];
3513 for (j = 0;j < p->numpoints;j++)
3515 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3516 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3517 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3518 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3519 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3520 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3526 // now recalculate the node bounding boxes from the leafs
3527 if (mod_recalculatenodeboxes.integer)
3528 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3536 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3539 Host_Error("AddPortalToNodes: NULL front node");
3541 Host_Error("AddPortalToNodes: NULL back node");
3542 if (p->nodes[0] || p->nodes[1])
3543 Host_Error("AddPortalToNodes: already included");
3544 // 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
3546 p->nodes[0] = front;
3547 p->next[0] = (portal_t *)front->portals;
3548 front->portals = (mportal_t *)p;
3551 p->next[1] = (portal_t *)back->portals;
3552 back->portals = (mportal_t *)p;
3557 RemovePortalFromNode
3560 static void RemovePortalFromNodes(portal_t *portal)
3564 void **portalpointer;
3566 for (i = 0;i < 2;i++)
3568 node = portal->nodes[i];
3570 portalpointer = (void **) &node->portals;
3573 t = (portal_t *)*portalpointer;
3575 Host_Error("RemovePortalFromNodes: portal not in leaf");
3579 if (portal->nodes[0] == node)
3581 *portalpointer = portal->next[0];
3582 portal->nodes[0] = NULL;
3584 else if (portal->nodes[1] == node)
3586 *portalpointer = portal->next[1];
3587 portal->nodes[1] = NULL;
3590 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3594 if (t->nodes[0] == node)
3595 portalpointer = (void **) &t->next[0];
3596 else if (t->nodes[1] == node)
3597 portalpointer = (void **) &t->next[1];
3599 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3604 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3605 static double *portalpointsbuffer;
3606 static int portalpointsbufferoffset;
3607 static int portalpointsbuffersize;
3608 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3611 mnode_t *front, *back, *other_node;
3612 mplane_t clipplane, *plane;
3613 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3614 int numfrontpoints, numbackpoints;
3615 double *frontpoints, *backpoints;
3617 // if a leaf, we're done
3621 // get some space for our clipping operations to use
3622 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3624 portalpointsbuffersize = portalpointsbufferoffset * 2;
3625 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3627 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3628 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3629 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3630 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3632 plane = node->plane;
3634 front = node->children[0];
3635 back = node->children[1];
3637 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3639 // create the new portal by generating a polygon for the node plane,
3640 // and clipping it by all of the other portals(which came from nodes above this one)
3641 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3642 nodeportal->plane = *plane;
3644 // 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)
3645 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);
3646 nodeportal->numpoints = 4;
3647 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3648 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3650 clipplane = portal->plane;
3651 if (portal->nodes[0] == portal->nodes[1])
3652 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3653 if (portal->nodes[0] == node)
3655 else if (portal->nodes[1] == node)
3657 clipplane.dist = -clipplane.dist;
3658 VectorNegate(clipplane.normal, clipplane.normal);
3663 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3664 side = 0; // hush warning
3667 for (i = 0;i < nodeportal->numpoints*3;i++)
3668 frontpoints[i] = nodeportal->points[i];
3669 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);
3670 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3674 if (nodeportal->numpoints < 3)
3676 Con_Warn("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3677 nodeportal->numpoints = 0;
3679 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3681 Con_Warn("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3682 nodeportal->numpoints = 0;
3685 AddPortalToNodes(nodeportal, front, back);
3687 // split the portals of this node along this node's plane and assign them to the children of this node
3688 // (migrating the portals downward through the tree)
3689 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3691 if (portal->nodes[0] == portal->nodes[1])
3692 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3693 if (portal->nodes[0] == node)
3695 else if (portal->nodes[1] == node)
3699 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3700 side = 0; // hush warning
3702 nextportal = portal->next[side];
3703 if (!portal->numpoints)
3706 other_node = portal->nodes[!side];
3707 RemovePortalFromNodes(portal);
3709 // cut the portal into two portals, one on each side of the node plane
3710 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);
3712 if (!numfrontpoints)
3715 AddPortalToNodes(portal, back, other_node);
3717 AddPortalToNodes(portal, other_node, back);
3723 AddPortalToNodes(portal, front, other_node);
3725 AddPortalToNodes(portal, other_node, front);
3729 // the portal is split
3730 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3731 temp = splitportal->chain;
3732 *splitportal = *portal;
3733 splitportal->chain = temp;
3734 for (i = 0;i < numbackpoints*3;i++)
3735 splitportal->points[i] = backpoints[i];
3736 splitportal->numpoints = numbackpoints;
3737 for (i = 0;i < numfrontpoints*3;i++)
3738 portal->points[i] = frontpoints[i];
3739 portal->numpoints = numfrontpoints;
3743 AddPortalToNodes(portal, front, other_node);
3744 AddPortalToNodes(splitportal, back, other_node);
3748 AddPortalToNodes(portal, other_node, front);
3749 AddPortalToNodes(splitportal, other_node, back);
3753 Mod_Q1BSP_RecursiveNodePortals(front);
3754 Mod_Q1BSP_RecursiveNodePortals(back);
3756 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3759 static void Mod_Q1BSP_MakePortals(void)
3761 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3762 portalpointsbufferoffset = 0;
3763 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3764 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3765 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3766 Mem_Free(portalpointsbuffer);
3767 portalpointsbuffer = NULL;
3768 portalpointsbufferoffset = 0;
3769 portalpointsbuffersize = 0;
3770 Mod_Q1BSP_FinalizePortals();
3771 Mem_ExpandableArray_FreeArray(&portalarray);
3774 //Returns PVS data for a given point
3775 //(note: can return NULL)
3776 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3779 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3781 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3782 if (((mleaf_t *)node)->clusterindex >= 0)
3783 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3788 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)
3792 float d = PlaneDiff(org, node->plane);
3794 node = node->children[0];
3795 else if (d < -radius)
3796 node = node->children[1];
3799 // go down both sides
3800 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3801 node = node->children[1];
3804 // if this leaf is in a cluster, accumulate the pvs bits
3805 if (((mleaf_t *)node)->clusterindex >= 0)
3808 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3809 for (i = 0;i < pvsbytes;i++)
3810 pvsbuffer[i] |= pvs[i];
3814 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3815 //of the given point.
3816 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3818 int bytes = model->brush.num_pvsclusterbytes;
3819 bytes = min(bytes, pvsbufferlength);
3820 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3822 memset(pvsbuffer, 0xFF, bytes);
3826 memset(pvsbuffer, 0, bytes);
3827 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3831 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3836 VectorSubtract(inmaxs, inmins, size);
3837 if (cmodel->brush.ishlbsp)
3840 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3841 else if (size[0] <= 32)
3843 if (size[2] < 54) // pick the nearest of 36 or 72
3844 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3846 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3849 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3854 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3855 else if (size[0] <= 32)
3856 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3858 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3860 VectorCopy(inmins, outmins);
3861 VectorAdd(inmins, hull->clip_size, outmaxs);
3864 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);
3866 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3869 sizebuf_t lumpsb[HEADER_LUMPS];
3871 float dist, modelyawradius, modelradius;
3872 msurface_t *surface;
3873 hullinfo_t hullinfo;
3874 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3875 model_brush_lightstyleinfo_t styleinfo[256];
3876 unsigned char *datapointer;
3879 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3881 mod->type = mod_brushq1;
3883 mod->brush.ishlbsp = false;
3884 mod->brush.isbsp2rmqe = false;
3885 mod->brush.isbsp2 = false;
3886 mod->brush.isq2bsp = false;
3887 mod->brush.isq3bsp = false;
3888 mod->brush.skymasking = true;
3889 i = MSG_ReadLittleLong(&sb);
3893 mod->modeldatatypestring = "Q1BSP";
3896 mod->brush.ishlbsp = true;
3897 mod->modeldatatypestring = "HLBSP";
3899 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3900 mod->brush.isbsp2 = true;
3901 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3902 mod->modeldatatypestring = "Q1BSP2rmqe";
3904 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3905 mod->brush.isbsp2 = true;
3906 mod->modeldatatypestring = "Q1BSP2";
3909 mod->modeldatatypestring = "Unknown BSP";
3910 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);
3914 // fill in hull info
3915 VectorClear (hullinfo.hullsizes[0][0]);
3916 VectorClear (hullinfo.hullsizes[0][1]);
3917 if (mod->brush.ishlbsp)
3919 hullinfo.filehulls = 4;
3920 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3921 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3922 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3923 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3924 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3925 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3929 hullinfo.filehulls = 4;
3930 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3931 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3932 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3933 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3937 for (i = 0; i < HEADER_LUMPS; i++)
3939 int offset = MSG_ReadLittleLong(&sb);
3940 int size = MSG_ReadLittleLong(&sb);
3941 if (offset < 0 || offset + size > sb.cursize)
3942 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);
3943 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3946 mod->soundfromcenter = true;
3947 mod->TraceBox = Mod_Q1BSP_TraceBox;
3948 mod->TraceLine = Mod_Q1BSP_TraceLine;
3949 mod->TracePoint = Mod_Q1BSP_TracePoint;
3950 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3951 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3952 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3953 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3954 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3955 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3956 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3957 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3958 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3959 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3960 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3961 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3962 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3963 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3964 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3965 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3966 mod->Draw = R_Q1BSP_Draw;
3967 mod->DrawDepth = R_Q1BSP_DrawDepth;
3968 mod->DrawDebug = R_Q1BSP_DrawDebug;
3969 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3970 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3971 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3972 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3973 mod->DrawLight = R_Q1BSP_DrawLight;
3977 mod->brush.qw_md4sum = 0;
3978 mod->brush.qw_md4sum2 = 0;
3979 for (i = 0;i < HEADER_LUMPS;i++)
3982 if (i == LUMP_ENTITIES)
3984 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3985 mod->brush.qw_md4sum ^= LittleLong(temp);
3986 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3988 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3991 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3992 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3993 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3994 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3995 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3996 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3997 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3998 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3999 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
4000 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
4001 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
4002 // load submodels before leafs because they contain the number of vis leafs
4003 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
4004 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
4005 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
4006 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
4008 for (i = 0; i < HEADER_LUMPS; i++)
4009 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
4010 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4012 // check if the map supports transparent water rendering
4013 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
4015 // we don't need the compressed pvs data anymore
4016 if (mod->brushq1.data_compressedpvs)
4017 Mem_Free(mod->brushq1.data_compressedpvs);
4018 mod->brushq1.data_compressedpvs = NULL;
4019 mod->brushq1.num_compressedpvs = 0;
4021 Mod_Q1BSP_MakeHull0();
4022 if (mod_bsp_portalize.integer)
4023 Mod_Q1BSP_MakePortals();
4025 mod->numframes = 2; // regular and alternate animation
4028 if (loadmodel->brush.numsubmodels)
4029 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
4031 // LadyHavoc: to clear the fog around the original quake submodel code, I
4033 // first of all, some background info on the submodels:
4034 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
4035 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
4036 // now the weird for loop itself:
4037 // the loop functions in an odd way, on each iteration it sets up the
4038 // current 'mod' model (which despite the confusing code IS the model of
4039 // the number i), at the end of the loop it duplicates the model to become
4040 // the next submodel, and loops back to set up the new submodel.
4042 // LadyHavoc: now the explanation of my sane way (which works identically):
4043 // set up the world model, then on each submodel copy from the world model
4044 // and set up the submodel with the respective model info.
4045 totalstylesurfaces = 0;
4047 for (i = 0;i < mod->brush.numsubmodels;i++)
4049 memset(stylecounts, 0, sizeof(stylecounts));
4050 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4052 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4053 for (j = 0;j < MAXLIGHTMAPS;j++)
4054 stylecounts[surface->lightmapinfo->styles[j]]++;
4056 for (k = 0;k < 255;k++)
4060 totalstylesurfaces += stylecounts[k];
4063 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4064 for (i = 0;i < mod->brush.numsubmodels;i++)
4066 // LadyHavoc: this code was originally at the end of this loop, but
4067 // has been transformed to something more readable at the start here.
4072 // duplicate the basic information
4073 dpsnprintf(name, sizeof(name), "*%i", i);
4074 mod = Mod_FindName(name, loadmodel->name);
4075 // copy the base model to this one
4077 // rename the clone back to its proper name
4078 strlcpy(mod->name, name, sizeof(mod->name));
4079 mod->brush.parentmodel = loadmodel;
4080 // textures and memory belong to the main model
4081 mod->texturepool = NULL;
4082 mod->mempool = NULL;
4083 mod->brush.GetPVS = NULL;
4084 mod->brush.FatPVS = NULL;
4085 mod->brush.BoxTouchingPVS = NULL;
4086 mod->brush.BoxTouchingLeafPVS = NULL;
4087 mod->brush.BoxTouchingVisibleLeafs = NULL;
4088 mod->brush.FindBoxClusters = NULL;
4089 mod->brush.LightPoint = NULL;
4090 mod->brush.AmbientSoundLevelsForPoint = NULL;
4093 mod->brush.submodel = i;
4095 if (loadmodel->brush.submodels)
4096 loadmodel->brush.submodels[i] = mod;
4098 bm = &mod->brushq1.submodels[i];
4100 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4101 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4103 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4104 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4107 mod->firstmodelsurface = bm->firstface;
4108 mod->nummodelsurfaces = bm->numfaces;
4110 // set node/leaf parents for this submodel
4111 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4113 // this has to occur after hull info has been set, as it uses Mod_Q1BSP_PointSuperContents
4114 Mod_Q1BSP_AssignNoShadowSkySurfaces(mod);
4116 // make the model surface list (used by shadowing/lighting)
4117 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4118 Mod_MakeSortedSurfaces(mod);
4120 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4121 // (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)
4122 VectorCopy(bm->mins, mod->normalmins);
4123 VectorCopy(bm->maxs, mod->normalmaxs);
4124 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4125 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4126 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4127 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4128 modelradius = modelyawradius + modelradius * modelradius;
4129 modelyawradius = sqrt(modelyawradius);
4130 modelradius = sqrt(modelradius);
4131 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4132 mod->yawmins[2] = mod->normalmins[2];
4133 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4134 mod->yawmaxs[2] = mod->normalmaxs[2];
4135 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4136 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4137 mod->radius = modelradius;
4138 mod->radius2 = modelradius * modelradius;
4140 // this gets altered below if sky or water is used
4141 mod->DrawSky = NULL;
4142 mod->DrawAddWaterPlanes = NULL;
4144 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4145 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4146 if (mod->nummodelsurfaces)
4148 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4149 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4151 if (j < mod->nummodelsurfaces)
4152 mod->DrawSky = R_Q1BSP_DrawSky;
4154 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4155 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4157 if (j < mod->nummodelsurfaces)
4158 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4160 // build lightstyle update chains
4161 // (used to rapidly mark lightmapupdateflags on many surfaces
4162 // when d_lightstylevalue changes)
4163 memset(stylecounts, 0, sizeof(stylecounts));
4164 for (k = 0;k < mod->nummodelsurfaces;k++)
4166 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4167 for (j = 0;j < MAXLIGHTMAPS;j++)
4168 stylecounts[surface->lightmapinfo->styles[j]]++;
4170 mod->brushq1.num_lightstyles = 0;
4171 for (k = 0;k < 255;k++)
4175 styleinfo[mod->brushq1.num_lightstyles].style = k;
4176 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4177 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4178 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4179 remapstyles[k] = mod->brushq1.num_lightstyles;
4180 mod->brushq1.num_lightstyles++;
4183 for (k = 0;k < mod->nummodelsurfaces;k++)
4185 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4186 for (j = 0;j < MAXLIGHTMAPS;j++)
4188 if (surface->lightmapinfo->styles[j] != 255)
4190 int r = remapstyles[surface->lightmapinfo->styles[j]];
4191 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4195 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4196 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4200 // LadyHavoc: empty submodel(lacrima.bsp has such a glitch)
4201 Con_Warnf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4203 //mod->brushq1.num_visleafs = bm->visleafs;
4205 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4206 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4208 if (mod_q1bsp_polygoncollisions.integer)
4210 mod->collision_bih = mod->render_bih;
4211 // point traces and contents checks still use the bsp tree
4212 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4213 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4214 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4215 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4218 // generate VBOs and other shared data before cloning submodels
4222 Mod_Q1BSP_LoadMapBrushes();
4223 //Mod_Q1BSP_ProcessLightList();
4227 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);
4230 int Mod_Q2BSP_SuperContentsFromNativeContents(int nativecontents)
4232 int supercontents = 0;
4233 if (nativecontents & CONTENTSQ2_SOLID)
4234 supercontents |= SUPERCONTENTS_SOLID;
4235 if (nativecontents & CONTENTSQ2_WATER)
4236 supercontents |= SUPERCONTENTS_WATER;
4237 if (nativecontents & CONTENTSQ2_SLIME)
4238 supercontents |= SUPERCONTENTS_SLIME;
4239 if (nativecontents & CONTENTSQ2_LAVA)
4240 supercontents |= SUPERCONTENTS_LAVA;
4241 if (nativecontents & CONTENTSQ2_MONSTER)
4242 supercontents |= SUPERCONTENTS_BODY;
4243 if (nativecontents & CONTENTSQ2_DEADMONSTER)
4244 supercontents |= SUPERCONTENTS_CORPSE;
4245 if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4246 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4247 if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4248 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4249 if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4250 supercontents |= SUPERCONTENTS_OPAQUE;
4251 return supercontents;
4254 int Mod_Q2BSP_NativeContentsFromSuperContents(int supercontents)
4256 int nativecontents = 0;
4257 if (supercontents & SUPERCONTENTS_SOLID)
4258 nativecontents |= CONTENTSQ2_SOLID;
4259 if (supercontents & SUPERCONTENTS_WATER)
4260 nativecontents |= CONTENTSQ2_WATER;
4261 if (supercontents & SUPERCONTENTS_SLIME)
4262 nativecontents |= CONTENTSQ2_SLIME;
4263 if (supercontents & SUPERCONTENTS_LAVA)
4264 nativecontents |= CONTENTSQ2_LAVA;
4265 if (supercontents & SUPERCONTENTS_BODY)
4266 nativecontents |= CONTENTSQ2_MONSTER;
4267 if (supercontents & SUPERCONTENTS_CORPSE)
4268 nativecontents |= CONTENTSQ2_DEADMONSTER;
4269 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4270 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4271 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4272 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4273 if (!(supercontents & SUPERCONTENTS_OPAQUE))
4274 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4275 return nativecontents;
4278 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4281 loadmodel->brushq1.num_compressedpvs = 0;
4282 loadmodel->brushq1.data_compressedpvs = NULL;
4283 loadmodel->brush.num_pvsclusters = 0;
4284 loadmodel->brush.num_pvsclusterbytes = 0;
4285 loadmodel->brush.data_pvsclusters = NULL;
4290 count = MSG_ReadLittleLong(sb);
4291 loadmodel->brush.num_pvsclusters = count;
4292 loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4293 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4294 for (i = 0;i < count;i++)
4296 int pvsofs = MSG_ReadLittleLong(sb);
4297 /*int phsofs = */MSG_ReadLittleLong(sb);
4298 // decompress the vis data for this cluster
4299 // (note this accesses the underlying data store of sb, which is kind of evil)
4300 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);
4302 // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4303 sb->readcount = sb->cursize;
4306 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4308 int i, j, count, p, child[2];
4310 int structsize = 28;
4312 if (sb->cursize % structsize)
4313 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4314 count = sb->cursize / structsize;
4316 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4317 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4319 loadmodel->brush.data_nodes = out;
4320 loadmodel->brush.num_nodes = count;
4322 for ( i=0 ; i<count ; i++, out++)
4324 p = MSG_ReadLittleLong(sb);
4325 out->plane = loadmodel->brush.data_planes + p;
4326 child[0] = MSG_ReadLittleLong(sb);
4327 child[1] = MSG_ReadLittleLong(sb);
4328 out->mins[0] = MSG_ReadLittleShort(sb);
4329 out->mins[1] = MSG_ReadLittleShort(sb);
4330 out->mins[2] = MSG_ReadLittleShort(sb);
4331 out->maxs[0] = MSG_ReadLittleShort(sb);
4332 out->maxs[1] = MSG_ReadLittleShort(sb);
4333 out->maxs[2] = MSG_ReadLittleShort(sb);
4334 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4335 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4336 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4338 Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4339 out->firstsurface = 0;
4340 out->numsurfaces = 0;
4342 for (j=0 ; j<2 ; j++)
4347 if (p < loadmodel->brush.num_nodes)
4348 out->children[j] = loadmodel->brush.data_nodes + p;
4351 Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4352 // map it to the solid leaf
4353 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4358 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4360 if (p < loadmodel->brush.num_leafs)
4361 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4364 Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4365 // map it to the solid leaf
4366 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4372 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
4375 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4379 int structsize = 76;
4380 int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4381 char filename[MAX_QPATH];
4383 if (sb->cursize % structsize)
4384 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4385 count = sb->cursize / structsize;
4386 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4387 loadmodel->brushq1.texinfo = out;
4388 loadmodel->brushq1.numtexinfo = count;
4389 loadmodel->num_texturesperskin = 0;
4390 loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4392 for (i = 0;i < count;i++, out++)
4395 for (k = 0;k < 2;k++)
4396 for (j = 0;j < 4;j++)
4397 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4399 out->q2flags = MSG_ReadLittleLong(sb);
4400 out->q2value = MSG_ReadLittleLong(sb);
4401 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4402 out->q2texture[31] = 0; // make absolutely sure it is terminated
4403 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4405 // find an existing match for the texture if possible
4406 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4407 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4408 if (!strcmp(filename, loadmodel->data_textures[j].name)
4409 && out->q2flags == loadmodel->data_textures[j].q2flags
4410 && out->q2value == loadmodel->data_textures[j].q2value)
4412 // if we don't find the texture, store the new texture
4413 if (j == loadmodel->num_texturesperskin)
4415 if (loadmodel->num_texturesperskin < maxtextures)
4417 texture_t *tx = loadmodel->data_textures + j;
4418 int q2flags = out->q2flags;
4419 unsigned char *walfile = NULL;
4420 fs_offset_t walfilesize = 0;
4421 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
4422 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4423 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4427 LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4437 tx->q2flags = out->q2flags;
4438 tx->q2value = out->q2value;
4439 // also modify the texture to have the correct contents and such based on flags
4440 // note that we create multiple texture_t structures if q2flags differs
4441 if (q2flags & Q2SURF_LIGHT)
4443 // doesn't mean anything to us
4445 if (q2flags & Q2SURF_SLICK)
4447 // would be nice to support...
4449 if (q2flags & Q2SURF_SKY)
4451 // sky is a rather specific thing
4452 q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4453 tx->basematerialflags = MATERIALFLAG_SKY;
4454 tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4455 tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4457 if (q2flags & Q2SURF_WARP)
4459 // we use a scroll instead of a warp
4460 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4461 // if it's also transparent, we can enable the WATERSHADER
4462 // but we do not set the WATERALPHA flag because we don't
4463 // want to honor r_wateralpha in q2bsp
4464 // (it would go against the artistic intent)
4465 if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4466 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4468 if (q2flags & Q2SURF_TRANS33)
4470 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4471 tx->basealpha = 1.0f / 3.0f;
4472 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4473 if (tx->q2contents & Q2CONTENTS_SOLID)
4474 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4476 if (q2flags & Q2SURF_TRANS66)
4478 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4479 tx->basealpha = 2.0f / 3.0f;
4480 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4481 if (tx->q2contents & Q2CONTENTS_SOLID)
4482 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4484 if ((q2flags & Q2SURF_FLOWING) && tx->materialshaderpass != NULL)
4486 tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4487 if (q2flags & Q2SURF_WARP)
4488 tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
4490 tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
4491 tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
4493 if (q2flags & Q2SURF_ALPHATEST)
4495 // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4496 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4498 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4500 if (!mod_q2bsp_littransparentsurfaces.integer)
4501 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4503 if (q2flags & Q2SURF_NODRAW)
4505 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4507 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4508 tx->q2contents |= Q2CONTENTS_DETAIL;
4509 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4510 tx->q2contents |= Q2CONTENTS_SOLID;
4511 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4513 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(tx->q2contents);
4514 // set the current values to the base values
4515 tx->currentframe = tx;
4516 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
4517 tx->currentmaterialflags = tx->basematerialflags;
4518 loadmodel->num_texturesperskin++;
4519 loadmodel->num_textures = loadmodel->num_texturesperskin;
4523 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4524 j = 0; // use first texture and give up
4527 // store the index we found for this texture
4528 out->textureindex = j;
4531 // realloc the textures array now that we know how many we actually need
4532 loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4534 // now assemble the texture chains
4535 // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier
4536 for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4539 texture_t *t = loadmodel->data_textures + out->textureindex;
4540 t->currentframe = t; // fix the reallocated pointer
4542 // if this is not animated, skip it
4543 // if this is already processed, skip it (part of an existing sequence)
4544 if (out->q2nexttexinfo == 0 || t->animated)
4547 // store the array of frames to use
4548 t->animated = 2; // q2bsp animation
4549 t->anim_total[0] = 0;
4550 t->anim_total[1] = 0;
4551 // gather up to 10 frames (we don't support more)
4552 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)
4554 // detect looping and stop there
4555 if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4557 t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4559 // we could look for the +a sequence here if this is the +0 sequence,
4560 // but it seems that quake2 did not implement that (even though the
4561 // files exist in the baseq2 content)
4563 // write the frame sequence to all the textures involved (just like
4564 // in the q1bsp loader)
4566 // note that this can overwrite the rest of the sequence - so if the
4567 // start of a sequence is found later than the other parts of the
4568 // sequence, it will go back and rewrite them correctly.
4569 for (k = 0;k < t->anim_total[0];k++)
4571 texture_t *txk = t->anim_frames[0][k];
4572 txk->animated = t->animated;
4573 txk->anim_total[0] = t->anim_total[0];
4574 for (l = 0;l < t->anim_total[0];l++)
4575 txk->anim_frames[0][l] = t->anim_frames[0][l];
4580 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4582 // LadyHavoc: this fits exactly the same format that we use in .lit files
4583 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4584 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4587 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4590 int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4591 int structsize = 28;
4593 if (sb->cursize % structsize)
4594 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4595 count = sb->cursize / structsize;
4596 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4598 loadmodel->brush.data_leafs = out;
4599 loadmodel->brush.num_leafs = count;
4601 // FIXME: this function could really benefit from some error checking
4602 for ( i=0 ; i<count ; i++, out++)
4604 out->contents = MSG_ReadLittleLong(sb);
4605 out->clusterindex = MSG_ReadLittleShort(sb);
4606 out->areaindex = MSG_ReadLittleShort(sb);
4607 out->mins[0] = MSG_ReadLittleShort(sb);
4608 out->mins[1] = MSG_ReadLittleShort(sb);
4609 out->mins[2] = MSG_ReadLittleShort(sb);
4610 out->maxs[0] = MSG_ReadLittleShort(sb);
4611 out->maxs[1] = MSG_ReadLittleShort(sb);
4612 out->maxs[2] = MSG_ReadLittleShort(sb);
4614 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4615 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4616 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4617 nummarkbrushes = (unsigned short)MSG_ReadLittleShort(sb);
4619 for (j = 0;j < 4;j++)
4620 out->ambient_sound_level[j] = 0;
4622 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4624 Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4625 out->clusterindex = -1;
4628 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4630 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4631 out->numleafsurfaces = nummarksurfaces;
4635 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4636 out->firstleafsurface = NULL;
4637 out->numleafsurfaces = 0;
4640 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4642 out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4643 out->numleafbrushes = nummarkbrushes;
4647 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4648 out->firstleafbrush = NULL;
4649 out->numleafbrushes = 0;
4654 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4659 if (sb->cursize % structsize)
4660 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4661 loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4662 loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4664 for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4666 j = (unsigned short) MSG_ReadLittleShort(sb);
4667 if (j >= loadmodel->brush.num_brushes)
4668 Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4669 loadmodel->brush.data_leafbrushes[i] = j;
4673 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4675 q3mbrushside_t *out;
4679 if (sb->cursize % structsize)
4680 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4681 count = sb->cursize / structsize;
4682 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4684 loadmodel->brush.data_brushsides = out;
4685 loadmodel->brush.num_brushsides = count;
4687 for (i = 0;i < count;i++, out++)
4689 n = (unsigned short)MSG_ReadLittleShort(sb);
4690 if (n < 0 || n >= loadmodel->brush.num_planes)
4691 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4692 out->plane = loadmodel->brush.data_planes + n;
4693 n = MSG_ReadLittleShort(sb);
4696 if (n >= loadmodel->brushq1.numtexinfo)
4697 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4698 out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4702 //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4703 out->texture = &mod_q1bsp_texture_solid;
4708 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4711 int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4712 colplanef_t *planes;
4713 int structsize = 12;
4714 qboolean brushmissingtextures;
4715 int numbrushesmissingtextures = 0;
4716 int numcreatedtextures = 0;
4718 if (sb->cursize % structsize)
4719 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4720 count = sb->cursize / structsize;
4721 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4723 loadmodel->brush.data_brushes = out;
4724 loadmodel->brush.num_brushes = count;
4729 for (i = 0; i < count; i++, out++)
4731 firstside = MSG_ReadLittleLong(sb);
4732 numsides = MSG_ReadLittleLong(sb);
4733 contents = MSG_ReadLittleLong(sb);
4734 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4735 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4737 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4738 out->numbrushsides = numsides;
4739 // convert the contents to our values
4740 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(contents);
4742 // problem: q2bsp brushes have contents but not a texture
4743 // problem: q2bsp brushsides *may* have a texture or may not
4744 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4745 // solution: nasty hacks
4746 brushmissingtextures = false;
4747 out->texture = NULL;
4748 for (j = 0; j < out->numbrushsides; j++)
4750 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4751 brushmissingtextures = true;
4754 // if we can find a matching texture on a brush side we can use it instead of creating one
4755 if (out->firstbrushside[j].texture->supercontents == supercontents)
4756 out->texture = out->firstbrushside[j].texture;
4759 if (brushmissingtextures || out->texture == NULL)
4761 numbrushesmissingtextures++;
4762 // if we didn't find any appropriate texture (matching contents), we'll have to create one
4763 // we could search earlier ones for a matching one but that can be slow
4764 if (out->texture == NULL)
4766 texture_t *validtexture;
4767 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4768 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4769 validtexture->surfaceflags = 0;
4770 validtexture->supercontents = supercontents;
4771 numcreatedtextures++;
4772 out->texture = validtexture;
4774 // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4775 for (j = 0; j < out->numbrushsides; j++)
4776 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4777 out->firstbrushside[j].texture = out->texture;
4780 // make a colbrush from the brush
4782 // make a list of mplane_t structs to construct a colbrush from
4783 if (maxplanes < out->numbrushsides)
4785 maxplanes = out->numbrushsides;
4788 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4790 for (j = 0;j < out->numbrushsides;j++)
4792 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4793 planes[j].dist = out->firstbrushside[j].plane->dist;
4794 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4795 planes[j].texture = out->firstbrushside[j].texture;
4796 q3surfaceflags |= planes[j].q3surfaceflags;
4798 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4800 // this whole loop can take a while (e.g. on redstarrepublic4)
4801 CL_KeepaliveMessage(false);
4805 if (numcreatedtextures)
4806 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);
4809 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4811 // 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)
4812 sb->readcount = sb->cursize;
4815 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4817 // we currently don't use areas, they represent closable doors as vis blockers
4818 sb->readcount = sb->cursize;
4821 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4823 // we currently don't use areas, they represent closable doors as vis blockers
4824 sb->readcount = sb->cursize;
4827 static void Mod_Q2BSP_LoadSubmodels(sizebuf_t *sb)
4831 int structsize = 48;
4833 if (sb->cursize % structsize)
4834 Host_Error ("Mod_Q2BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
4836 count = sb->cursize / structsize;
4837 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
4839 loadmodel->brushq1.submodels = out;
4840 loadmodel->brush.numsubmodels = count;
4842 // this is identical to the q1 submodel structure except for having 1 hull
4843 for (i = 0; i < count; i++, out++)
4845 // spread out the mins / maxs by a pixel
4846 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
4847 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
4848 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
4849 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
4850 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
4851 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
4852 out->origin[0] = MSG_ReadLittleFloat(sb);
4853 out->origin[1] = MSG_ReadLittleFloat(sb);
4854 out->origin[2] = MSG_ReadLittleFloat(sb);
4855 out->headnode[0] = MSG_ReadLittleLong(sb);
4856 out->firstface = MSG_ReadLittleLong(sb);
4857 out->numfaces = MSG_ReadLittleLong(sb);
4861 static void Mod_Q2BSP_FindSubmodelBrushRange_r(dp_model_t *mod, mnode_t *node, int *first, int *last)
4867 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4868 node = node->children[1];
4870 leaf = (mleaf_t*)node;
4871 for (i = 0;i < leaf->numleafbrushes;i++)
4873 int brushnum = leaf->firstleafbrush[i];
4874 if (*first > brushnum)
4876 if (*last < brushnum)
4881 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4884 sizebuf_t lumpsb[Q2HEADER_LUMPS];
4886 float dist, modelyawradius, modelradius;
4887 msurface_t *surface;
4888 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4889 model_brush_lightstyleinfo_t styleinfo[256];
4890 unsigned char *datapointer;
4893 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4895 mod->type = mod_brushq2;
4897 mod->brush.ishlbsp = false;
4898 mod->brush.isbsp2rmqe = false;
4899 mod->brush.isbsp2 = false;
4900 mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4901 mod->brush.isq3bsp = false;
4902 mod->brush.skymasking = true;
4903 mod->modeldatatypestring = "Q2BSP";
4905 i = MSG_ReadLittleLong(&sb);
4906 if (i != Q2BSPMAGIC)
4907 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4909 i = MSG_ReadLittleLong(&sb);
4910 if (i != Q2BSPVERSION)
4911 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4914 for (i = 0; i < Q2HEADER_LUMPS; i++)
4916 int offset = MSG_ReadLittleLong(&sb);
4917 int size = MSG_ReadLittleLong(&sb);
4918 if (offset < 0 || offset + size > sb.cursize)
4919 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);
4920 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4923 mod->soundfromcenter = true;
4924 mod->TracePoint = Mod_CollisionBIH_TracePoint;
4925 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4926 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4927 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4928 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4929 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4930 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4931 mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4932 mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4933 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
4934 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
4935 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
4936 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
4937 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
4938 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
4939 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
4940 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
4941 mod->brush.AmbientSoundLevelsForPoint = NULL;
4942 mod->brush.RoundUpToHullSize = NULL;
4943 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
4944 mod->Draw = R_Q1BSP_Draw;
4945 mod->DrawDepth = R_Q1BSP_DrawDepth;
4946 mod->DrawDebug = R_Q1BSP_DrawDebug;
4947 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
4948 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
4949 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
4950 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
4951 mod->DrawLight = R_Q1BSP_DrawLight;
4955 mod->brush.qw_md4sum = 0;
4956 mod->brush.qw_md4sum2 = 0;
4957 for (i = 0;i < Q2HEADER_LUMPS;i++)
4960 if (i == Q2LUMP_ENTITIES)
4962 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4963 mod->brush.qw_md4sum ^= LittleLong(temp);
4964 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4966 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4969 // many of these functions are identical to Q1 loaders, so we use those where possible
4970 Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4971 Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4972 Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4973 Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4974 Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4975 Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4976 Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4977 Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4978 Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4979 Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4980 Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4981 Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4982 Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4983 Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4984 Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4985 Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4986 Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4987 Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4988 Mod_Q2BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS]);
4990 for (i = 0; i < Q2HEADER_LUMPS; i++)
4991 if (lumpsb[i].readcount != lumpsb[i].cursize)
4992 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4994 // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4995 // doesn't enable the cvar, just indicates that transparent water is OK
4996 loadmodel->brush.supportwateralpha = true;
4998 // we don't need the compressed pvs data anymore
4999 if (mod->brushq1.data_compressedpvs)
5000 Mem_Free(mod->brushq1.data_compressedpvs);
5001 mod->brushq1.data_compressedpvs = NULL;
5002 mod->brushq1.num_compressedpvs = 0;
5004 // the MakePortals code works fine on the q2bsp data as well
5005 if (mod_bsp_portalize.integer)
5006 Mod_Q1BSP_MakePortals();
5008 mod->numframes = 0; // q2bsp animations are kind of special, frame is unbounded...
5011 if (loadmodel->brush.numsubmodels)
5012 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
5014 totalstylesurfaces = 0;
5016 for (i = 0;i < mod->brush.numsubmodels;i++)
5018 memset(stylecounts, 0, sizeof(stylecounts));
5019 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
5021 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
5022 for (j = 0;j < MAXLIGHTMAPS;j++)
5023 stylecounts[surface->lightmapinfo->styles[j]]++;
5025 for (k = 0;k < 255;k++)
5029 totalstylesurfaces += stylecounts[k];
5032 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
5033 // set up the world model, then on each submodel copy from the world model
5034 // and set up the submodel with the respective model info.
5036 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
5038 mnode_t *rootnode = NULL;
5039 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
5043 // duplicate the basic information
5044 dpsnprintf(name, sizeof(name), "*%i", i);
5045 mod = Mod_FindName(name, loadmodel->name);
5046 // copy the base model to this one
5048 // rename the clone back to its proper name
5049 strlcpy(mod->name, name, sizeof(mod->name));
5050 mod->brush.parentmodel = loadmodel;
5051 // textures and memory belong to the main model
5052 mod->texturepool = NULL;
5053 mod->mempool = NULL;
5054 mod->brush.GetPVS = NULL;
5055 mod->brush.FatPVS = NULL;
5056 mod->brush.BoxTouchingPVS = NULL;
5057 mod->brush.BoxTouchingLeafPVS = NULL;
5058 mod->brush.BoxTouchingVisibleLeafs = NULL;
5059 mod->brush.FindBoxClusters = NULL;
5060 mod->brush.LightPoint = NULL;
5061 mod->brush.AmbientSoundLevelsForPoint = NULL;
5063 mod->brush.submodel = i;
5064 if (loadmodel->brush.submodels)
5065 loadmodel->brush.submodels[i] = mod;
5067 bm = &mod->brushq1.submodels[i];
5069 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5070 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5072 mod->firstmodelsurface = bm->firstface;
5073 mod->nummodelsurfaces = bm->numfaces;
5075 // set node/leaf parents for this submodel
5076 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5077 // (this happens in base3.bsp)
5078 if (bm->headnode[0] >= 0)
5079 rootnode = mod->brush.data_nodes + bm->headnode[0];
5081 rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5082 Mod_Q1BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5084 // make the model surface list (used by shadowing/lighting)
5085 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
5086 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5087 if (firstbrush <= lastbrush)
5089 mod->firstmodelbrush = firstbrush;
5090 mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5094 mod->firstmodelbrush = 0;
5095 mod->nummodelbrushes = 0;
5097 Mod_MakeSortedSurfaces(mod);
5099 VectorCopy(bm->mins, mod->normalmins);
5100 VectorCopy(bm->maxs, mod->normalmaxs);
5101 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5102 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5103 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5104 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5105 modelradius = modelyawradius + modelradius * modelradius;
5106 modelyawradius = sqrt(modelyawradius);
5107 modelradius = sqrt(modelradius);
5108 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5109 mod->yawmins[2] = mod->normalmins[2];
5110 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
5111 mod->yawmaxs[2] = mod->normalmaxs[2];
5112 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5113 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5114 mod->radius = modelradius;
5115 mod->radius2 = modelradius * modelradius;
5117 // this gets altered below if sky or water is used
5118 mod->DrawSky = NULL;
5119 mod->DrawAddWaterPlanes = NULL;
5121 // scan surfaces for sky and water and flag the submodel as possessing these features or not
5122 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5123 if (mod->nummodelsurfaces)
5125 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5126 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
5128 if (j < mod->nummodelsurfaces)
5129 mod->DrawSky = R_Q1BSP_DrawSky;
5131 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5132 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
5134 if (j < mod->nummodelsurfaces)
5135 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
5137 // build lightstyle update chains
5138 // (used to rapidly mark lightmapupdateflags on many surfaces
5139 // when d_lightstylevalue changes)
5140 memset(stylecounts, 0, sizeof(stylecounts));
5141 for (k = 0;k < mod->nummodelsurfaces;k++)
5143 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5144 for (j = 0;j < MAXLIGHTMAPS;j++)
5145 stylecounts[surface->lightmapinfo->styles[j]]++;
5147 mod->brushq1.num_lightstyles = 0;
5148 for (k = 0;k < 255;k++)
5152 styleinfo[mod->brushq1.num_lightstyles].style = k;
5153 styleinfo[mod->brushq1.num_lightstyles].value = 0;
5154 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5155 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
5156 remapstyles[k] = mod->brushq1.num_lightstyles;
5157 mod->brushq1.num_lightstyles++;
5160 for (k = 0;k < mod->nummodelsurfaces;k++)
5162 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5163 for (j = 0;j < MAXLIGHTMAPS;j++)
5165 if (surface->lightmapinfo->styles[j] != 255)
5167 int r = remapstyles[surface->lightmapinfo->styles[j]];
5168 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
5172 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
5173 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5177 Con_Warnf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5179 //mod->brushq1.num_visleafs = bm->visleafs;
5181 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5182 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5184 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5185 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5187 // generate VBOs and other shared data before cloning submodels
5193 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);
5196 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents);
5197 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents);
5199 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5202 char key[128], value[MAX_INPUTLINE];
5204 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5205 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5206 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5209 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5210 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5211 loadmodel->brush.entities[l->filelen] = 0;
5212 data = loadmodel->brush.entities;
5213 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5214 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5215 loadmodel->brushq3.deluxemapping = false;
5216 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5220 if (!COM_ParseToken_Simple(&data, false, false, true))
5222 if (com_token[0] == '}')
5223 break; // end of worldspawn
5224 if (com_token[0] == '_')
5225 strlcpy(key, com_token + 1, sizeof(key));
5227 strlcpy(key, com_token, sizeof(key));
5228 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5229 key[strlen(key)-1] = 0;
5230 if (!COM_ParseToken_Simple(&data, false, false, true))
5232 strlcpy(value, com_token, sizeof(value));
5233 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5235 #if _MSC_VER >= 1400
5236 #define sscanf sscanf_s
5239 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5240 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5242 VectorSet(v, 64, 64, 128);
5243 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5244 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]);
5245 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5246 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5249 else if (!strcmp("deluxeMaps", key))
5251 if (!strcmp(com_token, "1"))
5253 loadmodel->brushq3.deluxemapping = true;
5254 loadmodel->brushq3.deluxemapping_modelspace = true;
5256 else if (!strcmp(com_token, "2"))
5258 loadmodel->brushq3.deluxemapping = true;
5259 loadmodel->brushq3.deluxemapping_modelspace = false;
5266 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5272 in = (q3dtexture_t *)(mod_base + l->fileofs);
5273 if (l->filelen % sizeof(*in))
5274 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5275 count = l->filelen / sizeof(*in);
5276 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5278 loadmodel->data_textures = out;
5279 loadmodel->num_textures = count;
5280 loadmodel->num_texturesperskin = loadmodel->num_textures;
5282 for (i = 0;i < count;i++)
5284 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5285 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5286 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
5287 // restore the surfaceflags and supercontents
5288 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5289 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5293 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5299 in = (q3dplane_t *)(mod_base + l->fileofs);
5300 if (l->filelen % sizeof(*in))
5301 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5302 count = l->filelen / sizeof(*in);
5303 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5305 loadmodel->brush.data_planes = out;
5306 loadmodel->brush.num_planes = count;
5308 for (i = 0;i < count;i++, in++, out++)
5310 out->normal[0] = LittleFloat(in->normal[0]);
5311 out->normal[1] = LittleFloat(in->normal[1]);
5312 out->normal[2] = LittleFloat(in->normal[2]);
5313 out->dist = LittleFloat(in->dist);
5318 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5321 q3mbrushside_t *out;
5324 in = (q3dbrushside_t *)(mod_base + l->fileofs);
5325 if (l->filelen % sizeof(*in))
5326 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5327 count = l->filelen / sizeof(*in);
5328 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5330 loadmodel->brush.data_brushsides = out;
5331 loadmodel->brush.num_brushsides = count;
5333 for (i = 0;i < count;i++, in++, out++)
5335 n = LittleLong(in->planeindex);
5336 if (n < 0 || n >= loadmodel->brush.num_planes)
5337 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5338 out->plane = loadmodel->brush.data_planes + n;
5339 n = LittleLong(in->textureindex);
5340 if (n < 0 || n >= loadmodel->num_textures)
5341 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5342 out->texture = loadmodel->data_textures + n;
5346 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5348 q3dbrushside_ig_t *in;
5349 q3mbrushside_t *out;
5352 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5353 if (l->filelen % sizeof(*in))
5354 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5355 count = l->filelen / sizeof(*in);
5356 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5358 loadmodel->brush.data_brushsides = out;
5359 loadmodel->brush.num_brushsides = count;
5361 for (i = 0;i < count;i++, in++, out++)
5363 n = LittleLong(in->planeindex);
5364 if (n < 0 || n >= loadmodel->brush.num_planes)
5365 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5366 out->plane = loadmodel->brush.data_planes + n;
5367 n = LittleLong(in->textureindex);
5368 if (n < 0 || n >= loadmodel->num_textures)
5369 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5370 out->texture = loadmodel->data_textures + n;
5374 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5378 int i, j, n, c, count, maxplanes, q3surfaceflags;
5379 colplanef_t *planes;
5381 in = (q3dbrush_t *)(mod_base + l->fileofs);
5382 if (l->filelen % sizeof(*in))
5383 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5384 count = l->filelen / sizeof(*in);
5385 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5387 loadmodel->brush.data_brushes = out;
5388 loadmodel->brush.num_brushes = count;
5393 for (i = 0;i < count;i++, in++, out++)
5395 n = LittleLong(in->firstbrushside);
5396 c = LittleLong(in->numbrushsides);
5397 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5398 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5399 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5400 out->numbrushsides = c;
5401 n = LittleLong(in->textureindex);
5402 if (n < 0 || n >= loadmodel->num_textures)
5403 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5404 out->texture = loadmodel->data_textures + n;
5406 // make a list of mplane_t structs to construct a colbrush from
5407 if (maxplanes < out->numbrushsides)
5409 maxplanes = out->numbrushsides;
5412 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5415 for (j = 0;j < out->numbrushsides;j++)
5417 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5418 planes[j].dist = out->firstbrushside[j].plane->dist;
5419 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5420 planes[j].texture = out->firstbrushside[j].texture;
5421 q3surfaceflags |= planes[j].q3surfaceflags;
5423 // make the colbrush from the planes
5424 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5426 // this whole loop can take a while (e.g. on redstarrepublic4)
5427 CL_KeepaliveMessage(false);
5433 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5439 in = (q3deffect_t *)(mod_base + l->fileofs);
5440 if (l->filelen % sizeof(*in))
5441 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5442 count = l->filelen / sizeof(*in);
5443 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5445 loadmodel->brushq3.data_effects = out;
5446 loadmodel->brushq3.num_effects = count;
5448 for (i = 0;i < count;i++, in++, out++)
5450 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5451 n = LittleLong(in->brushindex);
5452 if (n >= loadmodel->brush.num_brushes)
5454 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5457 out->brushindex = n;
5458 out->unknown = LittleLong(in->unknown);
5462 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5467 in = (q3dvertex_t *)(mod_base + l->fileofs);
5468 if (l->filelen % sizeof(*in))
5469 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5470 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5471 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5472 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5473 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5474 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5475 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5477 for (i = 0;i < count;i++, in++)
5479 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5480 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5481 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5482 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5483 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5484 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5485 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5486 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5487 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5488 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5489 // svector/tvector are calculated later in face loading
5490 if(mod_q3bsp_sRGBlightmaps.integer)
5492 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5493 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5494 // working like this may be odd, but matches q3map2 -gamma 2.2
5495 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5497 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5498 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5499 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5500 // we fix the brightness consistently via lightmapscale
5504 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5505 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5506 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5511 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5513 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5514 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5515 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5519 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5520 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5521 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5524 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5525 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5526 loadmodel->lit = true;
5530 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5536 in = (int *)(mod_base + l->fileofs);
5537 if (l->filelen % sizeof(int[3]))
5538 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5539 count = l->filelen / sizeof(*in);
5541 if(!loadmodel->brushq3.num_vertices)
5544 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5545 loadmodel->brushq3.num_triangles = 0;
5549 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5550 loadmodel->brushq3.num_triangles = count / 3;
5551 loadmodel->brushq3.data_element3i = out;
5553 for (i = 0;i < count;i++, in++, out++)
5555 *out = LittleLong(*in);
5556 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5558 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5564 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5566 q3dlightmap_t *input_pointer;
5584 int mergedrowsxcolumns;
5589 unsigned char *mergedpixels;
5590 unsigned char *mergeddeluxepixels;
5591 unsigned char *mergebuf;
5592 char mapname[MAX_QPATH];
5594 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5597 // defaults for q3bsp
5604 loadmodel->brushq3.lightmapsize = 128;
5606 if (cls.state == ca_dedicated)
5609 if(mod_q3bsp_nolightmaps.integer)
5615 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5616 if (developer_loading.integer)
5617 Con_Printf("Using internal lightmaps\n");
5618 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5619 if (l->filelen % sizeof(*input_pointer))
5620 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5621 count = l->filelen / sizeof(*input_pointer);
5622 for(i = 0; i < count; ++i)
5623 inpixels[i] = input_pointer[i].rgb;
5627 // no internal lightmaps
5628 // try external lightmaps
5629 if (developer_loading.integer)
5630 Con_Printf("Using external lightmaps\n");
5631 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5632 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5636 // using EXTERNAL lightmaps instead
5637 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5639 Mem_Free(inpixels[0]);
5640 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5650 for(count = 1; ; ++count)
5652 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5653 if(!inpixels[count])
5654 break; // we got all of them
5655 if(image_width != size || image_height != size)
5657 Mem_Free(inpixels[count]);
5658 inpixels[count] = NULL;
5659 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);
5665 loadmodel->brushq3.lightmapsize = size;
5666 loadmodel->brushq3.num_originallightmaps = count;
5668 // now check the surfaces to see if any of them index an odd numbered
5669 // lightmap, if so this is not a deluxemapped bsp file
5671 // also check what lightmaps are actually used, because q3map2 sometimes
5672 // (always?) makes an unused one at the end, which
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.
5677 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5678 // in Mod_Q3BSP_LoadEntities was failed
5679 if (!loadmodel->brushq3.deluxemapping)
5681 loadmodel->brushq3.deluxemapping = !(count & 1);
5682 loadmodel->brushq3.deluxemapping_modelspace = true;
5684 if (loadmodel->brushq3.deluxemapping)
5686 int facecount = faceslump->filelen / sizeof(q3dface_t);
5687 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5688 for (i = 0;i < facecount;i++)
5690 j = LittleLong(faces[i].lightmapindex);
5693 endlightmap = max(endlightmap, j + 1);
5694 if ((j & 1) || j + 1 >= count)
5696 loadmodel->brushq3.deluxemapping = false;
5703 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5704 // reason when only one lightmap is used, which can throw off the
5705 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5706 // to see if the second lightmap is blank, if so it is not deluxemapped.
5708 // further research has shown q3map2 sometimes creates a deluxemap and two
5709 // blank lightmaps, which must be handled properly as well
5710 if (endlightmap == 1 && count > 1)
5713 for (i = 0;i < size*size;i++)
5715 if (c[bytesperpixel*i + rgbmap[0]])
5717 if (c[bytesperpixel*i + rgbmap[1]])
5719 if (c[bytesperpixel*i + rgbmap[2]])
5724 // all pixels in the unused lightmap were black...
5725 loadmodel->brushq3.deluxemapping = false;
5730 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5732 // figure out what the most reasonable merge power is within limits
5734 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5735 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5737 // figure out how big the merged texture has to be
5738 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5739 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5740 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5742 mergedwidth = mergegoal;
5743 mergedheight = mergegoal;
5744 // choose non-square size (2x1 aspect) if only half the space is used;
5745 // this really only happens when the entire set fits in one texture, if
5746 // there are multiple textures, we don't worry about shrinking the last
5747 // one to fit, because the driver prefers the same texture size on
5748 // consecutive draw calls...
5749 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5752 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5753 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5754 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5755 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5756 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5757 loadmodel->brushq3.num_lightmapmergedheightpower++;
5758 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5760 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5761 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5762 powerxy = powerx+powery;
5763 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5765 mergedcolumns = 1 << powerx;
5766 mergedrows = 1 << powery;
5767 mergedrowsxcolumns = 1 << powerxy;
5769 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5770 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5771 if (loadmodel->brushq3.deluxemapping)
5772 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5774 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5775 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5776 for (i = 0;i < count;i++)
5778 // figure out which merged lightmap texture this fits into
5779 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5780 lightmapindex = i >> powerdxy;
5782 // choose the destination address
5783 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5784 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5785 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5786 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);
5788 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5789 for (j = 0;j < size;j++)
5790 for (k = 0;k < size;k++)
5792 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5793 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5794 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5795 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5798 // upload texture if this was the last tile being written to the texture
5799 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5801 if (loadmodel->brushq3.deluxemapping && (i & 1))
5802 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);
5805 if(mod_q3bsp_sRGBlightmaps.integer)
5808 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5810 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5811 // we fix the brightness consistently via lightmapscale
5814 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5815 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);
5819 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5820 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5821 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);
5827 if (mergeddeluxepixels)
5828 Mem_Free(mergeddeluxepixels);
5829 Mem_Free(mergedpixels);
5832 for(i = 0; i < count; ++i)
5833 Mem_Free(inpixels[i]);
5837 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5842 *collisionstride = stride;
5845 cnt = (num_triangles + stride - 1) / stride;
5846 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5847 for(j = 0; j < cnt; ++j)
5849 mins = &((*collisionbbox6f)[6 * j + 0]);
5850 maxs = &((*collisionbbox6f)[6 * j + 3]);
5851 for(k = 0; k < stride; ++k)
5853 tri = j * stride + k;
5854 if(tri >= num_triangles)
5856 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5857 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5858 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5859 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5860 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5861 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5862 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5863 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5864 if(vert[0] < mins[0]) mins[0] = vert[0];
5865 if(vert[1] < mins[1]) mins[1] = vert[1];
5866 if(vert[2] < mins[2]) mins[2] = vert[2];
5867 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5868 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5869 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5870 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5871 if(vert[0] < mins[0]) mins[0] = vert[0];
5872 if(vert[1] < mins[1]) mins[1] = vert[1];
5873 if(vert[2] < mins[2]) mins[2] = vert[2];
5874 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5875 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5876 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5881 *collisionbbox6f = NULL;
5884 typedef struct patchtess_s
5888 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5891 float *originalvertex3f;
5894 #define PATCHTESS_SAME_LODGROUP(a,b) \
5896 (a).lodgroup[0] == (b).lodgroup[0] && \
5897 (a).lodgroup[1] == (b).lodgroup[1] && \
5898 (a).lodgroup[2] == (b).lodgroup[2] && \
5899 (a).lodgroup[3] == (b).lodgroup[3] && \
5900 (a).lodgroup[4] == (b).lodgroup[4] && \
5901 (a).lodgroup[5] == (b).lodgroup[5] \
5904 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5906 q3dface_t *in, *oldin;
5907 msurface_t *out, *oldout;
5908 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;
5909 float lightmaptcbase[2], lightmaptcscale[2];
5910 //int *originalelement3i;
5911 float *originalvertex3f;
5912 //float *originalsvector3f;
5913 //float *originaltvector3f;
5914 float *originalnormal3f;
5915 float *originalcolor4f;
5916 float *originaltexcoordtexture2f;
5917 float *originaltexcoordlightmap2f;
5918 float *surfacecollisionvertex3f;
5919 int *surfacecollisionelement3i;
5921 patchtess_t *patchtess = NULL;
5922 int patchtesscount = 0;
5925 in = (q3dface_t *)(mod_base + l->fileofs);
5926 if (l->filelen % sizeof(*in))
5927 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5928 count = l->filelen / sizeof(*in);
5929 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5931 loadmodel->data_surfaces = out;
5932 loadmodel->num_surfaces = count;
5935 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5943 for (;i < count;i++, in++, out++)
5945 // check face type first
5946 type = LittleLong(in->type);
5947 if (type != Q3FACETYPE_FLAT
5948 && type != Q3FACETYPE_PATCH
5949 && type != Q3FACETYPE_MESH
5950 && type != Q3FACETYPE_FLARE)
5952 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5956 n = LittleLong(in->textureindex);
5957 if (n < 0 || n >= loadmodel->num_textures)
5959 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5962 out->texture = loadmodel->data_textures + n;
5963 n = LittleLong(in->effectindex);
5964 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5966 if (developer_extra.integer)
5967 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5973 out->effect = loadmodel->brushq3.data_effects + n;
5975 if (cls.state != ca_dedicated)
5977 out->lightmaptexture = NULL;
5978 out->deluxemaptexture = r_texture_blanknormalmap;
5979 n = LittleLong(in->lightmapindex);
5982 else if (n >= loadmodel->brushq3.num_originallightmaps)
5984 if(loadmodel->brushq3.num_originallightmaps != 0)
5985 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5990 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5991 if (loadmodel->brushq3.deluxemapping)
5992 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5993 loadmodel->lit = true;
5997 firstvertex = LittleLong(in->firstvertex);
5998 numvertices = LittleLong(in->numvertices);
5999 firstelement = LittleLong(in->firstelement);
6000 numtriangles = LittleLong(in->numelements) / 3;
6001 if (numtriangles * 3 != LittleLong(in->numelements))
6003 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));
6006 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
6008 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);
6011 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
6013 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);
6018 case Q3FACETYPE_FLAT:
6019 case Q3FACETYPE_MESH:
6020 // no processing necessary
6022 case Q3FACETYPE_PATCH:
6023 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6024 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6025 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))
6027 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
6030 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6032 // convert patch to Q3FACETYPE_MESH
6033 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
6034 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
6035 // bound to user settings
6036 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
6037 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
6038 // bound to sanity settings
6039 xtess = bound(0, xtess, 1024);
6040 ytess = bound(0, ytess, 1024);
6042 // lower quality collision patches! Same procedure as before, but different cvars
6043 // convert patch to Q3FACETYPE_MESH
6044 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
6045 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
6046 // bound to user settings
6047 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
6048 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
6049 // bound to sanity settings
6050 cxtess = bound(0, cxtess, 1024);
6051 cytess = bound(0, cytess, 1024);
6053 // store it for the LOD grouping step
6054 patchtess[patchtesscount].info.xsize = patchsize[0];
6055 patchtess[patchtesscount].info.ysize = patchsize[1];
6056 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
6057 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
6058 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
6059 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
6061 patchtess[patchtesscount].surface_id = i;
6062 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
6063 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
6064 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
6065 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
6066 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
6067 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
6068 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
6071 case Q3FACETYPE_FLARE:
6072 if (developer_extra.integer)
6073 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
6077 out->num_vertices = numvertices;
6078 out->num_triangles = numtriangles;
6079 meshvertices += out->num_vertices;
6080 meshtriangles += out->num_triangles;
6083 // Fix patches tesselations so that they make no seams
6087 for(i = 0; i < patchtesscount; ++i)
6089 for(j = i+1; j < patchtesscount; ++j)
6091 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
6094 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
6101 // Calculate resulting number of triangles
6102 collisionvertices = 0;
6103 collisiontriangles = 0;
6104 for(i = 0; i < patchtesscount; ++i)
6106 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
6107 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
6108 numvertices = finalwidth * finalheight;
6109 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6111 oldout[patchtess[i].surface_id].num_vertices = numvertices;
6112 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
6113 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
6114 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
6116 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
6117 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
6118 numvertices = finalwidth * finalheight;
6119 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6121 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
6122 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
6123 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
6124 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
6130 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true);
6131 if (collisiontriangles)
6133 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6134 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6138 collisionvertices = 0;
6139 collisiontriangles = 0;
6140 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6142 if (out->num_vertices < 3 || out->num_triangles < 1)
6145 type = LittleLong(in->type);
6146 firstvertex = LittleLong(in->firstvertex);
6147 firstelement = LittleLong(in->firstelement);
6148 out->num_firstvertex = meshvertices;
6149 out->num_firsttriangle = meshtriangles;
6150 out->num_firstcollisiontriangle = collisiontriangles;
6153 case Q3FACETYPE_FLAT:
6154 case Q3FACETYPE_MESH:
6155 // no processing necessary, except for lightmap merging
6156 for (j = 0;j < out->num_vertices;j++)
6158 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6159 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6160 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6161 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6162 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6163 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6164 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6165 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6166 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6167 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6168 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6169 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6170 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6171 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6173 for (j = 0;j < out->num_triangles*3;j++)
6174 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6176 case Q3FACETYPE_PATCH:
6177 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6178 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6179 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6180 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6181 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6182 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6183 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6185 xtess = ytess = cxtess = cytess = -1;
6186 for(j = 0; j < patchtesscount; ++j)
6187 if(patchtess[j].surface_id == i)
6189 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6190 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6191 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6192 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6197 Con_Errorf("ERROR: patch %d isn't preprocessed?!?\n", i);
6198 xtess = ytess = cxtess = cytess = 0;
6201 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6202 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6203 finalvertices = finalwidth * finalheight;
6204 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6205 type = Q3FACETYPE_MESH;
6206 // generate geometry
6207 // (note: normals are skipped because they get recalculated)
6208 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6209 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6210 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6211 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6212 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6213 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6215 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);
6217 if (developer_extra.integer)
6219 if (out->num_triangles < finaltriangles)
6220 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);
6222 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);
6224 // q3map does not put in collision brushes for curves... ugh
6225 // build the lower quality collision geometry
6226 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6227 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6228 finalvertices = finalwidth * finalheight;
6229 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6231 // legacy collision geometry implementation
6232 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
6233 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
6234 out->num_collisionvertices = finalvertices;
6235 out->num_collisiontriangles = finaltriangles;
6236 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6237 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
6239 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
6240 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
6242 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
6244 // now optimize the collision mesh by finding triangle bboxes...
6245 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
6246 Mod_Q3BSP_BuildBBoxes(loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle, out->num_triangles, loadmodel->surfmesh.data_vertex3f, &out->deprecatedq3data_bbox6f, &out->deprecatedq3num_bboxstride, mod_q3bsp_curves_stride.integer);
6248 // store collision geometry for BIH collision tree
6249 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6250 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6251 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6252 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6253 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6255 // remove this once the legacy code is removed
6257 int nc = out->num_collisiontriangles;
6259 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6261 if(nc != out->num_collisiontriangles)
6263 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
6268 if (developer_extra.integer)
6269 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);
6271 collisionvertices += finalvertices;
6272 collisiontriangles += out->num_collisiontriangles;
6277 meshvertices += out->num_vertices;
6278 meshtriangles += out->num_triangles;
6279 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6280 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)
6282 if (invalidelements)
6284 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);
6285 for (j = 0;j < out->num_triangles * 3;j++)
6287 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6288 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)
6289 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6293 // calculate a bounding box
6294 VectorClear(out->mins);
6295 VectorClear(out->maxs);
6296 if (out->num_vertices)
6298 if (cls.state != ca_dedicated && out->lightmaptexture)
6300 // figure out which part of the merged lightmap this fits into
6301 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6302 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6303 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6304 lightmapindex &= mergewidth * mergeheight - 1;
6305 lightmaptcscale[0] = 1.0f / mergewidth;
6306 lightmaptcscale[1] = 1.0f / mergeheight;
6307 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6308 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6309 // modify the lightmap texcoords to match this region of the merged lightmap
6310 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6312 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6313 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6316 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6317 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6318 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6320 out->mins[0] = min(out->mins[0], v[0]);
6321 out->maxs[0] = max(out->maxs[0], v[0]);
6322 out->mins[1] = min(out->mins[1], v[1]);
6323 out->maxs[1] = max(out->maxs[1], v[1]);
6324 out->mins[2] = min(out->mins[2], v[2]);
6325 out->maxs[2] = max(out->maxs[2], v[2]);
6327 out->mins[0] -= 1.0f;
6328 out->mins[1] -= 1.0f;
6329 out->mins[2] -= 1.0f;
6330 out->maxs[0] += 1.0f;
6331 out->maxs[1] += 1.0f;
6332 out->maxs[2] += 1.0f;
6334 // set lightmap styles for consistency with q1bsp
6335 //out->lightmapinfo->styles[0] = 0;
6336 //out->lightmapinfo->styles[1] = 255;
6337 //out->lightmapinfo->styles[2] = 255;
6338 //out->lightmapinfo->styles[3] = 255;
6343 for (;i < count;i++, out++)
6345 if(out->num_vertices && out->num_triangles)
6347 if(out->num_vertices == 0)
6349 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6350 if(out->num_triangles == 0)
6351 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6353 else if(out->num_triangles == 0)
6354 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)",
6355 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6356 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6357 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6360 // for per pixel lighting
6361 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);
6363 // generate ushort elements array if possible
6364 if (loadmodel->surfmesh.data_element3s)
6365 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6366 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6368 // free the no longer needed vertex data
6369 loadmodel->brushq3.num_vertices = 0;
6370 if (loadmodel->brushq3.data_vertex3f)
6371 Mem_Free(loadmodel->brushq3.data_vertex3f);
6372 loadmodel->brushq3.data_vertex3f = NULL;
6373 loadmodel->brushq3.data_normal3f = NULL;
6374 loadmodel->brushq3.data_texcoordtexture2f = NULL;
6375 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6376 loadmodel->brushq3.data_color4f = NULL;
6377 // free the no longer needed triangle data
6378 loadmodel->brushq3.num_triangles = 0;
6379 if (loadmodel->brushq3.data_element3i)
6380 Mem_Free(loadmodel->brushq3.data_element3i);
6381 loadmodel->brushq3.data_element3i = NULL;
6384 Mem_Free(patchtess);
6387 static void Mod_Q3BSP_LoadModels(lump_t *l)
6391 int i, j, n, c, count;
6393 in = (q3dmodel_t *)(mod_base + l->fileofs);
6394 if (l->filelen % sizeof(*in))
6395 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6396 count = l->filelen / sizeof(*in);
6397 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6399 loadmodel->brushq3.data_models = out;
6400 loadmodel->brushq3.num_models = count;
6402 for (i = 0;i < count;i++, in++, out++)
6404 for (j = 0;j < 3;j++)
6406 out->mins[j] = LittleFloat(in->mins[j]);
6407 out->maxs[j] = LittleFloat(in->maxs[j]);
6409 n = LittleLong(in->firstface);
6410 c = LittleLong(in->numfaces);
6411 if (n < 0 || n + c > loadmodel->num_surfaces)
6412 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6415 n = LittleLong(in->firstbrush);
6416 c = LittleLong(in->numbrushes);
6417 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6418 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6419 out->firstbrush = n;
6420 out->numbrushes = c;
6424 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6430 in = (int *)(mod_base + l->fileofs);
6431 if (l->filelen % sizeof(*in))
6432 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6433 count = l->filelen / sizeof(*in);
6434 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6436 loadmodel->brush.data_leafbrushes = out;
6437 loadmodel->brush.num_leafbrushes = count;
6439 for (i = 0;i < count;i++, in++, out++)
6441 n = LittleLong(*in);
6442 if (n < 0 || n >= loadmodel->brush.num_brushes)
6443 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6448 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6454 in = (int *)(mod_base + l->fileofs);
6455 if (l->filelen % sizeof(*in))
6456 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6457 count = l->filelen / sizeof(*in);
6458 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6460 loadmodel->brush.data_leafsurfaces = out;
6461 loadmodel->brush.num_leafsurfaces = count;
6463 for (i = 0;i < count;i++, in++, out++)
6465 n = LittleLong(*in);
6466 if (n < 0 || n >= loadmodel->num_surfaces)
6467 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6472 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6476 int i, j, n, c, count;
6478 in = (q3dleaf_t *)(mod_base + l->fileofs);
6479 if (l->filelen % sizeof(*in))
6480 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6481 count = l->filelen / sizeof(*in);
6482 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6484 loadmodel->brush.data_leafs = out;
6485 loadmodel->brush.num_leafs = count;
6487 for (i = 0;i < count;i++, in++, out++)
6491 out->clusterindex = LittleLong(in->clusterindex);
6492 out->areaindex = LittleLong(in->areaindex);
6493 for (j = 0;j < 3;j++)
6495 // yes the mins/maxs are ints
6496 out->mins[j] = LittleLong(in->mins[j]) - 1;
6497 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6499 n = LittleLong(in->firstleafface);
6500 c = LittleLong(in->numleaffaces);
6501 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6502 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6503 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6504 out->numleafsurfaces = c;
6505 n = LittleLong(in->firstleafbrush);
6506 c = LittleLong(in->numleafbrushes);
6507 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6508 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6509 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6510 out->numleafbrushes = c;
6514 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6520 in = (q3dnode_t *)(mod_base + l->fileofs);
6521 if (l->filelen % sizeof(*in))
6522 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6523 count = l->filelen / sizeof(*in);
6525 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6526 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6528 loadmodel->brush.data_nodes = out;
6529 loadmodel->brush.num_nodes = count;
6531 for (i = 0;i < count;i++, in++, out++)
6534 n = LittleLong(in->planeindex);
6535 if (n < 0 || n >= loadmodel->brush.num_planes)
6536 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6537 out->plane = loadmodel->brush.data_planes + n;
6538 for (j = 0;j < 2;j++)
6540 n = LittleLong(in->childrenindex[j]);
6543 if (n >= loadmodel->brush.num_nodes)
6544 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6545 out->children[j] = loadmodel->brush.data_nodes + n;
6550 if (n >= loadmodel->brush.num_leafs)
6551 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6552 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6555 for (j = 0;j < 3;j++)
6557 // yes the mins/maxs are ints
6558 out->mins[j] = LittleLong(in->mins[j]) - 1;
6559 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6563 // set the parent pointers
6564 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6567 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6570 q3dlightgrid_t *out;
6574 unsigned char *texturergba, *texturelayer[3], *texturepadding[2];
6575 double lightgridmatrix[4][4];
6577 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6578 if (l->filelen % sizeof(*in))
6579 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6580 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6581 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6582 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6583 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6584 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6585 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6586 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6587 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6588 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6589 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6590 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6591 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6592 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6593 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]);
6594 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]);
6596 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6599 if (l->filelen < count * (int)sizeof(*in))
6601 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]);
6602 return; // ignore the grid if we cannot understand it
6604 if (l->filelen != count * (int)sizeof(*in))
6605 Con_Warnf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
6606 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6607 loadmodel->brushq3.data_lightgrid = out;
6608 loadmodel->brushq3.num_lightgrid = count;
6609 // no swapping or validation necessary
6610 memcpy(out, in, count * (int)sizeof(*out));
6612 if(mod_q3bsp_sRGBlightmaps.integer)
6614 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6616 // we fix the brightness consistently via lightmapscale
6620 for(i = 0; i < count; ++i)
6622 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6623 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6624 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6625 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6626 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6627 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6633 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6635 for(i = 0; i < count; ++i)
6637 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6638 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6639 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6640 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6641 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6642 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6651 if (mod_q3bsp_lightgrid_texture.integer)
6653 // build a texture to hold the data for per-pixel sampling
6654 // this has 3 different kinds of data stacked in it:
6656 // bent-normal light color
6657 // bent-normal light dir
6659 texturesize[0] = loadmodel->brushq3.num_lightgrid_isize[0];
6660 texturesize[1] = loadmodel->brushq3.num_lightgrid_isize[1];
6661 texturesize[2] = (loadmodel->brushq3.num_lightgrid_isize[2] + 2) * 3;
6662 texturergba = (unsigned char*)Mem_Alloc(loadmodel->mempool, texturesize[0] * texturesize[1] * texturesize[2] * sizeof(char[4]));
6663 texturelayer[0] = texturergba + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6664 texturelayer[1] = texturelayer[0] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6665 texturelayer[2] = texturelayer[1] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6666 // the light dir layer needs padding above/below it that is a neutral unsigned normal (127,127,127,255)
6667 texturepadding[0] = texturelayer[2] - loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6668 texturepadding[1] = texturelayer[2] + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2] * 4;
6669 for (i = 0; i < texturesize[0] * texturesize[1]; i++)
6671 texturepadding[0][i * 4] = texturepadding[1][i * 4] = 127;
6672 texturepadding[0][i * 4 + 1] = texturepadding[1][i * 4 + 1] = 127;
6673 texturepadding[0][i * 4 + 2] = texturepadding[1][i * 4 + 2] = 127;
6674 texturepadding[0][i * 4 + 3] = texturepadding[1][i * 4 + 3] = 255;
6676 for (i = 0; i < count; i++)
6678 texturelayer[0][i * 4 + 0] = out[i].ambientrgb[0];
6679 texturelayer[0][i * 4 + 1] = out[i].ambientrgb[1];
6680 texturelayer[0][i * 4 + 2] = out[i].ambientrgb[2];
6681 texturelayer[0][i * 4 + 3] = 255;
6682 texturelayer[1][i * 4 + 0] = out[i].diffusergb[0];
6683 texturelayer[1][i * 4 + 1] = out[i].diffusergb[1];
6684 texturelayer[1][i * 4 + 2] = out[i].diffusergb[2];
6685 texturelayer[1][i * 4 + 3] = 255;
6686 // this uses the mod_md3_sin table because the values are
6687 // already in the 0-255 range, the 64+ bias fetches a cosine
6688 // instead of a sine value
6689 texturelayer[2][i * 4 + 0] = (char)((mod_md3_sin[64 + out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6690 texturelayer[2][i * 4 + 1] = (char)((mod_md3_sin[out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6691 texturelayer[2][i * 4 + 2] = (char)((mod_md3_sin[64 + out[i].diffusepitch]) * 127 + 127);
6692 texturelayer[2][i * 4 + 3] = 255;
6697 for (z = 0; z < loadmodel->brushq3.num_lightgrid_isize[2]; z++)
6699 for (y = 0; y < loadmodel->brushq3.num_lightgrid_isize[1]; y++)
6701 for (x = 0; x < loadmodel->brushq3.num_lightgrid_isize[0]; x++)
6703 i = (z * texturesize[1] + y) * texturesize[0] + x;
6704 texturelayer[0][i * 4 + 0] = x * 256 / loadmodel->brushq3.num_lightgrid_isize[0];
6705 texturelayer[0][i * 4 + 1] = y * 256 / loadmodel->brushq3.num_lightgrid_isize[1];
6706 texturelayer[0][i * 4 + 2] = z * 256 / loadmodel->brushq3.num_lightgrid_isize[2];
6711 loadmodel->brushq3.lightgridtexturesize[0] = texturesize[0];
6712 loadmodel->brushq3.lightgridtexturesize[1] = texturesize[1];
6713 loadmodel->brushq3.lightgridtexturesize[2] = texturesize[2];
6714 memset(lightgridmatrix[0], 0, sizeof(lightgridmatrix));
6715 lightgridmatrix[0][0] = loadmodel->brushq3.num_lightgrid_scale[0] / texturesize[0];
6716 lightgridmatrix[1][1] = loadmodel->brushq3.num_lightgrid_scale[1] / texturesize[1];
6717 lightgridmatrix[2][2] = loadmodel->brushq3.num_lightgrid_scale[2] / texturesize[2];
6718 lightgridmatrix[0][3] = -(loadmodel->brushq3.num_lightgrid_imins[0] - 0.5f) / texturesize[0];
6719 lightgridmatrix[1][3] = -(loadmodel->brushq3.num_lightgrid_imins[1] - 0.5f) / texturesize[1];
6720 lightgridmatrix[2][3] = -(loadmodel->brushq3.num_lightgrid_imins[2] - 1.5f) / texturesize[2];
6721 lightgridmatrix[3][3] = 1;
6722 Matrix4x4_FromArrayDoubleD3D(&loadmodel->brushq3.lightgridworldtotexturematrix, lightgridmatrix[0]);
6723 loadmodel->brushq3.lightgridtexture = R_LoadTexture3D(loadmodel->texturepool, "lightgrid", texturesize[0], texturesize[1], texturesize[2], texturergba, TEXTYPE_RGBA, TEXF_CLAMP, 0, NULL);
6724 Mem_Free(texturergba);
6729 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6734 if (l->filelen == 0)
6737 // unvised maps often have cluster indices even without pvs, so check
6738 // leafs to find real number of clusters
6739 loadmodel->brush.num_pvsclusters = 1;
6740 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6741 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6744 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6745 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6746 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6747 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6751 in = (q3dpvs_t *)(mod_base + l->fileofs);
6753 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6755 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6756 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6757 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6758 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6759 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6760 if (l->filelen < totalchains + (int)sizeof(*in))
6761 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);
6763 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6764 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6767 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6769 int i, j, k, index[3];
6770 float transformed[3], blend1, blend2, blend, stylescale = 1;
6771 q3dlightgrid_t *a, *s;
6773 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6774 // LadyHavoc: FIXME: is this true?
6775 stylescale = 1; // added while render
6776 //stylescale = r_refdef.scene.rtlightstylevalue[0];
6778 if (!model->brushq3.num_lightgrid)
6780 ambientcolor[0] = stylescale;
6781 ambientcolor[1] = stylescale;
6782 ambientcolor[2] = stylescale;
6786 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6787 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6788 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6789 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6790 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6791 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6792 index[0] = (int)floor(transformed[0]);
6793 index[1] = (int)floor(transformed[1]);
6794 index[2] = (int)floor(transformed[2]);
6795 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6797 // now lerp the values
6798 VectorClear(diffusenormal);
6799 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6800 for (k = 0;k < 2;k++)
6802 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6803 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6805 for (j = 0;j < 2;j++)
6807 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6808 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6810 for (i = 0;i < 2;i++)
6812 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6813 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6815 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6816 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6817 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6818 // this uses the mod_md3_sin table because the values are
6819 // already in the 0-255 range, the 64+ bias fetches a cosine
6820 // instead of a sine value
6821 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6822 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6823 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6824 //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)));
6829 // normalize the light direction before turning
6830 VectorNormalize(diffusenormal);
6831 //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]);
6834 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3], double endpos[3])
6837 double midf, mid[3];
6843 // find the point distances
6844 mplane_t *plane = node->plane;
6845 if (plane->type < 3)
6847 t1 = p1[plane->type] - plane->dist;
6848 t2 = p2[plane->type] - plane->dist;
6852 t1 = DotProduct (plane->normal, p1) - plane->dist;
6853 t2 = DotProduct (plane->normal, p2) - plane->dist;
6860 node = node->children[1];
6869 node = node->children[0];
6875 midf = t1 / (t1 - t2);
6876 VectorLerp(p1, midf, p2, mid);
6878 // recurse both sides, front side first
6879 // return 2 if empty is followed by solid (hit something)
6880 // do not return 2 if both are solid or both empty,
6881 // or if start is solid and end is empty
6882 // as these degenerate cases usually indicate the eye is in solid and
6883 // should see the target point anyway
6884 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid, endpos);
6887 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2, endpos);
6890 VectorCopy(mid, endpos);
6893 return ((mleaf_t *)node)->clusterindex < 0;
6896 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)
6898 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6901 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
6902 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
6906 double tracestart[3], traceend[3], traceendpos[3];
6907 VectorCopy(start, tracestart);
6908 VectorCopy(end, traceend);
6909 VectorCopy(end, traceendpos);
6910 Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend, traceendpos);
6911 return BoxesOverlap(traceendpos, traceendpos, acceptmins, acceptmaxs);
6915 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)
6918 const bih_leaf_t *leaf;
6919 const bih_node_t *node;
6920 const colbrushf_t *brush;
6923 int nodestackpos = 0;
6924 int nodestack[1024];
6926 memset(trace, 0, sizeof(*trace));
6927 trace->fraction = 1;
6928 trace->hitsupercontentsmask = hitsupercontentsmask;
6929 trace->skipsupercontentsmask = skipsupercontentsmask;
6930 trace->skipmaterialflagsmask = skipmaterialflagsmask;
6932 bih = &model->collision_bih;
6936 nodenum = bih->rootnode;
6937 nodestack[nodestackpos++] = nodenum;
6938 while (nodestackpos)
6940 nodenum = nodestack[--nodestackpos];
6941 node = bih->nodes + nodenum;
6943 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6946 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6948 axis = node->type - BIH_SPLITX;
6949 if (start[axis] >= node->frontmin)
6950 nodestack[nodestackpos++] = node->front;
6951 if (start[axis] <= node->backmax)
6952 nodestack[nodestackpos++] = node->back;
6954 else if (node->type == BIH_UNORDERED)
6956 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6958 leaf = bih->leafs + node->children[axis];
6960 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6966 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6967 Collision_TracePointBrushFloat(trace, start, brush);
6969 case BIH_COLLISIONTRIANGLE:
6970 // collision triangle - skipped because they have no volume
6972 case BIH_RENDERTRIANGLE:
6973 // render triangle - skipped because they have no volume
6981 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)
6983 const bih_leaf_t *leaf;
6984 const bih_node_t *node;
6985 const colbrushf_t *brush;
6987 const texture_t *texture;
6988 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6989 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6990 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6995 if (VectorCompare(start, end))
6997 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7001 nodenum = bih->rootnode;
7003 memset(trace, 0, sizeof(*trace));
7004 trace->fraction = 1;
7005 trace->hitsupercontentsmask = hitsupercontentsmask;
7006 trace->skipsupercontentsmask = skipsupercontentsmask;
7007 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7010 nodestackline[nodestackpos][0] = start[0];
7011 nodestackline[nodestackpos][1] = start[1];
7012 nodestackline[nodestackpos][2] = start[2];
7013 nodestackline[nodestackpos][3] = end[0];
7014 nodestackline[nodestackpos][4] = end[1];
7015 nodestackline[nodestackpos][5] = end[2];
7016 nodestack[nodestackpos++] = nodenum;
7017 while (nodestackpos)
7019 nodenum = nodestack[--nodestackpos];
7020 node = bih->nodes + nodenum;
7021 VectorCopy(nodestackline[nodestackpos], nodestart);
7022 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7023 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
7024 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
7025 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
7026 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
7027 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
7028 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
7029 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs) && !collision_bih_fullrecursion.integer)
7031 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7033 // recurse children of the split
7034 axis = node->type - BIH_SPLITX;
7035 d1 = node->backmax - nodestart[axis];
7036 d2 = node->backmax - nodeend[axis];
7037 d3 = nodestart[axis] - node->frontmin;
7038 d4 = nodeend[axis] - node->frontmin;
7039 if (collision_bih_fullrecursion.integer)
7040 d1 = d2 = d3 = d4 = 1; // force full recursion
7041 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7043 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;
7044 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;
7045 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;
7046 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7047 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;
7048 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;
7049 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;
7050 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7051 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;
7052 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;
7053 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;
7054 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7055 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7056 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7057 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7058 case 15: /* <<<< */ break;
7061 else if (node->type == BIH_UNORDERED)
7063 // calculate sweep bounds for this node
7064 // copy node bounds into local variables
7065 VectorCopy(node->mins, nodebigmins);
7066 VectorCopy(node->maxs, nodebigmaxs);
7067 // clip line to this node bounds
7068 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); }
7069 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); }
7070 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); }
7071 // some of the line intersected the enlarged node box
7072 // calculate sweep bounds for this node
7073 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
7074 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
7075 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
7076 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
7077 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
7078 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
7079 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7081 leaf = bih->leafs + node->children[axis];
7082 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7087 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7088 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
7090 case BIH_COLLISIONTRIANGLE:
7091 if (!mod_q3bsp_curves_collisions.integer)
7093 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7094 texture = model->data_textures + leaf->textureindex;
7095 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);
7097 case BIH_RENDERTRIANGLE:
7098 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7099 texture = model->data_textures + leaf->textureindex;
7100 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);
7108 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)
7110 if (VectorCompare(start, end))
7112 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7115 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->collision_bih);
7118 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)
7121 const bih_leaf_t *leaf;
7122 const bih_node_t *node;
7123 const colbrushf_t *brush;
7125 const texture_t *texture;
7126 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
7127 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
7128 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
7129 int axis, nodenum, nodestackpos = 0, nodestack[1024];
7131 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
7133 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
7134 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7136 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7140 bih = &model->collision_bih;
7143 nodenum = bih->rootnode;
7145 // box trace, performed as brush trace
7146 memset(trace, 0, sizeof(*trace));
7147 trace->fraction = 1;
7148 trace->hitsupercontentsmask = hitsupercontentsmask;
7149 trace->skipsupercontentsmask = skipsupercontentsmask;
7150 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7152 // calculate tracebox-like parameters for efficient culling
7153 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
7154 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
7155 VectorSubtract(thisbrush_start->mins, start, startmins);
7156 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
7157 VectorSubtract(thisbrush_end->mins, end, endmins);
7158 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7159 mins[0] = min(startmins[0], endmins[0]);
7160 mins[1] = min(startmins[1], endmins[1]);
7161 mins[2] = min(startmins[2], endmins[2]);
7162 maxs[0] = max(startmaxs[0], endmaxs[0]);
7163 maxs[1] = max(startmaxs[1], endmaxs[1]);
7164 maxs[2] = max(startmaxs[2], endmaxs[2]);
7167 nodestackline[nodestackpos][0] = start[0];
7168 nodestackline[nodestackpos][1] = start[1];
7169 nodestackline[nodestackpos][2] = start[2];
7170 nodestackline[nodestackpos][3] = end[0];
7171 nodestackline[nodestackpos][4] = end[1];
7172 nodestackline[nodestackpos][5] = end[2];
7173 nodestack[nodestackpos++] = nodenum;
7174 while (nodestackpos)
7176 nodenum = nodestack[--nodestackpos];
7177 node = bih->nodes + nodenum;
7178 VectorCopy(nodestackline[nodestackpos], nodestart);
7179 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7180 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7181 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7182 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7183 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7184 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7185 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7186 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7188 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7190 // recurse children of the split
7191 axis = node->type - BIH_SPLITX;
7192 d1 = node->backmax - nodestart[axis] - mins[axis];
7193 d2 = node->backmax - nodeend[axis] - mins[axis];
7194 d3 = nodestart[axis] - node->frontmin + maxs[axis];
7195 d4 = nodeend[axis] - node->frontmin + maxs[axis];
7196 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7198 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;
7199 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;
7200 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;
7201 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7202 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;
7203 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;
7204 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;
7205 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7206 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;
7207 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;
7208 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;
7209 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7210 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7211 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7212 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7213 case 15: /* <<<< */ break;
7216 else if (node->type == BIH_UNORDERED)
7218 // calculate sweep bounds for this node
7219 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7220 VectorSubtract(node->mins, maxs, nodebigmins);
7221 VectorSubtract(node->maxs, mins, nodebigmaxs);
7222 // clip line to this node bounds
7223 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); }
7224 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); }
7225 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); }
7226 // some of the line intersected the enlarged node box
7227 // calculate sweep bounds for this node
7228 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7229 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7230 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7231 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7232 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7233 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7234 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7236 leaf = bih->leafs + node->children[axis];
7237 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7242 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7243 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7245 case BIH_COLLISIONTRIANGLE:
7246 if (!mod_q3bsp_curves_collisions.integer)
7248 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7249 texture = model->data_textures + leaf->textureindex;
7250 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);
7252 case BIH_RENDERTRIANGLE:
7253 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7254 texture = model->data_textures + leaf->textureindex;
7255 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);
7263 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)
7265 colboxbrushf_t thisbrush_start, thisbrush_end;
7266 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7268 // box trace, performed as brush trace
7269 VectorAdd(start, boxmins, boxstartmins);
7270 VectorAdd(start, boxmaxs, boxstartmaxs);
7271 VectorAdd(end, boxmins, boxendmins);
7272 VectorAdd(end, boxmaxs, boxendmaxs);
7273 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7274 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7275 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7279 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7282 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0, 0);
7283 return trace.startsupercontents;
7286 qboolean Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
7289 Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
7290 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
7293 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)
7296 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7298 int hitsupercontents;
7299 VectorSet(end, start[0], start[1], model->normalmins[2]);
7301 memset(trace, 0, sizeof(*trace));
7302 trace->fraction = 1;
7303 trace->hitsupercontentsmask = hitsupercontentsmask;
7304 trace->skipsupercontentsmask = skipsupercontentsmask;
7305 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7307 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7308 hitsupercontents = trace->hitsupercontents;
7309 memset(trace, 0, sizeof(*trace));
7310 trace->fraction = 1;
7311 trace->hitsupercontentsmask = hitsupercontentsmask;
7312 trace->skipsupercontentsmask = skipsupercontentsmask;
7313 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7314 trace->startsupercontents = hitsupercontents;
7318 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7321 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7324 VectorSet(end, start[0], start[1], model->normalmins[2]);
7325 memset(&trace, 0, sizeof(trace));
7327 trace.hitsupercontentsmask = hitsupercontentsmask;
7328 trace.skipsupercontentsmask = skipsupercontentsmask;
7329 trace.skipmaterialflagsmask = skipmaterialflagsmask;
7330 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7331 return trace.hitsupercontents;
7337 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
7342 // find which leaf the point is in
7344 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7345 // point trace the brushes
7346 leaf = (mleaf_t *)node;
7347 for (i = 0;i < leaf->numleafbrushes;i++)
7349 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7350 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
7352 brush->markframe = markframe;
7353 Collision_TracePointBrushFloat(trace, point, brush);
7356 // can't do point traces on curves (they have no thickness)
7359 static void Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t start, const vec3_t end, vec_t startfrac, vec_t endfrac, const vec3_t linestart, const vec3_t lineend, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
7361 int i, startside, endside;
7362 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
7364 msurface_t *surface;
7367 // walk the tree until we hit a leaf, recursing for any split cases
7371 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7373 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7374 node = node->children[1];
7376 // abort if this part of the bsp tree can not be hit by this trace
7377 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7379 plane = node->plane;
7380 // axial planes are much more common than non-axial, so an optimized
7381 // axial case pays off here
7382 if (plane->type < 3)
7384 dist1 = start[plane->type] - plane->dist;
7385 dist2 = end[plane->type] - plane->dist;
7389 dist1 = DotProduct(start, plane->normal) - plane->dist;
7390 dist2 = DotProduct(end, plane->normal) - plane->dist;
7392 startside = dist1 < 0;
7393 endside = dist2 < 0;
7394 if (startside == endside)
7396 // most of the time the line fragment is on one side of the plane
7397 node = node->children[startside];
7401 // line crosses node plane, split the line
7402 dist1 = PlaneDiff(linestart, plane);
7403 dist2 = PlaneDiff(lineend, plane);
7404 midfrac = dist1 / (dist1 - dist2);
7405 VectorLerp(linestart, midfrac, lineend, mid);
7406 // take the near side first
7407 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7408 // if we found an impact on the front side, don't waste time
7409 // exploring the far side
7410 if (midfrac <= trace->fraction)
7411 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7416 // abort if this part of the bsp tree can not be hit by this trace
7417 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7420 nodesegmentmins[0] = min(start[0], end[0]) - 1;
7421 nodesegmentmins[1] = min(start[1], end[1]) - 1;
7422 nodesegmentmins[2] = min(start[2], end[2]) - 1;
7423 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
7424 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
7425 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
7426 // line trace the brushes
7427 leaf = (mleaf_t *)node;
7429 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7432 for (i = 0;i < leaf->numleafbrushes;i++)
7434 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7435 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7437 brush->markframe = markframe;
7438 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
7441 // can't do point traces on curves (they have no thickness)
7442 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
7444 // line trace the curves
7445 for (i = 0;i < leaf->numleafsurfaces;i++)
7447 surface = model->data_surfaces + leaf->firstleafsurface[i];
7448 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7450 surface->deprecatedq3collisionmarkframe = markframe;
7451 Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
7457 static void Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
7463 msurface_t *surface;
7465 float nodesegmentmins[3], nodesegmentmaxs[3];
7466 // walk the tree until we hit a leaf, recursing for any split cases
7470 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7472 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7473 node = node->children[1];
7475 // abort if this part of the bsp tree can not be hit by this trace
7476 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7478 plane = node->plane;
7479 // axial planes are much more common than non-axial, so an optimized
7480 // axial case pays off here
7481 if (plane->type < 3)
7483 // this is an axial plane, compare bounding box directly to it and
7484 // recurse sides accordingly
7485 // recurse down node sides
7486 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
7487 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
7488 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
7489 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
7493 // this is a non-axial plane, so check if the start and end boxes
7494 // are both on one side of the plane to handle 'diagonal' cases
7495 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
7499 // segment crosses plane
7500 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7503 // if sides == 0 then the trace itself is bogus (Not A Number values),
7504 // in this case we simply pretend the trace hit nothing
7506 return; // ERROR: NAN bounding box!
7507 // take whichever side the segment box is on
7508 node = node->children[sides - 1];
7511 // abort if this part of the bsp tree can not be hit by this trace
7512 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7514 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
7515 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
7516 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
7517 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
7518 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
7519 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
7521 leaf = (mleaf_t *)node;
7523 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7526 for (i = 0;i < leaf->numleafbrushes;i++)
7528 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7529 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7531 brush->markframe = markframe;
7532 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7535 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
7537 for (i = 0;i < leaf->numleafsurfaces;i++)
7539 surface = model->data_surfaces + leaf->firstleafsurface[i];
7540 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7542 surface->deprecatedq3collisionmarkframe = markframe;
7543 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
7550 static int markframe = 0;
7552 static void Mod_Q3BSP_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
7556 memset(trace, 0, sizeof(*trace));
7557 trace->fraction = 1;
7558 trace->hitsupercontentsmask = hitsupercontentsmask;
7559 trace->skipsupercontentsmask = skipsupercontentsmask;
7560 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7561 if (mod_collision_bih.integer)
7562 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7563 else if (model->brush.submodel)
7565 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7566 if (brush->colbrushf)
7567 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
7570 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
7573 static void Mod_Q3BSP_TraceLine(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
7576 float segmentmins[3], segmentmaxs[3];
7577 msurface_t *surface;
7580 if (VectorCompare(start, end))
7582 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7586 memset(trace, 0, sizeof(*trace));
7587 trace->fraction = 1;
7588 trace->hitsupercontentsmask = hitsupercontentsmask;
7589 trace->skipsupercontentsmask = skipsupercontentsmask;
7590 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7591 segmentmins[0] = min(start[0], end[0]) - 1;
7592 segmentmins[1] = min(start[1], end[1]) - 1;
7593 segmentmins[2] = min(start[2], end[2]) - 1;
7594 segmentmaxs[0] = max(start[0], end[0]) + 1;
7595 segmentmaxs[1] = max(start[1], end[1]) + 1;
7596 segmentmaxs[2] = max(start[2], end[2]) + 1;
7597 if (mod_collision_bih.integer)
7598 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7599 else if (model->brush.submodel)
7601 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7602 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7603 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7604 if (mod_q3bsp_curves_collisions.integer)
7605 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7606 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7607 Collision_TraceLineTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
7610 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
7613 static void Mod_Q3BSP_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *start, colbrushf_t *end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
7615 float segmentmins[3], segmentmaxs[3];
7617 msurface_t *surface;
7620 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
7622 if (VectorCompare(start->mins, end->mins))
7623 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7625 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7629 // box trace, performed as brush trace
7630 memset(trace, 0, sizeof(*trace));
7631 trace->fraction = 1;
7632 trace->hitsupercontentsmask = hitsupercontentsmask;
7633 trace->skipsupercontentsmask = skipsupercontentsmask;
7634 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7635 segmentmins[0] = min(start->mins[0], end->mins[0]) - 1;
7636 segmentmins[1] = min(start->mins[1], end->mins[1]) - 1;
7637 segmentmins[2] = min(start->mins[2], end->mins[2]) - 1;
7638 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]) + 1;
7639 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]) + 1;
7640 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]) + 1;
7641 if (mod_collision_bih.integer)
7642 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7643 else if (model->brush.submodel)
7645 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7646 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7647 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7648 if (mod_q3bsp_curves_collisions.integer)
7649 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7650 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7651 Collision_TraceBrushTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
7654 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
7657 static void Mod_Q3BSP_TraceBox(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
7659 colboxbrushf_t thisbrush_start, thisbrush_end;
7660 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7662 // box trace, performed as brush trace
7663 VectorAdd(start, boxmins, boxstartmins);
7664 VectorAdd(start, boxmaxs, boxstartmaxs);
7665 VectorAdd(end, boxmins, boxendmins);
7666 VectorAdd(end, boxmaxs, boxendmaxs);
7667 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7668 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7669 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7672 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7675 int supercontents = 0;
7677 if (mod_collision_bih.integer)
7679 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
7681 // test if the point is inside each brush
7682 else if (model->brush.submodel)
7684 // submodels are effectively one leaf
7685 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7686 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7687 supercontents |= brush->colbrushf->supercontents;
7691 mnode_t *node = model->brush.data_nodes;
7693 // find which leaf the point is in
7695 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7696 leaf = (mleaf_t *)node;
7697 // now check the brushes in the leaf
7698 for (i = 0;i < leaf->numleafbrushes;i++)
7700 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
7701 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7702 supercontents |= brush->colbrushf->supercontents;
7705 return supercontents;
7708 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)
7710 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->render_bih);
7714 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
7722 int nummodelbrushes = model->nummodelbrushes;
7723 int nummodelsurfaces = model->nummodelsurfaces;
7725 const int *collisionelement3i;
7726 const float *collisionvertex3f;
7727 const int *renderelement3i;
7728 const float *rendervertex3f;
7729 bih_leaf_t *bihleafs;
7730 bih_node_t *bihnodes;
7732 int *temp_leafsortscratch;
7733 const msurface_t *surface;
7734 const q3mbrush_t *brush;
7736 // find out how many BIH leaf nodes we need
7738 if (userendersurfaces)
7740 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7741 bihnumleafs += surface->num_triangles;
7745 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7746 if (brush->colbrushf)
7748 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7750 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7751 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7753 bihnumleafs += surface->num_collisiontriangles;
7760 // allocate the memory for the BIH leaf nodes
7761 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7763 // now populate the BIH leaf nodes
7766 // add render surfaces
7767 renderelement3i = model->surfmesh.data_element3i;
7768 rendervertex3f = model->surfmesh.data_vertex3f;
7769 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7771 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7773 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7775 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7776 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7777 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7778 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7779 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7780 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7781 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7782 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7783 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7784 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7789 if (!userendersurfaces)
7791 // add collision brushes
7792 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7794 if (!brush->colbrushf)
7796 bihleafs[bihleafindex].type = BIH_BRUSH;
7797 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7798 bihleafs[bihleafindex].surfaceindex = -1;
7799 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7800 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7801 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7805 // add collision surfaces
7806 collisionelement3i = model->brush.data_collisionelement3i;
7807 collisionvertex3f = model->brush.data_collisionvertex3f;
7808 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7810 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7812 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7813 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7814 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7815 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7816 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7817 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7818 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7819 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7820 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7821 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7827 // allocate buffers for the produced and temporary data
7828 bihmaxnodes = bihnumleafs + 1;
7829 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7830 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7831 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7834 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7836 // we're done with the temporary data
7837 Mem_Free(temp_leafsort);
7839 // resize the BIH nodes array if it over-allocated
7840 if (out->maxnodes > out->numnodes)
7842 out->maxnodes = out->numnodes;
7843 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7849 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents)
7851 int supercontents = 0;
7852 if (nativecontents & CONTENTSQ3_SOLID)
7853 supercontents |= SUPERCONTENTS_SOLID;
7854 if (nativecontents & CONTENTSQ3_WATER)
7855 supercontents |= SUPERCONTENTS_WATER;
7856 if (nativecontents & CONTENTSQ3_SLIME)
7857 supercontents |= SUPERCONTENTS_SLIME;
7858 if (nativecontents & CONTENTSQ3_LAVA)
7859 supercontents |= SUPERCONTENTS_LAVA;
7860 if (nativecontents & CONTENTSQ3_BODY)
7861 supercontents |= SUPERCONTENTS_BODY;
7862 if (nativecontents & CONTENTSQ3_CORPSE)
7863 supercontents |= SUPERCONTENTS_CORPSE;
7864 if (nativecontents & CONTENTSQ3_NODROP)
7865 supercontents |= SUPERCONTENTS_NODROP;
7866 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7867 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7868 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7869 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7870 if (nativecontents & CONTENTSQ3_DONOTENTER)
7871 supercontents |= SUPERCONTENTS_DONOTENTER;
7872 if (nativecontents & CONTENTSQ3_BOTCLIP)
7873 supercontents |= SUPERCONTENTS_BOTCLIP;
7874 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7875 supercontents |= SUPERCONTENTS_OPAQUE;
7876 return supercontents;
7879 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents)
7881 int nativecontents = 0;
7882 if (supercontents & SUPERCONTENTS_SOLID)
7883 nativecontents |= CONTENTSQ3_SOLID;
7884 if (supercontents & SUPERCONTENTS_WATER)
7885 nativecontents |= CONTENTSQ3_WATER;
7886 if (supercontents & SUPERCONTENTS_SLIME)
7887 nativecontents |= CONTENTSQ3_SLIME;
7888 if (supercontents & SUPERCONTENTS_LAVA)
7889 nativecontents |= CONTENTSQ3_LAVA;
7890 if (supercontents & SUPERCONTENTS_BODY)
7891 nativecontents |= CONTENTSQ3_BODY;
7892 if (supercontents & SUPERCONTENTS_CORPSE)
7893 nativecontents |= CONTENTSQ3_CORPSE;
7894 if (supercontents & SUPERCONTENTS_NODROP)
7895 nativecontents |= CONTENTSQ3_NODROP;
7896 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7897 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7898 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7899 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7900 if (supercontents & SUPERCONTENTS_DONOTENTER)
7901 nativecontents |= CONTENTSQ3_DONOTENTER;
7902 if (supercontents & SUPERCONTENTS_BOTCLIP)
7903 nativecontents |= CONTENTSQ3_BOTCLIP;
7904 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7905 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7906 return nativecontents;
7909 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7914 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7915 node = node->children[1];
7917 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7918 if (loadmodel->brush.num_leafs < numleafs)
7919 loadmodel->brush.num_leafs = numleafs;
7922 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7925 q3dheader_t *header;
7926 float corner[3], yawradius, modelradius;
7928 mod->modeldatatypestring = "Q3BSP";
7930 mod->type = mod_brushq3;
7931 mod->brush.ishlbsp = false;
7932 mod->brush.isbsp2rmqe = false;
7933 mod->brush.isbsp2 = false;
7934 mod->brush.isq2bsp = false;
7935 mod->brush.isq3bsp = true;
7936 mod->brush.skymasking = true;
7937 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7940 header = (q3dheader_t *)buffer;
7941 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7942 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7944 i = LittleLong(header->version);
7945 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7946 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7948 mod->soundfromcenter = true;
7949 mod->TraceBox = Mod_Q3BSP_TraceBox;
7950 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7951 mod->TraceLine = Mod_Q3BSP_TraceLine;
7952 mod->TracePoint = Mod_Q3BSP_TracePoint;
7953 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7954 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7955 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7956 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7957 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7958 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7959 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7960 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7961 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7962 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7963 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7964 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7965 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7966 mod->brush.AmbientSoundLevelsForPoint = NULL;
7967 mod->brush.RoundUpToHullSize = NULL;
7968 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7969 mod->Draw = R_Q1BSP_Draw;
7970 mod->DrawDepth = R_Q1BSP_DrawDepth;
7971 mod->DrawDebug = R_Q1BSP_DrawDebug;
7972 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7973 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7974 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7975 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7976 mod->DrawLight = R_Q1BSP_DrawLight;
7978 mod_base = (unsigned char *)header;
7980 // swap all the lumps
7981 header->ident = LittleLong(header->ident);
7982 header->version = LittleLong(header->version);
7983 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7984 for (i = 0;i < lumps;i++)
7986 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7987 if((char *) bufferend < (char *) buffer + j)
7988 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7989 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7990 if((char *) bufferend < (char *) buffer + j)
7991 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7994 * NO, do NOT clear them!
7995 * they contain actual data referenced by other stuff.
7996 * Instead, before using the advertisements lump, check header->versio
7998 * Sorry, but otherwise it breaks memory of the first lump.
7999 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
8001 header->lumps[i].fileofs = 0;
8002 header->lumps[i].filelen = 0;
8006 mod->brush.qw_md4sum = 0;
8007 mod->brush.qw_md4sum2 = 0;
8008 for (i = 0;i < lumps;i++)
8010 if (i == Q3LUMP_ENTITIES)
8012 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
8013 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
8015 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
8017 // all this checksumming can take a while, so let's send keepalives here too
8018 CL_KeepaliveMessage(false);
8021 // allocate a texture pool if we need it
8022 if (mod->texturepool == NULL)
8023 mod->texturepool = R_AllocTexturePool();
8025 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
8026 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
8027 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
8028 if (header->version == Q3BSPVERSION_IG)
8029 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
8031 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
8032 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
8033 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
8034 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
8035 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
8036 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
8037 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
8038 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
8039 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
8040 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
8041 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
8042 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
8043 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
8044 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
8045 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
8047 // the MakePortals code works fine on the q3bsp data as well
8048 if (mod_bsp_portalize.integer)
8049 Mod_Q1BSP_MakePortals();
8051 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
8052 loadmodel->brush.supportwateralpha = true;
8054 loadmodel->brush.num_leafs = 0;
8055 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
8057 if (loadmodel->brush.numsubmodels)
8058 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8061 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8066 // duplicate the basic information
8067 dpsnprintf(name, sizeof(name), "*%i", i);
8068 mod = Mod_FindName(name, loadmodel->name);
8069 // copy the base model to this one
8071 // rename the clone back to its proper name
8072 strlcpy(mod->name, name, sizeof(mod->name));
8073 mod->brush.parentmodel = loadmodel;
8074 // textures and memory belong to the main model
8075 mod->texturepool = NULL;
8076 mod->mempool = NULL;
8077 mod->brush.GetPVS = NULL;
8078 mod->brush.FatPVS = NULL;
8079 mod->brush.BoxTouchingPVS = NULL;
8080 mod->brush.BoxTouchingLeafPVS = NULL;
8081 mod->brush.BoxTouchingVisibleLeafs = NULL;
8082 mod->brush.FindBoxClusters = NULL;
8083 mod->brush.LightPoint = NULL;
8084 mod->brush.AmbientSoundLevelsForPoint = NULL;
8086 mod->brush.submodel = i;
8087 if (loadmodel->brush.submodels)
8088 loadmodel->brush.submodels[i] = mod;
8090 // make the model surface list (used by shadowing/lighting)
8091 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
8092 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
8093 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
8094 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
8095 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
8096 Mod_MakeSortedSurfaces(mod);
8098 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
8099 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
8100 // enlarge the bounding box to enclose all geometry of this model,
8101 // because q3map2 sometimes lies (mostly to affect the lightgrid),
8102 // which can in turn mess up the farclip (as well as culling when
8103 // outside the level - an unimportant concern)
8105 //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]);
8106 for (j = 0;j < mod->nummodelsurfaces;j++)
8108 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8109 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8111 if (!surface->num_vertices)
8113 for (k = 0;k < surface->num_vertices;k++, v += 3)
8115 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
8116 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
8117 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
8118 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
8119 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
8120 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
8123 //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]);
8124 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8125 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8126 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8127 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8128 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8129 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8130 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8131 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8132 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8133 mod->yawmins[2] = mod->normalmins[2];
8134 mod->yawmaxs[2] = mod->normalmaxs[2];
8135 mod->radius = modelradius;
8136 mod->radius2 = modelradius * modelradius;
8138 // this gets altered below if sky or water is used
8139 mod->DrawSky = NULL;
8140 mod->DrawAddWaterPlanes = NULL;
8142 for (j = 0;j < mod->nummodelsurfaces;j++)
8143 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8145 if (j < mod->nummodelsurfaces)
8146 mod->DrawSky = R_Q1BSP_DrawSky;
8148 for (j = 0;j < mod->nummodelsurfaces;j++)
8149 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8151 if (j < mod->nummodelsurfaces)
8152 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8154 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
8155 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
8157 // generate VBOs and other shared data before cloning submodels
8162 if (mod_q3bsp_sRGBlightmaps.integer)
8164 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
8166 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
8167 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
8168 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
8169 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
8170 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
8172 else // if this is NOT set, regular rendering looks right by this requirement anyway
8175 // we want color 1 to do the same as without sRGB
8176 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
8177 loadmodel->lightmapscale *= 2.476923f; // fixes max level
8180 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
8181 // we need to undo that
8182 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
8186 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);
8189 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
8191 int i = LittleLong(((int *)buffer)[1]);
8192 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
8193 Mod_Q3BSP_Load(mod,buffer, bufferend);
8194 else if (i == Q2BSPVERSION)
8195 Mod_Q2BSP_Load(mod,buffer, bufferend);
8197 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
8200 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
8202 Host_Error("Mod_MAP_Load: not yet implemented");
8205 typedef struct objvertex_s
8216 static unsigned char nobsp_pvs[1] = {1};
8218 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
8220 const char *textbase = (char *)buffer, *text = textbase;
8224 char materialname[MAX_QPATH];
8225 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
8226 int index1, index2, index3;
8227 objvertex_t vfirst, vprev, vcurrent;
8230 int numtriangles = 0;
8231 int maxtriangles = 0;
8232 objvertex_t *vertices = NULL;
8234 int maxtextures = 0, numtextures = 0, textureindex = 0;
8235 int maxv = 0, numv = 1;
8236 int maxvt = 0, numvt = 1;
8237 int maxvn = 0, numvn = 1;
8238 char *texturenames = NULL;
8239 float dist, modelradius, modelyawradius, yawradius;
8240 float *obj_v = NULL;
8241 float *obj_vt = NULL;
8242 float *obj_vn = NULL;
8246 objvertex_t *thisvertex = NULL;
8247 int vertexhashindex;
8248 int *vertexhashtable = NULL;
8249 objvertex_t *vertexhashdata = NULL;
8250 objvertex_t *vdata = NULL;
8251 int vertexhashsize = 0;
8252 int vertexhashcount = 0;
8253 skinfile_t *skinfiles = NULL;
8254 unsigned char *data = NULL;
8255 int *submodelfirstsurface;
8256 msurface_t *tempsurface;
8257 msurface_t *tempsurfaces;
8259 memset(&vfirst, 0, sizeof(vfirst));
8260 memset(&vprev, 0, sizeof(vprev));
8261 memset(&vcurrent, 0, sizeof(vcurrent));
8263 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8265 loadmodel->modeldatatypestring = "OBJ";
8267 loadmodel->type = mod_obj;
8268 loadmodel->soundfromcenter = true;
8269 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
8270 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
8271 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
8272 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
8273 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8274 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
8275 loadmodel->brush.TraceLineOfSight = NULL;
8276 loadmodel->brush.SuperContentsFromNativeContents = NULL;
8277 loadmodel->brush.NativeContentsFromSuperContents = NULL;
8278 loadmodel->brush.GetPVS = NULL;
8279 loadmodel->brush.FatPVS = NULL;
8280 loadmodel->brush.BoxTouchingPVS = NULL;
8281 loadmodel->brush.BoxTouchingLeafPVS = NULL;
8282 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
8283 loadmodel->brush.FindBoxClusters = NULL;
8284 loadmodel->brush.LightPoint = NULL;
8285 loadmodel->brush.FindNonSolidLocation = NULL;
8286 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8287 loadmodel->brush.RoundUpToHullSize = NULL;
8288 loadmodel->brush.PointInLeaf = NULL;
8289 loadmodel->Draw = R_Q1BSP_Draw;
8290 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
8291 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
8292 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
8293 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
8294 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
8295 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
8296 loadmodel->DrawLight = R_Q1BSP_DrawLight;
8298 skinfiles = Mod_LoadSkinFiles();
8299 if (loadmodel->numskins < 1)
8300 loadmodel->numskins = 1;
8302 // make skinscenes for the skins (no groups)
8303 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8304 for (i = 0;i < loadmodel->numskins;i++)
8306 loadmodel->skinscenes[i].firstframe = i;
8307 loadmodel->skinscenes[i].framecount = 1;
8308 loadmodel->skinscenes[i].loop = true;
8309 loadmodel->skinscenes[i].framerate = 10;
8315 // we always have model 0, i.e. the first "submodel"
8316 loadmodel->brush.numsubmodels = 1;
8318 // parse the OBJ text now
8321 static char emptyarg[1] = "";
8326 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8327 line[linelen] = text[linelen];
8329 for (argc = 0;argc < 4;argc++)
8330 argv[argc] = emptyarg;
8333 while (*s == ' ' || *s == '\t')
8343 while (*s == ' ' || *s == '\t')
8353 if (argv[0][0] == '#')
8355 if (!strcmp(argv[0], "v"))
8359 maxv = max(maxv * 2, 1024);
8360 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
8362 if(mod_obj_orientation.integer)
8364 obj_v[numv*3+0] = atof(argv[1]);
8365 obj_v[numv*3+2] = atof(argv[2]);
8366 obj_v[numv*3+1] = atof(argv[3]);
8370 obj_v[numv*3+0] = atof(argv[1]);
8371 obj_v[numv*3+1] = atof(argv[2]);
8372 obj_v[numv*3+2] = atof(argv[3]);
8376 else if (!strcmp(argv[0], "vt"))
8380 maxvt = max(maxvt * 2, 1024);
8381 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
8383 obj_vt[numvt*2+0] = atof(argv[1]);
8384 obj_vt[numvt*2+1] = 1-atof(argv[2]);
8387 else if (!strcmp(argv[0], "vn"))
8391 maxvn = max(maxvn * 2, 1024);
8392 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
8394 if(mod_obj_orientation.integer)
8396 obj_vn[numvn*3+0] = atof(argv[1]);
8397 obj_vn[numvn*3+2] = atof(argv[2]);
8398 obj_vn[numvn*3+1] = atof(argv[3]);
8402 obj_vn[numvn*3+0] = atof(argv[1]);
8403 obj_vn[numvn*3+1] = atof(argv[2]);
8404 obj_vn[numvn*3+2] = atof(argv[3]);
8408 else if (!strcmp(argv[0], "f"))
8412 if (maxtextures <= numtextures)
8414 maxtextures = max(maxtextures * 2, 256);
8415 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8417 textureindex = numtextures++;
8418 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
8420 for (j = 1;j < argc;j++)
8422 index1 = atoi(argv[j]);
8423 while(argv[j][0] && argv[j][0] != '/')
8427 index2 = atoi(argv[j]);
8428 while(argv[j][0] && argv[j][0] != '/')
8432 index3 = atoi(argv[j]);
8433 // negative refers to a recent vertex
8434 // zero means not specified
8435 // positive means an absolute vertex index
8437 index1 = numv - index1;
8439 index2 = numvt - index2;
8441 index3 = numvn - index3;
8442 vcurrent.nextindex = -1;
8443 vcurrent.textureindex = textureindex;
8444 vcurrent.submodelindex = submodelindex;
8445 if (obj_v && index1 >= 0 && index1 < numv)
8446 VectorCopy(obj_v + 3*index1, vcurrent.v);
8447 if (obj_vt && index2 >= 0 && index2 < numvt)
8448 Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
8449 if (obj_vn && index3 >= 0 && index3 < numvn)
8450 VectorCopy(obj_vn + 3*index3, vcurrent.vn);
8451 if (numtriangles == 0)
8453 VectorCopy(vcurrent.v, mins);
8454 VectorCopy(vcurrent.v, maxs);
8458 mins[0] = min(mins[0], vcurrent.v[0]);
8459 mins[1] = min(mins[1], vcurrent.v[1]);
8460 mins[2] = min(mins[2], vcurrent.v[2]);
8461 maxs[0] = max(maxs[0], vcurrent.v[0]);
8462 maxs[1] = max(maxs[1], vcurrent.v[1]);
8463 maxs[2] = max(maxs[2], vcurrent.v[2]);
8469 if (maxtriangles <= numtriangles)
8471 maxtriangles = max(maxtriangles * 2, 32768);
8472 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8474 if(mod_obj_orientation.integer)
8476 vertices[numtriangles*3+0] = vfirst;
8477 vertices[numtriangles*3+1] = vprev;
8478 vertices[numtriangles*3+2] = vcurrent;
8482 vertices[numtriangles*3+0] = vfirst;
8483 vertices[numtriangles*3+2] = vprev;
8484 vertices[numtriangles*3+1] = vcurrent;
8491 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8493 submodelindex = atof(argv[1]);
8494 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8496 else if (!strcmp(argv[0], "usemtl"))
8498 for (i = 0;i < numtextures;i++)
8499 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8501 if (i < numtextures)
8505 if (maxtextures <= numtextures)
8507 maxtextures = max(maxtextures * 2, 256);
8508 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8510 textureindex = numtextures++;
8511 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8516 // now that we have the OBJ data loaded as-is, we can convert it
8518 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8519 VectorCopy(mins, loadmodel->normalmins);
8520 VectorCopy(maxs, loadmodel->normalmaxs);
8521 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8522 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8523 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8524 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8525 modelradius = modelyawradius + modelradius * modelradius;
8526 modelyawradius = sqrt(modelyawradius);
8527 modelradius = sqrt(modelradius);
8528 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8529 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8530 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8531 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8532 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8533 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8534 loadmodel->radius = modelradius;
8535 loadmodel->radius2 = modelradius * modelradius;
8537 // allocate storage for triangles
8538 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8539 // allocate vertex hash structures to build an optimal vertex subset
8540 vertexhashsize = numtriangles*2;
8541 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8542 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8543 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8544 vertexhashcount = 0;
8546 // gather surface stats for assigning vertex/triangle ranges
8550 loadmodel->num_surfaces = 0;
8551 // allocate storage for the worst case number of surfaces, later we resize
8552 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8553 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8554 tempsurface = tempsurfaces;
8555 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8557 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8558 for (textureindex = 0;textureindex < numtextures;textureindex++)
8560 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8562 thisvertex = vertices + vertexindex;
8563 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8566 // skip the surface creation if there are no triangles for it
8567 if (vertexindex == numtriangles*3)
8569 // create a surface for these vertices
8570 surfacevertices = 0;
8571 surfaceelements = 0;
8572 // we hack in a texture index in the surface to be fixed up later...
8573 tempsurface->texture = (texture_t *)((size_t)textureindex);
8574 // calculate bounds as we go
8575 VectorCopy(thisvertex->v, tempsurface->mins);
8576 VectorCopy(thisvertex->v, tempsurface->maxs);
8577 for (;vertexindex < numtriangles*3;vertexindex++)
8579 thisvertex = vertices + vertexindex;
8580 if (thisvertex->submodelindex != submodelindex)
8582 if (thisvertex->textureindex != textureindex)
8584 // add vertex to surface bounds
8585 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8586 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8587 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8588 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8589 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8590 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8591 // add the vertex if it is not found in the merged set, and
8592 // get its index (triangle element) for the surface
8593 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8594 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8596 vdata = vertexhashdata + i;
8597 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8602 i = vertexhashcount++;
8603 vdata = vertexhashdata + i;
8604 *vdata = *thisvertex;
8605 vdata->nextindex = vertexhashtable[vertexhashindex];
8606 vertexhashtable[vertexhashindex] = i;
8609 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8612 surfacetriangles = surfaceelements / 3;
8613 tempsurface->num_vertices = surfacevertices;
8614 tempsurface->num_triangles = surfacetriangles;
8615 tempsurface->num_firstvertex = firstvertex;
8616 tempsurface->num_firsttriangle = firsttriangle;
8617 firstvertex += tempsurface->num_vertices;
8618 firsttriangle += tempsurface->num_triangles;
8620 loadmodel->num_surfaces++;
8623 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8624 numvertices = firstvertex;
8625 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8626 tempsurfaces = NULL;
8628 // allocate storage for final mesh data
8629 loadmodel->num_textures = numtextures * loadmodel->numskins;
8630 loadmodel->num_texturesperskin = numtextures;
8631 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 *));
8632 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
8633 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8634 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8635 loadmodel->surfmesh.num_vertices = numvertices;
8636 loadmodel->surfmesh.num_triangles = numtriangles;
8637 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8638 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8639 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8640 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8641 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8643 if (loadmodel->surfmesh.num_vertices <= 65536) {
8644 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8647 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8649 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8650 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8651 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8654 // load the textures
8655 for (textureindex = 0;textureindex < numtextures;textureindex++)
8656 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8657 Mod_FreeSkinFiles(skinfiles);
8659 // set the surface textures to their real values now that we loaded them...
8660 for (i = 0;i < loadmodel->num_surfaces;i++)
8661 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8665 Mem_Free(texturenames);
8669 Mem_Free(vertexhashtable);
8670 Mem_Free(vertexhashdata);
8672 // compute all the mesh information that was not loaded from the file
8673 if (loadmodel->surfmesh.data_element3s)
8674 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8675 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8676 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8677 // generate normals if the file did not have them
8678 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8679 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);
8680 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);
8682 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8683 loadmodel->brush.num_visleafs = 1;
8684 loadmodel->brush.num_leafs = 1;
8685 loadmodel->brush.num_nodes = 0;
8686 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8687 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8688 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8689 loadmodel->brush.num_pvsclusters = 1;
8690 loadmodel->brush.num_pvsclusterbytes = 1;
8691 loadmodel->brush.data_pvsclusters = nobsp_pvs;
8692 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8693 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8694 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
8695 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8696 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8697 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8698 loadmodel->brush.data_leafs->clusterindex = 0;
8699 loadmodel->brush.data_leafs->areaindex = 0;
8700 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8701 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8702 loadmodel->brush.data_leafs->numleafbrushes = 0;
8703 loadmodel->brush.data_leafs->firstleafbrush = NULL;
8704 loadmodel->brush.supportwateralpha = true;
8706 if (loadmodel->brush.numsubmodels)
8707 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8710 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8715 // duplicate the basic information
8716 dpsnprintf(name, sizeof(name), "*%i", i);
8717 mod = Mod_FindName(name, loadmodel->name);
8718 // copy the base model to this one
8720 // rename the clone back to its proper name
8721 strlcpy(mod->name, name, sizeof(mod->name));
8722 mod->brush.parentmodel = loadmodel;
8723 // textures and memory belong to the main model
8724 mod->texturepool = NULL;
8725 mod->mempool = NULL;
8726 mod->brush.GetPVS = NULL;
8727 mod->brush.FatPVS = NULL;
8728 mod->brush.BoxTouchingPVS = NULL;
8729 mod->brush.BoxTouchingLeafPVS = NULL;
8730 mod->brush.BoxTouchingVisibleLeafs = NULL;
8731 mod->brush.FindBoxClusters = NULL;
8732 mod->brush.LightPoint = NULL;
8733 mod->brush.AmbientSoundLevelsForPoint = NULL;
8735 mod->brush.submodel = i;
8736 if (loadmodel->brush.submodels)
8737 loadmodel->brush.submodels[i] = mod;
8739 // make the model surface list (used by shadowing/lighting)
8740 mod->firstmodelsurface = submodelfirstsurface[i];
8741 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8742 mod->firstmodelbrush = 0;
8743 mod->nummodelbrushes = 0;
8744 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8745 Mod_MakeSortedSurfaces(mod);
8747 VectorClear(mod->normalmins);
8748 VectorClear(mod->normalmaxs);
8750 for (j = 0;j < mod->nummodelsurfaces;j++)
8752 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8753 const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8755 if (!surface->num_vertices)
8760 VectorCopy(v3f, mod->normalmins);
8761 VectorCopy(v3f, mod->normalmaxs);
8763 for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8765 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8766 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8767 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8768 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8769 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8770 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8773 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8774 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8775 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8776 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8777 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8778 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8779 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8780 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8781 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8782 mod->yawmins[2] = mod->normalmins[2];
8783 mod->yawmaxs[2] = mod->normalmaxs[2];
8784 mod->radius = modelradius;
8785 mod->radius2 = modelradius * modelradius;
8787 // this gets altered below if sky or water is used
8788 mod->DrawSky = NULL;
8789 mod->DrawAddWaterPlanes = NULL;
8791 for (j = 0;j < mod->nummodelsurfaces;j++)
8792 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8794 if (j < mod->nummodelsurfaces)
8795 mod->DrawSky = R_Q1BSP_DrawSky;
8797 for (j = 0;j < mod->nummodelsurfaces;j++)
8798 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8800 if (j < mod->nummodelsurfaces)
8801 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8803 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8804 mod->render_bih = mod->collision_bih;
8806 // generate VBOs and other shared data before cloning submodels
8811 Mem_Free(submodelfirstsurface);
8813 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);