2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
30 cvar_t mod_bsp_portalize = {0, "mod_bsp_portalize", "1", "enables portal generation from BSP tree (may take several seconds per map), used by r_drawportals, r_useportalculling, r_shadow_realtime_world_compileportalculling, sv_cullentities_portal"};
31 cvar_t r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
34 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
35 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
38 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
39 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
40 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t r_trippy = {0, "r_trippy", "0", "easter egg"};
42 cvar_t r_fxaa = {CVAR_SAVE, "r_fxaa", "0", "fast approximate anti aliasing"};
43 cvar_t mod_noshader_default_offsetmapping = {CVAR_SAVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
44 cvar_t mod_obj_orientation = {0, "mod_obj_orientation", "1", "fix orientation of OBJ models to the usual conventions (if zero, use coordinates as is)"};
45 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
46 cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
47 cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
48 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
49 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
50 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
51 cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
52 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
53 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
54 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
55 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
56 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
57 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
58 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
59 cvar_t mod_q3shader_force_addalpha = {0, "mod_q3shader_force_addalpha", "0", "treat GL_ONE GL_ONE (or add) blendfunc as GL_SRC_ALPHA GL_ONE for compatibility with older DarkPlaces releases"};
60 cvar_t mod_q3shader_force_terrain_alphaflag = {0, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
62 cvar_t mod_q1bsp_polygoncollisions = {0, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
63 cvar_t mod_collision_bih = {0, "mod_collision_bih", "1", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
64 cvar_t mod_recalculatenodeboxes = {0, "mod_recalculatenodeboxes", "1", "enables use of generated node bounding boxes based on BSP tree portal reconstruction, rather than the node boxes supplied by the map compiler"};
66 static texture_t mod_q1bsp_texture_solid;
67 static texture_t mod_q1bsp_texture_sky;
68 static texture_t mod_q1bsp_texture_lava;
69 static texture_t mod_q1bsp_texture_slime;
70 static texture_t mod_q1bsp_texture_water;
72 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end);
74 void Mod_BrushInit(void)
76 // Cvar_RegisterVariable(&r_subdivide_size);
77 Cvar_RegisterVariable(&mod_bsp_portalize);
78 Cvar_RegisterVariable(&r_novis);
79 Cvar_RegisterVariable(&r_nosurftextures);
80 Cvar_RegisterVariable(&r_subdivisions_tolerance);
81 Cvar_RegisterVariable(&r_subdivisions_mintess);
82 Cvar_RegisterVariable(&r_subdivisions_maxtess);
83 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
84 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
85 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
86 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
87 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
88 Cvar_RegisterVariable(&r_trippy);
89 Cvar_RegisterVariable(&r_fxaa);
90 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
91 Cvar_RegisterVariable(&mod_obj_orientation);
92 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
93 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
94 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
95 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
96 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
97 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
98 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
99 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
100 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
101 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
102 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
103 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
104 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
105 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
106 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
107 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
108 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
109 Cvar_RegisterVariable(&mod_collision_bih);
110 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
112 // these games were made for older DP engines and are no longer
113 // maintained; use this hack to show their textures properly
114 if(gamemode == GAME_NEXUIZ)
115 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
117 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
118 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
119 mod_q1bsp_texture_solid.surfaceflags = 0;
120 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
122 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
123 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
124 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
125 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
127 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
128 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
129 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
130 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
132 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
133 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
134 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
135 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
137 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
138 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
139 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
140 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
143 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
150 // LordHavoc: modified to start at first clip node,
151 // in other words: first node of the (sub)model
152 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
154 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
156 return (mleaf_t *)node;
159 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
163 leaf = Mod_Q1BSP_PointInLeaf(model, p);
166 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
169 memcpy(out, leaf->ambient_sound_level, i);
175 memset(out, 0, outsize);
178 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
181 int nodestackindex = 0;
182 mnode_t *node, *nodestack[1024];
183 if (!model->brush.num_pvsclusters)
185 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
191 // node - recurse down the BSP tree
192 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
196 return -1; // ERROR: NAN bounding box!
197 // box is on one side of plane, take that path
198 node = node->children[sides-1];
202 // box crosses plane, take one path and remember the other
203 if (nodestackindex < 1024)
204 nodestack[nodestackindex++] = node->children[0];
205 node = node->children[1];
211 // leaf - add clusterindex to list
212 if (numclusters < maxclusters)
213 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
217 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
221 if (nodestackindex < 1024)
222 nodestack[nodestackindex++] = node->children[0];
223 node = node->children[1];
228 // leaf - add clusterindex to list
229 if (numclusters < maxclusters)
230 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
235 // try another path we didn't take earlier
236 if (nodestackindex == 0)
238 node = nodestack[--nodestackindex];
240 // return number of clusters found (even if more than the maxclusters)
244 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
246 int nodestackindex = 0;
247 mnode_t *node, *nodestack[1024];
248 if (!model->brush.num_pvsclusters)
250 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
256 // node - recurse down the BSP tree
257 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
261 return -1; // ERROR: NAN bounding box!
262 // box is on one side of plane, take that path
263 node = node->children[sides-1];
267 // box crosses plane, take one path and remember the other
268 if (nodestackindex < 1024)
269 nodestack[nodestackindex++] = node->children[0];
270 node = node->children[1];
276 // leaf - check cluster bit
277 int clusterindex = ((mleaf_t *)node)->clusterindex;
278 if (CHECKPVSBIT(pvs, clusterindex))
280 // it is visible, return immediately with the news
285 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
289 if (nodestackindex < 1024)
290 nodestack[nodestackindex++] = node->children[0];
291 node = node->children[1];
296 // leaf - check cluster bit
297 int clusterindex = ((mleaf_t *)node)->clusterindex;
298 if (CHECKPVSBIT(pvs, clusterindex))
300 // it is visible, return immediately with the news
306 // nothing to see here, try another path we didn't take earlier
307 if (nodestackindex == 0)
309 node = nodestack[--nodestackindex];
315 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
317 int nodestackindex = 0;
318 mnode_t *node, *nodestack[1024];
319 if (!model->brush.num_leafs)
321 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
327 // node - recurse down the BSP tree
328 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
332 return -1; // ERROR: NAN bounding box!
333 // box is on one side of plane, take that path
334 node = node->children[sides-1];
338 // box crosses plane, take one path and remember the other
339 if (nodestackindex < 1024)
340 nodestack[nodestackindex++] = node->children[0];
341 node = node->children[1];
347 // leaf - check cluster bit
348 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
349 if (CHECKPVSBIT(pvs, clusterindex))
351 // it is visible, return immediately with the news
356 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
360 if (nodestackindex < 1024)
361 nodestack[nodestackindex++] = node->children[0];
362 node = node->children[1];
367 // leaf - check cluster bit
368 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
369 if (CHECKPVSBIT(pvs, clusterindex))
371 // it is visible, return immediately with the news
377 // nothing to see here, try another path we didn't take earlier
378 if (nodestackindex == 0)
380 node = nodestack[--nodestackindex];
386 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
388 int nodestackindex = 0;
389 mnode_t *node, *nodestack[1024];
390 if (!model->brush.num_leafs)
392 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
398 // node - recurse down the BSP tree
399 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
403 return -1; // ERROR: NAN bounding box!
404 // box is on one side of plane, take that path
405 node = node->children[sides-1];
409 // box crosses plane, take one path and remember the other
410 if (nodestackindex < 1024)
411 nodestack[nodestackindex++] = node->children[0];
412 node = node->children[1];
418 // leaf - check if it is visible
419 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
421 // it is visible, return immediately with the news
426 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
430 if (nodestackindex < 1024)
431 nodestack[nodestackindex++] = node->children[0];
432 node = node->children[1];
437 // leaf - check if it is visible
438 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
440 // it is visible, return immediately with the news
446 // nothing to see here, try another path we didn't take earlier
447 if (nodestackindex == 0)
449 node = nodestack[--nodestackindex];
455 typedef struct findnonsolidlocationinfo_s
458 vec3_t absmin, absmax;
464 findnonsolidlocationinfo_t;
466 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
469 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
471 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
472 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
473 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
474 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
475 VectorSubtract(vert[1], vert[0], edge[0]);
476 VectorSubtract(vert[2], vert[1], edge[1]);
477 CrossProduct(edge[1], edge[0], facenormal);
478 if (facenormal[0] || facenormal[1] || facenormal[2])
480 VectorNormalize(facenormal);
481 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
482 if (f <= info->bestdist && f >= -info->bestdist)
484 VectorSubtract(vert[0], vert[2], edge[2]);
485 VectorNormalize(edge[0]);
486 VectorNormalize(edge[1]);
487 VectorNormalize(edge[2]);
488 CrossProduct(facenormal, edge[0], edgenormal[0]);
489 CrossProduct(facenormal, edge[1], edgenormal[1]);
490 CrossProduct(facenormal, edge[2], edgenormal[2]);
492 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
493 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
494 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
496 // we got lucky, the center is within the face
497 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
501 if (info->bestdist > dist)
503 info->bestdist = dist;
504 VectorScale(facenormal, (info->radius - -dist), info->nudge);
509 if (info->bestdist > dist)
511 info->bestdist = dist;
512 VectorScale(facenormal, (info->radius - dist), info->nudge);
518 // check which edge or vertex the center is nearest
519 for (i = 0;i < 3;i++)
521 f = DotProduct(info->center, edge[i]);
522 if (f >= DotProduct(vert[0], edge[i])
523 && f <= DotProduct(vert[1], edge[i]))
526 VectorMA(info->center, -f, edge[i], point);
527 dist = sqrt(DotProduct(point, point));
528 if (info->bestdist > dist)
530 info->bestdist = dist;
531 VectorScale(point, (info->radius / dist), info->nudge);
533 // skip both vertex checks
534 // (both are further away than this edge)
539 // not on edge, check first vertex of edge
540 VectorSubtract(info->center, vert[i], point);
541 dist = sqrt(DotProduct(point, point));
542 if (info->bestdist > dist)
544 info->bestdist = dist;
545 VectorScale(point, (info->radius / dist), info->nudge);
554 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
556 int surfacenum, k, *mark;
558 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
560 surface = info->model->data_surfaces + *mark;
561 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
563 if(surface->deprecatedq3num_bboxstride > 0)
566 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
567 for(i = 0; i < cnt; ++i)
569 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
571 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
573 tri = i * surface->deprecatedq3num_bboxstride + k;
574 if(tri >= surface->num_triangles)
576 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
583 for (k = 0;k < surface->num_triangles;k++)
585 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
592 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
596 float f = PlaneDiff(info->center, node->plane);
597 if (f >= -info->bestdist)
598 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
599 if (f <= info->bestdist)
600 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
604 if (((mleaf_t *)node)->numleafsurfaces)
605 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
609 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
612 findnonsolidlocationinfo_t info;
618 VectorCopy(in, info.center);
619 info.radius = radius;
624 VectorClear(info.nudge);
625 info.bestdist = radius;
626 VectorCopy(info.center, info.absmin);
627 VectorCopy(info.center, info.absmax);
628 info.absmin[0] -= info.radius + 1;
629 info.absmin[1] -= info.radius + 1;
630 info.absmin[2] -= info.radius + 1;
631 info.absmax[0] += info.radius + 1;
632 info.absmax[1] += info.radius + 1;
633 info.absmax[2] += info.radius + 1;
634 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
635 VectorAdd(info.center, info.nudge, info.center);
637 while (info.bestdist < radius && ++i < 10);
638 VectorCopy(info.center, out);
641 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
643 switch(nativecontents)
648 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
650 return SUPERCONTENTS_WATER;
652 return SUPERCONTENTS_SLIME;
654 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
656 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
661 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
663 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
664 return CONTENTS_SOLID;
665 if (supercontents & SUPERCONTENTS_SKY)
667 if (supercontents & SUPERCONTENTS_LAVA)
668 return CONTENTS_LAVA;
669 if (supercontents & SUPERCONTENTS_SLIME)
670 return CONTENTS_SLIME;
671 if (supercontents & SUPERCONTENTS_WATER)
672 return CONTENTS_WATER;
673 return CONTENTS_EMPTY;
676 typedef struct RecursiveHullCheckTraceInfo_s
678 // the hull we're tracing through
681 // the trace structure to fill in
684 // start, end, and end - start (in model space)
689 RecursiveHullCheckTraceInfo_t;
691 // 1/32 epsilon to keep floating point happy
692 #define DIST_EPSILON (0.03125)
694 #define HULLCHECKSTATE_EMPTY 0
695 #define HULLCHECKSTATE_SOLID 1
696 #define HULLCHECKSTATE_DONE 2
698 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
700 // status variables, these don't need to be saved on the stack when
701 // recursing... but are because this should be thread-safe
702 // (note: tracing against a bbox is not thread-safe, yet)
707 // variables that need to be stored on the stack when recursing
712 // keep looping until we hit a leaf
715 // find the point distances
716 node = t->hull->clipnodes + num;
717 plane = t->hull->planes + node->planenum;
719 // axial planes can be calculated more quickly without the DotProduct
722 t1 = p1[plane->type] - plane->dist;
723 t2 = p2[plane->type] - plane->dist;
727 t1 = DotProduct (plane->normal, p1) - plane->dist;
728 t2 = DotProduct (plane->normal, p2) - plane->dist;
731 // negative plane distances indicate children[1] (behind plane)
735 // if the line starts and ends on the same side of the plane, recurse
736 // into that child instantly
737 if (p1side == p2side)
739 #if COLLISIONPARANOID >= 3
745 // loop back and process the start child
746 num = node->children[p1side];
750 // find the midpoint where the line crosses the plane, use the
751 // original line for best accuracy
752 #if COLLISIONPARANOID >= 3
757 t1 = t->start[plane->type] - plane->dist;
758 t2 = t->end[plane->type] - plane->dist;
762 t1 = DotProduct (plane->normal, t->start) - plane->dist;
763 t2 = DotProduct (plane->normal, t->end) - plane->dist;
765 midf = t1 / (t1 - t2);
766 midf = bound(p1f, midf, p2f);
767 VectorMA(t->start, midf, t->dist, mid);
769 // we now have a mid point, essentially splitting the line into
770 // the segments in the near child and the far child, we can now
771 // recurse those in order and get their results
773 // recurse both sides, front side first
774 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
775 // if this side is not empty, return what it is (solid or done)
776 if (ret != HULLCHECKSTATE_EMPTY)
779 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
780 // if other side is not solid, return what it is (empty or done)
781 if (ret != HULLCHECKSTATE_SOLID)
784 // front is air and back is solid, this is the impact point...
786 // copy the plane information, flipping it if needed
789 t->trace->plane.dist = -plane->dist;
790 VectorNegate (plane->normal, t->trace->plane.normal);
794 t->trace->plane.dist = plane->dist;
795 VectorCopy (plane->normal, t->trace->plane.normal);
798 // calculate the return fraction which is nudged off the surface a bit
799 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
800 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
801 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
802 t->trace->fraction = bound(0, midf, 1);
804 #if COLLISIONPARANOID >= 3
807 return HULLCHECKSTATE_DONE;
811 // we reached a leaf contents
814 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
815 if (!t->trace->startfound)
817 t->trace->startfound = true;
818 t->trace->startsupercontents |= num;
820 if (num & SUPERCONTENTS_LIQUIDSMASK)
821 t->trace->inwater = true;
823 t->trace->inopen = true;
824 if (num & SUPERCONTENTS_SOLID)
825 t->trace->hittexture = &mod_q1bsp_texture_solid;
826 else if (num & SUPERCONTENTS_SKY)
827 t->trace->hittexture = &mod_q1bsp_texture_sky;
828 else if (num & SUPERCONTENTS_LAVA)
829 t->trace->hittexture = &mod_q1bsp_texture_lava;
830 else if (num & SUPERCONTENTS_SLIME)
831 t->trace->hittexture = &mod_q1bsp_texture_slime;
833 t->trace->hittexture = &mod_q1bsp_texture_water;
834 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
835 t->trace->hitsupercontents = num;
836 if (num & t->trace->hitsupercontentsmask)
838 // if the first leaf is solid, set startsolid
839 if (t->trace->allsolid)
840 t->trace->startsolid = true;
841 #if COLLISIONPARANOID >= 3
844 return HULLCHECKSTATE_SOLID;
848 t->trace->allsolid = false;
849 #if COLLISIONPARANOID >= 3
852 return HULLCHECKSTATE_EMPTY;
856 //#if COLLISIONPARANOID < 2
857 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
860 mclipnode_t *nodes = t->hull->clipnodes;
861 mplane_t *planes = t->hull->planes;
863 VectorCopy(t->start, point);
866 plane = planes + nodes[num].planenum;
867 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
869 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
870 t->trace->startsupercontents |= num;
871 if (num & SUPERCONTENTS_LIQUIDSMASK)
872 t->trace->inwater = true;
874 t->trace->inopen = true;
875 if (num & t->trace->hitsupercontentsmask)
877 t->trace->allsolid = t->trace->startsolid = true;
878 return HULLCHECKSTATE_SOLID;
882 t->trace->allsolid = t->trace->startsolid = false;
883 return HULLCHECKSTATE_EMPTY;
888 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)
890 RecursiveHullCheckTraceInfo_t rhc;
892 memset(&rhc, 0, sizeof(rhc));
893 memset(trace, 0, sizeof(trace_t));
895 rhc.trace->fraction = 1;
896 rhc.trace->allsolid = true;
897 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
898 VectorCopy(start, rhc.start);
899 VectorCopy(start, rhc.end);
900 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
903 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);
905 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)
907 RecursiveHullCheckTraceInfo_t rhc;
909 if (VectorCompare(start, end))
911 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
915 // 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...
916 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
918 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
922 memset(&rhc, 0, sizeof(rhc));
923 memset(trace, 0, sizeof(trace_t));
925 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
926 rhc.trace->fraction = 1;
927 rhc.trace->allsolid = true;
928 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
929 VectorCopy(start, rhc.start);
930 VectorCopy(end, rhc.end);
931 VectorSubtract(rhc.end, rhc.start, rhc.dist);
932 #if COLLISIONPARANOID >= 2
933 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]);
934 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
939 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
940 memset(&testtrace, 0, sizeof(trace_t));
941 rhc.trace = &testtrace;
942 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
943 rhc.trace->fraction = 1;
944 rhc.trace->allsolid = true;
945 VectorCopy(test, rhc.start);
946 VectorCopy(test, rhc.end);
947 VectorClear(rhc.dist);
948 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
949 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
950 if (!trace->startsolid && testtrace.startsolid)
951 Con_Printf(" - ended in solid!\n");
955 if (VectorLength2(rhc.dist))
956 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
958 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
962 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)
964 // this function currently only supports same size start and end
966 RecursiveHullCheckTraceInfo_t rhc;
968 if (VectorCompare(boxmins, boxmaxs))
970 if (VectorCompare(start, end))
971 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
973 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
977 memset(&rhc, 0, sizeof(rhc));
978 memset(trace, 0, sizeof(trace_t));
980 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
981 rhc.trace->fraction = 1;
982 rhc.trace->allsolid = true;
983 VectorSubtract(boxmaxs, boxmins, boxsize);
985 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
986 else if (model->brush.ishlbsp)
988 // LordHavoc: this has to have a minor tolerance (the .1) because of
989 // minor float precision errors from the box being transformed around
990 if (boxsize[0] < 32.1)
992 if (boxsize[2] < 54) // pick the nearest of 36 or 72
993 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
995 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
998 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1002 // LordHavoc: this has to have a minor tolerance (the .1) because of
1003 // minor float precision errors from the box being transformed around
1004 if (boxsize[0] < 32.1)
1005 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1007 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1009 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1010 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1011 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1012 #if COLLISIONPARANOID >= 2
1013 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]);
1014 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1019 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1020 memset(&testtrace, 0, sizeof(trace_t));
1021 rhc.trace = &testtrace;
1022 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1023 rhc.trace->fraction = 1;
1024 rhc.trace->allsolid = true;
1025 VectorCopy(test, rhc.start);
1026 VectorCopy(test, rhc.end);
1027 VectorClear(rhc.dist);
1028 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1029 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1030 if (!trace->startsolid && testtrace.startsolid)
1031 Con_Printf(" - ended in solid!\n");
1035 if (VectorLength2(rhc.dist))
1036 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1038 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1042 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1044 int num = model->brushq1.hulls[0].firstclipnode;
1046 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1047 mplane_t *planes = model->brushq1.hulls[0].planes;
1050 plane = planes + nodes[num].planenum;
1051 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1053 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1056 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 boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1060 colplanef_t cbox_planes[6];
1062 cbox.hasaabbplanes = true;
1063 cbox.supercontents = boxsupercontents;
1066 cbox.numtriangles = 0;
1067 cbox.planes = cbox_planes;
1069 cbox.elements = NULL;
1077 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];
1078 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];
1079 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];
1080 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];
1081 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];
1082 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];
1083 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1084 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1085 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1086 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1087 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1088 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1089 memset(trace, 0, sizeof(trace_t));
1090 trace->hitsupercontentsmask = hitsupercontentsmask;
1091 trace->fraction = 1;
1092 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1094 RecursiveHullCheckTraceInfo_t rhc;
1095 static hull_t box_hull;
1096 static mclipnode_t box_clipnodes[6];
1097 static mplane_t box_planes[6];
1098 // fill in a default trace
1099 memset(&rhc, 0, sizeof(rhc));
1100 memset(trace, 0, sizeof(trace_t));
1101 //To keep everything totally uniform, bounding boxes are turned into small
1102 //BSP trees instead of being compared directly.
1103 // create a temp hull from bounding box sizes
1104 box_planes[0].dist = cmaxs[0] - mins[0];
1105 box_planes[1].dist = cmins[0] - maxs[0];
1106 box_planes[2].dist = cmaxs[1] - mins[1];
1107 box_planes[3].dist = cmins[1] - maxs[1];
1108 box_planes[4].dist = cmaxs[2] - mins[2];
1109 box_planes[5].dist = cmins[2] - maxs[2];
1110 #if COLLISIONPARANOID >= 3
1111 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]);
1114 if (box_hull.clipnodes == NULL)
1118 //Set up the planes and clipnodes so that the six floats of a bounding box
1119 //can just be stored out and get a proper hull_t structure.
1121 box_hull.clipnodes = box_clipnodes;
1122 box_hull.planes = box_planes;
1123 box_hull.firstclipnode = 0;
1124 box_hull.lastclipnode = 5;
1126 for (i = 0;i < 6;i++)
1128 box_clipnodes[i].planenum = i;
1132 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1134 box_clipnodes[i].children[side^1] = i + 1;
1136 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1138 box_planes[i].type = i>>1;
1139 box_planes[i].normal[i>>1] = 1;
1143 // trace a line through the generated clipping hull
1144 //rhc.boxsupercontents = boxsupercontents;
1145 rhc.hull = &box_hull;
1147 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1148 rhc.trace->fraction = 1;
1149 rhc.trace->allsolid = true;
1150 VectorCopy(start, rhc.start);
1151 VectorCopy(end, rhc.end);
1152 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1153 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1154 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1155 if (rhc.trace->startsupercontents)
1156 rhc.trace->startsupercontents = boxsupercontents;
1160 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1162 memset(trace, 0, sizeof(trace_t));
1163 trace->fraction = 1;
1164 if (BoxesOverlap(start, start, cmins, cmaxs))
1166 trace->startsupercontents |= boxsupercontents;
1167 if (hitsupercontentsmask & boxsupercontents)
1169 trace->startsolid = true;
1170 trace->allsolid = true;
1175 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1178 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1179 return trace.fraction == 1;
1182 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)
1186 float mid, distz = endz - startz;
1190 switch (node->plane->type)
1193 node = node->children[x < node->plane->dist];
1194 continue; // loop back and process the new node
1196 node = node->children[y < node->plane->dist];
1197 continue; // loop back and process the new node
1199 side = startz < node->plane->dist;
1200 if ((endz < node->plane->dist) == side)
1202 node = node->children[side];
1203 continue; // loop back and process the new node
1205 // found an intersection
1206 mid = node->plane->dist;
1209 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1210 front += startz * node->plane->normal[2];
1211 back += endz * node->plane->normal[2];
1212 side = front < node->plane->dist;
1213 if ((back < node->plane->dist) == side)
1215 node = node->children[side];
1216 continue; // loop back and process the new node
1218 // found an intersection
1219 mid = startz + distz * (front - node->plane->dist) / (front - back);
1223 // go down front side
1224 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1225 return true; // hit something
1227 // check for impact on this node
1228 if (node->numsurfaces)
1231 int dsi, dti, lmwidth, lmheight;
1233 msurface_t *surface;
1234 unsigned char *lightmap;
1235 int maps, line3, size3;
1238 float scale, w, w00, w01, w10, w11;
1240 surface = model->data_surfaces + node->firstsurface;
1241 for (i = 0;i < node->numsurfaces;i++, surface++)
1243 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1244 continue; // no lightmaps
1246 // location we want to sample in the lightmap
1247 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;
1248 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;
1251 // thanks to jitspoe for pointing out that this int cast was
1252 // rounding toward zero, so we floor it
1253 dsi = (int)floor(ds);
1254 dti = (int)floor(dt);
1255 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1256 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1259 // we have to tolerate a position of lmwidth-1 for some rare
1260 // cases - in which case the sampling position still gets
1261 // clamped but the color gets interpolated to that edge.
1262 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1264 // in the rare cases where we're sampling slightly off
1265 // the polygon, clamp the sampling position (we can still
1266 // interpolate outside it, where it becomes extrapolation)
1271 if (dsi > lmwidth-2)
1273 if (dti > lmheight-2)
1276 // calculate bilinear interpolation factors
1277 // and also multiply by fixedpoint conversion factors to
1278 // compensate for lightmaps being 0-255 (as 0-2), we use
1279 // r_refdef.scene.rtlightstylevalue here which is already
1280 // 0.000-2.148 range
1281 // (if we used r_refdef.scene.lightstylevalue this
1282 // divisor would be 32768 rather than 128)
1285 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1286 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1287 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1288 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1290 // values for pointer math
1291 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1292 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1294 // look up the pixel
1295 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1297 // bilinear filter each lightmap style, and sum them
1298 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1300 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1301 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1302 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1303 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1304 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1308 return true; // success
1313 // go down back side
1314 node = node->children[side ^ 1];
1316 distz = endz - startz;
1317 // loop back and process the new node
1320 // did not hit anything
1324 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1326 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1327 VectorSet(diffusenormal, 0, 0, 1);
1329 if (!model->brushq1.lightdata)
1331 VectorSet(ambientcolor, 1, 1, 1);
1332 VectorSet(diffusecolor, 0, 0, 0);
1336 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);
1339 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1344 const msurface_t *surface;
1349 float edgenormal[3];
1356 surface = model->data_surfaces + node->firstsurface;
1357 for (i = 0;i < node->numsurfaces;i++, surface++)
1359 // skip surfaces whose bounding box does not include the point
1360 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1362 // skip faces with contents we don't care about
1363 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1365 // get the surface normal - since it is flat we know any vertex normal will suffice
1366 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1368 if (DotProduct(t->dist, normal) > 0)
1370 // iterate edges and see if the point is outside one of them
1371 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1373 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1374 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1375 VectorSubtract(v0, v1, edgedir);
1376 CrossProduct(edgedir, normal, edgenormal);
1377 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1380 // if the point is outside one of the edges, it is not within the surface
1381 if (j < surface->num_vertices)
1384 // we hit a surface, this is the impact point...
1385 VectorCopy(normal, t->trace->plane.normal);
1386 t->trace->plane.dist = DotProduct(normal, p);
1388 // calculate the return fraction which is nudged off the surface a bit
1389 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1390 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1391 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1392 t->trace->fraction = bound(0, midf, 1);
1394 t->trace->hittexture = surface->texture->currentframe;
1395 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1396 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1397 return surface->texture->currentframe;
1402 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])
1404 const mplane_t *plane;
1407 double midf, mid[3];
1408 const mleaf_t *leaf;
1412 plane = node->plane;
1413 if (plane->type < 3)
1415 t1 = p1[plane->type] - plane->dist;
1416 t2 = p2[plane->type] - plane->dist;
1420 t1 = DotProduct (plane->normal, p1) - plane->dist;
1421 t2 = DotProduct (plane->normal, p2) - plane->dist;
1427 node = node->children[1];
1436 node = node->children[0];
1442 // the line intersects, find intersection point
1443 // LordHavoc: this uses the original trace for maximum accuracy
1444 if (plane->type < 3)
1446 t1 = t->start[plane->type] - plane->dist;
1447 t2 = t->end[plane->type] - plane->dist;
1451 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1452 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1455 midf = t1 / (t1 - t2);
1456 VectorMA(t->start, midf, t->dist, mid);
1458 // recurse both sides, front side first, return if we hit a surface
1459 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1460 return HULLCHECKSTATE_DONE;
1462 // test each surface on the node
1463 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1464 if (t->trace->hittexture)
1465 return HULLCHECKSTATE_DONE;
1467 // recurse back side
1468 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1470 leaf = (const mleaf_t *)node;
1471 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1472 if (!t->trace->startfound)
1474 t->trace->startfound = true;
1475 t->trace->startsupercontents |= side;
1477 if (side & SUPERCONTENTS_LIQUIDSMASK)
1478 t->trace->inwater = true;
1480 t->trace->inopen = true;
1481 if (side & t->trace->hitsupercontentsmask)
1483 // if the first leaf is solid, set startsolid
1484 if (t->trace->allsolid)
1485 t->trace->startsolid = true;
1486 return HULLCHECKSTATE_SOLID;
1490 t->trace->allsolid = false;
1491 return HULLCHECKSTATE_EMPTY;
1495 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)
1497 RecursiveHullCheckTraceInfo_t rhc;
1499 memset(&rhc, 0, sizeof(rhc));
1500 memset(trace, 0, sizeof(trace_t));
1502 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1503 rhc.trace->fraction = 1;
1504 rhc.trace->allsolid = true;
1505 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1506 VectorCopy(start, rhc.start);
1507 VectorCopy(end, rhc.end);
1508 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1509 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1510 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1513 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1516 unsigned char *outstart = out;
1517 while (out < outend)
1521 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));
1531 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));
1534 for (c = *in++;c > 0;c--)
1538 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));
1549 R_Q1BSP_LoadSplitSky
1551 A sky texture is 256*128, with the right side being a masked overlay
1554 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1559 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1560 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1562 // allocate a texture pool if we need it
1563 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1564 loadmodel->texturepool = R_AllocTexturePool();
1566 if (bytesperpixel == 4)
1568 for (y = 0;y < h;y++)
1570 for (x = 0;x < w;x++)
1572 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1573 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1579 // make an average value for the back to avoid
1580 // a fringe on the top level
1589 for (y = 0;y < h;y++)
1591 for (x = 0;x < w;x++)
1593 p = src[x*width+y+w];
1594 r += palette_rgb[p][0];
1595 g += palette_rgb[p][1];
1596 b += palette_rgb[p][2];
1599 bgra.b[2] = r/(w*h);
1600 bgra.b[1] = g/(w*h);
1601 bgra.b[0] = b/(w*h);
1603 for (y = 0;y < h;y++)
1605 for (x = 0;x < w;x++)
1607 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1609 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1614 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1615 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1616 Mem_Free(solidpixels);
1617 Mem_Free(alphapixels);
1620 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1622 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1623 skinframe_t *skinframe;
1624 texture_t *tx, *tx2, *anims[10], *altanims[10];
1625 texture_t backuptex;
1626 unsigned char *data, *mtdata;
1628 char mapname[MAX_QPATH], name[MAX_QPATH];
1629 unsigned char zeroopaque[4], zerotrans[4];
1632 Vector4Set(zeroopaque, 0, 0, 0, 255);
1633 Vector4Set(zerotrans, 0, 0, 0, 128);
1635 loadmodel->data_textures = NULL;
1637 // add two slots for notexture walls and notexture liquids
1640 nummiptex = MSG_ReadLittleLong(sb);
1641 loadmodel->num_textures = nummiptex + 2;
1642 loadmodel->num_texturesperskin = loadmodel->num_textures;
1646 loadmodel->num_textures = 2;
1647 loadmodel->num_texturesperskin = loadmodel->num_textures;
1650 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1652 // fill out all slots with notexture
1653 if (cls.state != ca_dedicated)
1654 skinframe = R_SkinFrame_LoadMissing();
1657 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1659 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1662 tx->basealpha = 1.0f;
1663 if (cls.state != ca_dedicated)
1665 tx->numskinframes = 1;
1666 tx->skinframerate = 1;
1667 tx->skinframes[0] = skinframe;
1668 tx->currentskinframe = tx->skinframes[0];
1670 tx->basematerialflags = MATERIALFLAG_WALL;
1671 if (i == loadmodel->num_textures - 1)
1673 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1674 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1675 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1679 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1680 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1682 tx->currentframe = tx;
1684 // clear water settings
1687 tx->refractfactor = 1;
1688 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1689 tx->reflectfactor = 1;
1690 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1691 tx->r_water_wateralpha = 1;
1692 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1693 tx->offsetscale = 1;
1695 tx->specularscalemod = 1;
1696 tx->specularpowermod = 1;
1697 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1698 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1699 // JUST GREP FOR "specularscalemod = 1".
1704 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1708 s = loadmodel->name;
1709 if (!strncasecmp(s, "maps/", 5))
1711 FS_StripExtension(s, mapname, sizeof(mapname));
1713 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1714 // LordHavoc: mostly rewritten map texture loader
1715 for (i = 0;i < nummiptex;i++)
1717 doffset = MSG_ReadLittleLong(sb);
1718 if (r_nosurftextures.integer)
1722 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1726 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1728 // copy name, but only up to 16 characters
1729 // (the output buffer can hold more than this, but the input buffer is
1731 for (j = 0;j < 16;j++)
1732 name[j] = MSG_ReadByte(&miptexsb);
1734 // pretty up the buffer (replacing any trailing garbage with 0)
1735 for (j = (int)strlen(name);j < 16;j++)
1740 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1741 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1744 mtwidth = MSG_ReadLittleLong(&miptexsb);
1745 mtheight = MSG_ReadLittleLong(&miptexsb);
1747 j = MSG_ReadLittleLong(&miptexsb);
1751 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1753 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1756 mtdata = miptexsb.data + j;
1759 if ((mtwidth & 15) || (mtheight & 15))
1760 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1762 // LordHavoc: force all names to lowercase
1763 for (j = 0;name[j];j++)
1764 if (name[j] >= 'A' && name[j] <= 'Z')
1765 name[j] += 'a' - 'A';
1767 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1768 backuptex = loadmodel->data_textures[i];
1769 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1771 loadmodel->data_textures[i] = backuptex;
1773 tx = loadmodel->data_textures + i;
1774 strlcpy(tx->name, name, sizeof(tx->name));
1775 tx->width = mtwidth;
1776 tx->height = mtheight;
1777 tx->basealpha = 1.0f;
1779 if (tx->name[0] == '*')
1781 if (!strncmp(tx->name, "*lava", 5))
1783 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1784 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1786 else if (!strncmp(tx->name, "*slime", 6))
1788 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1789 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1793 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1794 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1797 else if (!strncmp(tx->name, "sky", 3))
1799 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1800 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1801 // for the surface traceline we need to hit this surface as a solid...
1802 tx->supercontents |= SUPERCONTENTS_SOLID;
1806 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1807 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1810 if (cls.state != ca_dedicated)
1812 // LordHavoc: HL sky textures are entirely different than quake
1813 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1815 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1817 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1818 if (data && image_width == image_height * 2)
1820 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1823 else if (mtdata != NULL)
1824 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1828 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);
1830 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);
1832 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1835 // did not find external texture, load it from the bsp or wad3
1836 if (loadmodel->brush.ishlbsp)
1838 // internal texture overrides wad
1839 unsigned char *pixels, *freepixels;
1840 pixels = freepixels = NULL;
1842 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1844 pixels = freepixels = W_GetTextureBGRA(tx->name);
1847 tx->width = image_width;
1848 tx->height = image_height;
1849 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1852 Mem_Free(freepixels);
1854 else if (mtdata) // texture included
1855 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1857 // if skinframe is still NULL the "missing" texture will be used
1859 tx->skinframes[0] = skinframe;
1861 // LordHavoc: some Tenebrae textures get replaced by black
1862 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1863 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1864 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1865 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1868 tx->basematerialflags = MATERIALFLAG_WALL;
1869 if (tx->name[0] == '*')
1871 // LordHavoc: some turbulent textures should not be affected by wateralpha
1872 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1873 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1874 else if (!strncmp(tx->name,"*lava",5)
1875 || !strncmp(tx->name,"*teleport",9)
1876 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1877 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1879 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1880 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1881 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1883 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1885 // replace the texture with black
1886 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1888 else if (!strncmp(tx->name, "sky", 3))
1889 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1890 else if (!strcmp(tx->name, "caulk"))
1891 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1892 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1893 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1895 // start out with no animation
1896 tx->currentframe = tx;
1897 tx->currentskinframe = tx->skinframes[0];
1898 tx->currentmaterialflags = tx->basematerialflags;
1901 // sequence the animations
1902 for (i = 0;i < nummiptex;i++)
1904 tx = loadmodel->data_textures + i;
1905 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1907 if (tx->anim_total[0] || tx->anim_total[1])
1908 continue; // already sequenced
1910 // find the number of frames in the animation
1911 memset(anims, 0, sizeof(anims));
1912 memset(altanims, 0, sizeof(altanims));
1914 for (j = i;j < nummiptex;j++)
1916 tx2 = loadmodel->data_textures + j;
1917 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1921 if (num >= '0' && num <= '9')
1922 anims[num - '0'] = tx2;
1923 else if (num >= 'a' && num <= 'j')
1924 altanims[num - 'a'] = tx2;
1926 Con_Printf("Bad animating texture %s\n", tx->name);
1930 for (j = 0;j < 10;j++)
1937 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1940 for (j = 0;j < max;j++)
1944 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1948 for (j = 0;j < altmax;j++)
1952 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1961 // if there is no alternate animation, duplicate the primary
1962 // animation into the alternate
1964 for (k = 0;k < 10;k++)
1965 altanims[k] = anims[k];
1968 // link together the primary animation
1969 for (j = 0;j < max;j++)
1972 tx2->animated = 1; // q1bsp
1973 tx2->anim_total[0] = max;
1974 tx2->anim_total[1] = altmax;
1975 for (k = 0;k < 10;k++)
1977 tx2->anim_frames[0][k] = anims[k];
1978 tx2->anim_frames[1][k] = altanims[k];
1982 // if there really is an alternate anim...
1983 if (anims[0] != altanims[0])
1985 // link together the alternate animation
1986 for (j = 0;j < altmax;j++)
1989 tx2->animated = 1; // q1bsp
1990 // the primary/alternate are reversed here
1991 tx2->anim_total[0] = altmax;
1992 tx2->anim_total[1] = max;
1993 for (k = 0;k < 10;k++)
1995 tx2->anim_frames[0][k] = altanims[k];
1996 tx2->anim_frames[1][k] = anims[k];
2003 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2006 unsigned char *in, *out, *data, d;
2007 char litfilename[MAX_QPATH];
2008 char dlitfilename[MAX_QPATH];
2009 fs_offset_t filesize;
2010 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2012 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2013 for (i = 0;i < sb->cursize;i++)
2014 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2016 else // LordHavoc: bsp version 29 (normal white lighting)
2018 // LordHavoc: hope is not lost yet, check for a .lit file to load
2019 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2020 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2021 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2022 strlcat (litfilename, ".lit", sizeof (litfilename));
2023 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2024 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2027 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2029 i = LittleLong(((int *)data)[1]);
2032 if (developer_loading.integer)
2033 Con_Printf("loaded %s\n", litfilename);
2034 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2035 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2037 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2040 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2042 i = LittleLong(((int *)data)[1]);
2045 if (developer_loading.integer)
2046 Con_Printf("loaded %s\n", dlitfilename);
2047 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2048 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2049 loadmodel->brushq3.deluxemapping_modelspace = false;
2050 loadmodel->brushq3.deluxemapping = true;
2059 Con_Printf("Unknown .lit file version (%d)\n", i);
2061 else if (filesize == 8)
2062 Con_Print("Empty .lit file, ignoring\n");
2064 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2071 // LordHavoc: oh well, expand the white lighting data
2074 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2076 out = loadmodel->brushq1.lightdata;
2077 for (i = 0;i < sb->cursize;i++)
2087 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2089 loadmodel->brushq1.num_compressedpvs = 0;
2090 loadmodel->brushq1.data_compressedpvs = NULL;
2093 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2094 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2095 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2098 // used only for HalfLife maps
2099 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2101 char key[128], value[4096];
2105 if (!COM_ParseToken_Simple(&data, false, false, true))
2107 if (com_token[0] != '{')
2111 if (!COM_ParseToken_Simple(&data, false, false, true))
2113 if (com_token[0] == '}')
2114 break; // end of worldspawn
2115 if (com_token[0] == '_')
2116 strlcpy(key, com_token + 1, sizeof(key));
2118 strlcpy(key, com_token, sizeof(key));
2119 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2120 key[strlen(key)-1] = 0;
2121 if (!COM_ParseToken_Simple(&data, false, false, true))
2123 dpsnprintf(value, sizeof(value), "%s", com_token);
2124 if (!strcmp("wad", key)) // for HalfLife maps
2126 if (loadmodel->brush.ishlbsp)
2129 for (i = 0;i < (int)sizeof(value);i++)
2130 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2134 for (;i < (int)sizeof(value);i++)
2136 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2137 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2139 else if (value[i] == ';' || value[i] == 0)
2143 W_LoadTextureWadFile(&value[j], false);
2155 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2157 loadmodel->brush.entities = NULL;
2160 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2161 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2162 loadmodel->brush.entities[sb->cursize] = 0;
2163 if (loadmodel->brush.ishlbsp)
2164 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2168 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2172 int structsize = 12;
2174 if (sb->cursize % structsize)
2175 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2176 count = sb->cursize / structsize;
2177 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2179 loadmodel->brushq1.vertexes = out;
2180 loadmodel->brushq1.numvertexes = count;
2182 for ( i=0 ; i<count ; i++, out++)
2184 out->position[0] = MSG_ReadLittleFloat(sb);
2185 out->position[1] = MSG_ReadLittleFloat(sb);
2186 out->position[2] = MSG_ReadLittleFloat(sb);
2190 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2194 int structsize = (48+4*hullinfo->filehulls);
2196 if (sb->cursize % structsize)
2197 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2199 count = sb->cursize / structsize;
2200 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2202 loadmodel->brushq1.submodels = out;
2203 loadmodel->brush.numsubmodels = count;
2205 for (i = 0; i < count; i++, out++)
2207 // spread out the mins / maxs by a pixel
2208 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2209 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2210 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2211 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2212 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2213 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2214 out->origin[0] = MSG_ReadLittleFloat(sb);
2215 out->origin[1] = MSG_ReadLittleFloat(sb);
2216 out->origin[2] = MSG_ReadLittleFloat(sb);
2217 for (j = 0; j < hullinfo->filehulls; j++)
2218 out->headnode[j] = MSG_ReadLittleLong(sb);
2219 out->visleafs = MSG_ReadLittleLong(sb);
2220 out->firstface = MSG_ReadLittleLong(sb);
2221 out->numfaces = MSG_ReadLittleLong(sb);
2225 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2229 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2231 if (sb->cursize % structsize)
2232 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2233 count = sb->cursize / structsize;
2234 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2236 loadmodel->brushq1.edges = out;
2237 loadmodel->brushq1.numedges = count;
2239 for ( i=0 ; i<count ; i++, out++)
2241 if (loadmodel->brush.isbsp2)
2243 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2244 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2248 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2249 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2251 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2253 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);
2254 if(!loadmodel->brushq1.numvertexes)
2255 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2263 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2266 int i, j, k, count, miptex;
2267 int structsize = 40;
2269 if (sb->cursize % structsize)
2270 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2271 count = sb->cursize / structsize;
2272 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2274 loadmodel->brushq1.texinfo = out;
2275 loadmodel->brushq1.numtexinfo = count;
2277 for (i = 0;i < count;i++, out++)
2279 for (k = 0;k < 2;k++)
2280 for (j = 0;j < 4;j++)
2281 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2283 miptex = MSG_ReadLittleLong(sb);
2284 out->q1flags = MSG_ReadLittleLong(sb);
2286 if (out->q1flags & TEX_SPECIAL)
2288 // if texture chosen is NULL or the shader needs a lightmap,
2289 // force to notexture water shader
2290 out->textureindex = loadmodel->num_textures - 1;
2294 // if texture chosen is NULL, force to notexture
2295 out->textureindex = loadmodel->num_textures - 2;
2297 // see if the specified miptex is valid and try to use it instead
2298 if (loadmodel->data_textures)
2300 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2301 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2303 out->textureindex = miptex;
2309 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2314 mins[0] = mins[1] = mins[2] = 9999;
2315 maxs[0] = maxs[1] = maxs[2] = -9999;
2317 for (i = 0;i < numverts;i++)
2319 for (j = 0;j < 3;j++, v++)
2329 #define MAX_SUBDIVPOLYTRIANGLES 4096
2330 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2332 static int subdivpolyverts, subdivpolytriangles;
2333 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2334 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2336 static int subdivpolylookupvert(vec3_t v)
2339 for (i = 0;i < subdivpolyverts;i++)
2340 if (subdivpolyvert[i][0] == v[0]
2341 && subdivpolyvert[i][1] == v[1]
2342 && subdivpolyvert[i][2] == v[2])
2344 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2345 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2346 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2347 return subdivpolyverts++;
2350 static void SubdividePolygon(int numverts, float *verts)
2352 int i, i1, i2, i3, f, b, c, p;
2353 vec3_t mins, maxs, front[256], back[256];
2354 float m, *pv, *cv, dist[256], frac;
2357 Host_Error("SubdividePolygon: ran out of verts in buffer");
2359 BoundPoly(numverts, verts, mins, maxs);
2361 for (i = 0;i < 3;i++)
2363 m = (mins[i] + maxs[i]) * 0.5;
2364 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2365 if (maxs[i] - m < 8)
2367 if (m - mins[i] < 8)
2371 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2372 dist[c] = cv[i] - m;
2375 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2379 VectorCopy(pv, front[f]);
2384 VectorCopy(pv, back[b]);
2387 if (dist[p] == 0 || dist[c] == 0)
2389 if ((dist[p] > 0) != (dist[c] > 0) )
2392 frac = dist[p] / (dist[p] - dist[c]);
2393 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2394 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2395 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2401 SubdividePolygon(f, front[0]);
2402 SubdividePolygon(b, back[0]);
2406 i1 = subdivpolylookupvert(verts);
2407 i2 = subdivpolylookupvert(verts + 3);
2408 for (i = 2;i < numverts;i++)
2410 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2412 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2416 i3 = subdivpolylookupvert(verts + i * 3);
2417 subdivpolyindex[subdivpolytriangles][0] = i1;
2418 subdivpolyindex[subdivpolytriangles][1] = i2;
2419 subdivpolyindex[subdivpolytriangles][2] = i3;
2421 subdivpolytriangles++;
2425 //Breaks a polygon up along axial 64 unit
2426 //boundaries so that turbulent and sky warps
2427 //can be done reasonably.
2428 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2434 subdivpolytriangles = 0;
2435 subdivpolyverts = 0;
2436 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2437 if (subdivpolytriangles < 1)
2438 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2440 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2441 mesh->num_vertices = subdivpolyverts;
2442 mesh->num_triangles = subdivpolytriangles;
2443 mesh->vertex = (surfvertex_t *)(mesh + 1);
2444 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2445 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2447 for (i = 0;i < mesh->num_triangles;i++)
2448 for (j = 0;j < 3;j++)
2449 mesh->index[i*3+j] = subdivpolyindex[i][j];
2451 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2453 VectorCopy(subdivpolyvert[i], v->v);
2454 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2455 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2460 extern cvar_t gl_max_lightmapsize;
2461 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2463 msurface_t *surface;
2464 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2465 float texmins[2], texmaxs[2], val;
2466 rtexture_t *lightmaptexture, *deluxemaptexture;
2468 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2470 if (sb->cursize % structsize)
2471 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2472 count = sb->cursize / structsize;
2473 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2474 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2476 loadmodel->num_surfaces = count;
2478 loadmodel->brushq1.firstrender = true;
2479 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2483 for (surfacenum = 0;surfacenum < count;surfacenum++)
2485 if (loadmodel->brush.isbsp2)
2486 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2488 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2489 totalverts += numedges;
2490 totaltris += numedges - 2;
2493 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2495 lightmaptexture = NULL;
2496 deluxemaptexture = r_texture_blanknormalmap;
2498 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2499 totallightmapsamples = 0;
2503 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2505 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2506 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2507 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2508 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2509 firstedge = MSG_ReadLittleLong(sb);
2510 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2511 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2512 for (i = 0;i < MAXLIGHTMAPS;i++)
2513 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2514 lightmapoffset = MSG_ReadLittleLong(sb);
2516 // FIXME: validate edges, texinfo, etc?
2517 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)
2518 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2519 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2520 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2521 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2522 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2524 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2525 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2527 //surface->flags = surface->texture->flags;
2528 //if (LittleShort(in->side))
2529 // surface->flags |= SURF_PLANEBACK;
2530 //surface->plane = loadmodel->brush.data_planes + planenum;
2532 surface->num_firstvertex = totalverts;
2533 surface->num_vertices = numedges;
2534 surface->num_firsttriangle = totaltris;
2535 surface->num_triangles = numedges - 2;
2536 totalverts += numedges;
2537 totaltris += numedges - 2;
2539 // convert edges back to a normal polygon
2540 for (i = 0;i < surface->num_vertices;i++)
2542 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2544 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2546 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2548 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2549 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2550 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2551 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2552 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2553 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2554 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2555 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2558 for (i = 0;i < surface->num_triangles;i++)
2560 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2561 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2562 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2565 // compile additional data about the surface geometry
2566 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);
2567 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);
2568 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2570 // generate surface extents information
2571 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2572 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2573 for (i = 1;i < surface->num_vertices;i++)
2575 for (j = 0;j < 2;j++)
2577 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2578 texmins[j] = min(texmins[j], val);
2579 texmaxs[j] = max(texmaxs[j], val);
2582 for (i = 0;i < 2;i++)
2584 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2585 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2588 smax = surface->lightmapinfo->extents[0] >> 4;
2589 tmax = surface->lightmapinfo->extents[1] >> 4;
2590 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2591 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2594 surface->lightmaptexture = NULL;
2595 surface->deluxemaptexture = r_texture_blanknormalmap;
2596 if (lightmapoffset == -1)
2598 surface->lightmapinfo->samples = NULL;
2600 // give non-lightmapped water a 1x white lightmap
2601 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2603 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2604 surface->lightmapinfo->styles[0] = 0;
2605 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2609 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LordHavoc: HalfLife map (bsp version 30)
2610 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2611 else // LordHavoc: white lighting (bsp version 29)
2613 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2614 if (loadmodel->brushq1.nmaplightdata)
2615 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2618 // check if we should apply a lightmap to this
2619 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2621 if (ssize > 256 || tsize > 256)
2622 Host_Error("Bad surface extents");
2624 if (lightmapsize < ssize)
2625 lightmapsize = ssize;
2626 if (lightmapsize < tsize)
2627 lightmapsize = tsize;
2629 totallightmapsamples += ssize*tsize;
2631 // force lightmap upload on first time seeing the surface
2633 // additionally this is used by the later code to see if a
2634 // lightmap is needed on this surface (rather than duplicating the
2636 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2637 loadmodel->lit = true;
2641 // small maps (such as ammo boxes especially) don't need big lightmap
2642 // textures, so this code tries to guess a good size based on
2643 // totallightmapsamples (size of the lightmaps lump basically), as well as
2644 // trying to max out the size if there is a lot of lightmap data to store
2645 // additionally, never choose a lightmapsize that is smaller than the
2646 // largest surface encountered (as it would fail)
2648 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2651 // now that we've decided the lightmap texture size, we can do the rest
2652 if (cls.state != ca_dedicated)
2654 int stainmapsize = 0;
2655 mod_alloclightmap_state_t allocState;
2657 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2658 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2660 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2661 float u, v, ubase, vbase, uscale, vscale;
2663 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2666 smax = surface->lightmapinfo->extents[0] >> 4;
2667 tmax = surface->lightmapinfo->extents[1] >> 4;
2668 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2669 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2670 stainmapsize += ssize * tsize * 3;
2672 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2674 // allocate a texture pool if we need it
2675 if (loadmodel->texturepool == NULL)
2676 loadmodel->texturepool = R_AllocTexturePool();
2677 // could not find room, make a new lightmap
2678 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2679 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2680 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2681 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);
2682 if (loadmodel->brushq1.nmaplightdata)
2683 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);
2685 Mod_AllocLightmap_Reset(&allocState);
2686 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2688 surface->lightmaptexture = lightmaptexture;
2689 surface->deluxemaptexture = deluxemaptexture;
2690 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2691 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2693 uscale = 1.0f / (float)lightmapsize;
2694 vscale = 1.0f / (float)lightmapsize;
2695 ubase = lightmapx * uscale;
2696 vbase = lightmapy * vscale;
2698 for (i = 0;i < surface->num_vertices;i++)
2700 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);
2701 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);
2702 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2703 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2704 // LordHavoc: calc lightmap data offset for vertex lighting to use
2707 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2711 if (cl_stainmaps.integer)
2713 // allocate stainmaps for permanent marks on walls and clear white
2714 unsigned char *stainsamples = NULL;
2715 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2716 memset(stainsamples, 255, stainmapsize);
2718 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2720 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2722 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2723 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2724 surface->lightmapinfo->stainsamples = stainsamples;
2725 stainsamples += ssize * tsize * 3;
2730 // generate ushort elements array if possible
2731 if (loadmodel->surfmesh.data_element3s)
2732 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2733 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2736 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2739 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2740 node->parent = parent;
2743 // this is a node, recurse to children
2744 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2745 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2746 // combine supercontents of children
2747 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2752 mleaf_t *leaf = (mleaf_t *)node;
2753 // if this is a leaf, calculate supercontents mask from all collidable
2754 // primitives in the leaf (brushes and collision surfaces)
2755 // also flag if the leaf contains any collision surfaces
2756 leaf->combinedsupercontents = 0;
2757 // combine the supercontents values of all brushes in this leaf
2758 for (j = 0;j < leaf->numleafbrushes;j++)
2759 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2760 // check if this leaf contains any collision surfaces (q3 patches)
2761 for (j = 0;j < leaf->numleafsurfaces;j++)
2763 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2764 if (surface->num_collisiontriangles)
2766 leaf->containscollisionsurfaces = true;
2767 leaf->combinedsupercontents |= surface->texture->supercontents;
2773 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2775 int i, j, count, p, child[2];
2777 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2779 if (sb->cursize % structsize)
2780 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2781 count = sb->cursize / structsize;
2783 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2784 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2786 loadmodel->brush.data_nodes = out;
2787 loadmodel->brush.num_nodes = count;
2789 for ( i=0 ; i<count ; i++, out++)
2791 p = MSG_ReadLittleLong(sb);
2792 out->plane = loadmodel->brush.data_planes + p;
2794 if (loadmodel->brush.isbsp2rmqe)
2796 child[0] = MSG_ReadLittleLong(sb);
2797 child[1] = MSG_ReadLittleLong(sb);
2798 out->mins[0] = MSG_ReadLittleShort(sb);
2799 out->mins[1] = MSG_ReadLittleShort(sb);
2800 out->mins[2] = MSG_ReadLittleShort(sb);
2801 out->maxs[0] = MSG_ReadLittleShort(sb);
2802 out->maxs[1] = MSG_ReadLittleShort(sb);
2803 out->maxs[2] = MSG_ReadLittleShort(sb);
2804 out->firstsurface = MSG_ReadLittleLong(sb);
2805 out->numsurfaces = MSG_ReadLittleLong(sb);
2807 else if (loadmodel->brush.isbsp2)
2809 child[0] = MSG_ReadLittleLong(sb);
2810 child[1] = MSG_ReadLittleLong(sb);
2811 out->mins[0] = MSG_ReadLittleFloat(sb);
2812 out->mins[1] = MSG_ReadLittleFloat(sb);
2813 out->mins[2] = MSG_ReadLittleFloat(sb);
2814 out->maxs[0] = MSG_ReadLittleFloat(sb);
2815 out->maxs[1] = MSG_ReadLittleFloat(sb);
2816 out->maxs[2] = MSG_ReadLittleFloat(sb);
2817 out->firstsurface = MSG_ReadLittleLong(sb);
2818 out->numsurfaces = MSG_ReadLittleLong(sb);
2822 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2823 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2824 if (child[0] >= count)
2826 if (child[1] >= count)
2829 out->mins[0] = MSG_ReadLittleShort(sb);
2830 out->mins[1] = MSG_ReadLittleShort(sb);
2831 out->mins[2] = MSG_ReadLittleShort(sb);
2832 out->maxs[0] = MSG_ReadLittleShort(sb);
2833 out->maxs[1] = MSG_ReadLittleShort(sb);
2834 out->maxs[2] = MSG_ReadLittleShort(sb);
2836 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2837 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2840 for (j=0 ; j<2 ; j++)
2842 // LordHavoc: this code supports broken bsp files produced by
2843 // arguire qbsp which can produce more than 32768 nodes, any value
2844 // below count is assumed to be a node number, any other value is
2845 // assumed to be a leaf number
2849 if (p < loadmodel->brush.num_nodes)
2850 out->children[j] = loadmodel->brush.data_nodes + p;
2853 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2854 // map it to the solid leaf
2855 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2860 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2862 if (p < loadmodel->brush.num_leafs)
2863 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2866 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2867 // map it to the solid leaf
2868 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2874 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2877 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2880 int i, j, count, p, firstmarksurface, nummarksurfaces;
2881 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2883 if (sb->cursize % structsize)
2884 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2885 count = sb->cursize / structsize;
2886 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2888 loadmodel->brush.data_leafs = out;
2889 loadmodel->brush.num_leafs = count;
2890 // get visleafs from the submodel data
2891 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2892 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2893 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2894 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2896 // FIXME: this function could really benefit from some error checking
2897 for ( i=0 ; i<count ; i++, out++)
2899 out->contents = MSG_ReadLittleLong(sb);
2901 out->clusterindex = i - 1;
2902 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2903 out->clusterindex = -1;
2905 p = MSG_ReadLittleLong(sb);
2906 // ignore visofs errors on leaf 0 (solid)
2907 if (p >= 0 && out->clusterindex >= 0)
2909 if (p >= loadmodel->brushq1.num_compressedpvs)
2910 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2912 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);
2915 if (loadmodel->brush.isbsp2rmqe)
2917 out->mins[0] = MSG_ReadLittleShort(sb);
2918 out->mins[1] = MSG_ReadLittleShort(sb);
2919 out->mins[2] = MSG_ReadLittleShort(sb);
2920 out->maxs[0] = MSG_ReadLittleShort(sb);
2921 out->maxs[1] = MSG_ReadLittleShort(sb);
2922 out->maxs[2] = MSG_ReadLittleShort(sb);
2924 firstmarksurface = MSG_ReadLittleLong(sb);
2925 nummarksurfaces = MSG_ReadLittleLong(sb);
2927 else if (loadmodel->brush.isbsp2)
2929 out->mins[0] = MSG_ReadLittleFloat(sb);
2930 out->mins[1] = MSG_ReadLittleFloat(sb);
2931 out->mins[2] = MSG_ReadLittleFloat(sb);
2932 out->maxs[0] = MSG_ReadLittleFloat(sb);
2933 out->maxs[1] = MSG_ReadLittleFloat(sb);
2934 out->maxs[2] = MSG_ReadLittleFloat(sb);
2936 firstmarksurface = MSG_ReadLittleLong(sb);
2937 nummarksurfaces = MSG_ReadLittleLong(sb);
2941 out->mins[0] = MSG_ReadLittleShort(sb);
2942 out->mins[1] = MSG_ReadLittleShort(sb);
2943 out->mins[2] = MSG_ReadLittleShort(sb);
2944 out->maxs[0] = MSG_ReadLittleShort(sb);
2945 out->maxs[1] = MSG_ReadLittleShort(sb);
2946 out->maxs[2] = MSG_ReadLittleShort(sb);
2948 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2949 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2952 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2954 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2955 out->numleafsurfaces = nummarksurfaces;
2959 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2960 out->firstleafsurface = NULL;
2961 out->numleafsurfaces = 0;
2964 for (j = 0;j < 4;j++)
2965 out->ambient_sound_level[j] = MSG_ReadByte(sb);
2969 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2973 const unsigned char *pvs;
2974 // if there's no vis data, assume supported (because everything is visible all the time)
2975 if (!loadmodel->brush.data_pvsclusters)
2977 // check all liquid leafs to see if they can see into empty leafs, if any
2978 // can we can assume this map supports r_wateralpha
2979 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2981 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2983 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2984 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2985 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2992 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
2997 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
2999 if (sb->cursize % structsize)
3000 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3001 count = sb->cursize / structsize;
3002 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3004 loadmodel->brushq1.clipnodes = out;
3005 loadmodel->brushq1.numclipnodes = count;
3007 for (i = 1; i < MAX_MAP_HULLS; i++)
3009 hull = &loadmodel->brushq1.hulls[i];
3010 hull->clipnodes = out;
3011 hull->firstclipnode = 0;
3012 hull->lastclipnode = count-1;
3013 hull->planes = loadmodel->brush.data_planes;
3014 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3015 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3016 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3017 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3018 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3019 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3020 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3023 for (i=0 ; i<count ; i++, out++)
3025 out->planenum = MSG_ReadLittleLong(sb);
3026 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3027 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3028 if (loadmodel->brush.isbsp2)
3030 out->children[0] = MSG_ReadLittleLong(sb);
3031 out->children[1] = MSG_ReadLittleLong(sb);
3032 if (out->children[0] >= count)
3033 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3034 if (out->children[1] >= count)
3035 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3039 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3040 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3041 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3042 if (out->children[0] >= count)
3043 out->children[0] -= 65536;
3044 if (out->children[1] >= count)
3045 out->children[1] -= 65536;
3050 //Duplicate the drawing hull structure as a clipping hull
3051 static void Mod_Q1BSP_MakeHull0(void)
3058 hull = &loadmodel->brushq1.hulls[0];
3060 in = loadmodel->brush.data_nodes;
3061 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3063 hull->clipnodes = out;
3064 hull->firstclipnode = 0;
3065 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3066 hull->planes = loadmodel->brush.data_planes;
3068 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3070 out->planenum = in->plane - loadmodel->brush.data_planes;
3071 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3072 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3076 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3079 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3081 if (sb->cursize % structsize)
3082 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3083 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3084 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3086 if (loadmodel->brush.isbsp2)
3088 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3090 j = MSG_ReadLittleLong(sb);
3091 if (j < 0 || j >= loadmodel->num_surfaces)
3092 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3093 loadmodel->brush.data_leafsurfaces[i] = j;
3098 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3100 j = (unsigned short) MSG_ReadLittleShort(sb);
3101 if (j >= loadmodel->num_surfaces)
3102 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3103 loadmodel->brush.data_leafsurfaces[i] = j;
3108 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3113 if (sb->cursize % structsize)
3114 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3115 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3116 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3118 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3119 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3123 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3127 int structsize = 20;
3129 if (sb->cursize % structsize)
3130 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3131 loadmodel->brush.num_planes = sb->cursize / structsize;
3132 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3134 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3136 out->normal[0] = MSG_ReadLittleFloat(sb);
3137 out->normal[1] = MSG_ReadLittleFloat(sb);
3138 out->normal[2] = MSG_ReadLittleFloat(sb);
3139 out->dist = MSG_ReadLittleFloat(sb);
3140 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3145 static void Mod_Q1BSP_LoadMapBrushes(void)
3149 int submodel, numbrushes;
3150 qboolean firstbrush;
3151 char *text, *maptext;
3152 char mapfilename[MAX_QPATH];
3153 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3154 strlcat (mapfilename, ".map", sizeof (mapfilename));
3155 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3159 if (!COM_ParseToken_Simple(&data, false, false, true))
3164 if (!COM_ParseToken_Simple(&data, false, false, true))
3166 if (com_token[0] != '{')
3172 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3175 if (!COM_ParseToken_Simple(&data, false, false, true))
3177 if (com_token[0] == '}')
3178 break; // end of entity
3179 if (com_token[0] == '{')
3186 if (submodel > loadmodel->brush.numsubmodels)
3188 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3192 model = loadmodel->brush.submodels[submodel];
3199 if (!COM_ParseToken_Simple(&data, false, false, true))
3201 if (com_token[0] == '}')
3202 break; // end of brush
3203 // each brush face should be this format:
3204 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3205 // FIXME: support hl .map format
3206 for (pointnum = 0;pointnum < 3;pointnum++)
3208 COM_ParseToken_Simple(&data, false, false, true);
3209 for (componentnum = 0;componentnum < 3;componentnum++)
3211 COM_ParseToken_Simple(&data, false, false, true);
3212 point[pointnum][componentnum] = atof(com_token);
3214 COM_ParseToken_Simple(&data, false, false, true);
3216 COM_ParseToken_Simple(&data, false, false, true);
3217 strlcpy(facetexture, com_token, sizeof(facetexture));
3218 COM_ParseToken_Simple(&data, false, false, true);
3219 //scroll_s = atof(com_token);
3220 COM_ParseToken_Simple(&data, false, false, true);
3221 //scroll_t = atof(com_token);
3222 COM_ParseToken_Simple(&data, false, false, true);
3223 //rotate = atof(com_token);
3224 COM_ParseToken_Simple(&data, false, false, true);
3225 //scale_s = atof(com_token);
3226 COM_ParseToken_Simple(&data, false, false, true);
3227 //scale_t = atof(com_token);
3228 TriangleNormal(point[0], point[1], point[2], planenormal);
3229 VectorNormalizeDouble(planenormal);
3230 planedist = DotProduct(point[0], planenormal);
3231 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3241 #define MAX_PORTALPOINTS 64
3243 typedef struct portal_s
3246 mnode_t *nodes[2]; // [0] = front side of plane
3247 struct portal_s *next[2];
3249 double points[3*MAX_PORTALPOINTS];
3250 struct portal_s *chain; // all portals are linked into a list
3254 static memexpandablearray_t portalarray;
3256 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3258 // process only nodes (leafs already had their box calculated)
3262 // calculate children first
3263 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3264 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3266 // make combined bounding box from children
3267 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3268 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3269 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3270 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3271 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3272 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3275 static void Mod_Q1BSP_FinalizePortals(void)
3277 int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3281 mleaf_t *leaf, *endleaf;
3283 // tally up portal and point counts and recalculate bounding boxes for all
3284 // leafs (because qbsp is very sloppy)
3285 leaf = loadmodel->brush.data_leafs;
3286 endleaf = leaf + loadmodel->brush.num_leafs;
3287 if (mod_recalculatenodeboxes.integer)
3289 for (;leaf < endleaf;leaf++)
3291 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3292 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3297 for (portalindex = 0;portalindex < portalrange;portalindex++)
3299 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3302 // note: this check must match the one below or it will usually corrupt memory
3303 // 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
3304 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3307 numpoints += p->numpoints * 2;
3310 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3311 loadmodel->brush.num_portals = numportals;
3312 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3313 loadmodel->brush.num_portalpoints = numpoints;
3314 // clear all leaf portal chains
3315 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3316 loadmodel->brush.data_leafs[i].portals = NULL;
3317 // process all portals in the global portal chain, while freeing them
3318 portal = loadmodel->brush.data_portals;
3319 point = loadmodel->brush.data_portalpoints;
3320 for (portalindex = 0;portalindex < portalrange;portalindex++)
3322 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3325 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3327 // note: this check must match the one above or it will usually corrupt memory
3328 // 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
3329 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3331 // first make the back to front portal(forward portal)
3332 portal->points = point;
3333 portal->numpoints = p->numpoints;
3334 portal->plane.dist = p->plane.dist;
3335 VectorCopy(p->plane.normal, portal->plane.normal);
3336 portal->here = (mleaf_t *)p->nodes[1];
3337 portal->past = (mleaf_t *)p->nodes[0];
3339 for (j = 0;j < portal->numpoints;j++)
3341 VectorCopy(p->points + j*3, point->position);
3344 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3345 PlaneClassify(&portal->plane);
3347 // link into leaf's portal chain
3348 portal->next = portal->here->portals;
3349 portal->here->portals = portal;
3351 // advance to next portal
3354 // then make the front to back portal(backward portal)
3355 portal->points = point;
3356 portal->numpoints = p->numpoints;
3357 portal->plane.dist = -p->plane.dist;
3358 VectorNegate(p->plane.normal, portal->plane.normal);
3359 portal->here = (mleaf_t *)p->nodes[0];
3360 portal->past = (mleaf_t *)p->nodes[1];
3362 for (j = portal->numpoints - 1;j >= 0;j--)
3364 VectorCopy(p->points + j*3, point->position);
3367 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3368 PlaneClassify(&portal->plane);
3370 // link into leaf's portal chain
3371 portal->next = portal->here->portals;
3372 portal->here->portals = portal;
3374 // advance to next portal
3377 // add the portal's polygon points to the leaf bounding boxes
3378 if (mod_recalculatenodeboxes.integer)
3380 for (i = 0;i < 2;i++)
3382 leaf = (mleaf_t *)p->nodes[i];
3383 for (j = 0;j < p->numpoints;j++)
3385 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3386 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3387 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3388 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3389 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3390 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3396 // now recalculate the node bounding boxes from the leafs
3397 if (mod_recalculatenodeboxes.integer)
3398 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3406 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3409 Host_Error("AddPortalToNodes: NULL front node");
3411 Host_Error("AddPortalToNodes: NULL back node");
3412 if (p->nodes[0] || p->nodes[1])
3413 Host_Error("AddPortalToNodes: already included");
3414 // 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
3416 p->nodes[0] = front;
3417 p->next[0] = (portal_t *)front->portals;
3418 front->portals = (mportal_t *)p;
3421 p->next[1] = (portal_t *)back->portals;
3422 back->portals = (mportal_t *)p;
3427 RemovePortalFromNode
3430 static void RemovePortalFromNodes(portal_t *portal)
3434 void **portalpointer;
3436 for (i = 0;i < 2;i++)
3438 node = portal->nodes[i];
3440 portalpointer = (void **) &node->portals;
3443 t = (portal_t *)*portalpointer;
3445 Host_Error("RemovePortalFromNodes: portal not in leaf");
3449 if (portal->nodes[0] == node)
3451 *portalpointer = portal->next[0];
3452 portal->nodes[0] = NULL;
3454 else if (portal->nodes[1] == node)
3456 *portalpointer = portal->next[1];
3457 portal->nodes[1] = NULL;
3460 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3464 if (t->nodes[0] == node)
3465 portalpointer = (void **) &t->next[0];
3466 else if (t->nodes[1] == node)
3467 portalpointer = (void **) &t->next[1];
3469 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3474 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3475 static double *portalpointsbuffer;
3476 static int portalpointsbufferoffset;
3477 static int portalpointsbuffersize;
3478 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3481 mnode_t *front, *back, *other_node;
3482 mplane_t clipplane, *plane;
3483 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3484 int numfrontpoints, numbackpoints;
3485 double *frontpoints, *backpoints;
3487 // if a leaf, we're done
3491 // get some space for our clipping operations to use
3492 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3494 portalpointsbuffersize = portalpointsbufferoffset * 2;
3495 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3497 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3498 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3499 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3500 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3502 plane = node->plane;
3504 front = node->children[0];
3505 back = node->children[1];
3507 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3509 // create the new portal by generating a polygon for the node plane,
3510 // and clipping it by all of the other portals(which came from nodes above this one)
3511 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3512 nodeportal->plane = *plane;
3514 // 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)
3515 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);
3516 nodeportal->numpoints = 4;
3517 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3518 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3520 clipplane = portal->plane;
3521 if (portal->nodes[0] == portal->nodes[1])
3522 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3523 if (portal->nodes[0] == node)
3525 else if (portal->nodes[1] == node)
3527 clipplane.dist = -clipplane.dist;
3528 VectorNegate(clipplane.normal, clipplane.normal);
3533 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3534 side = 0; // hush warning
3537 for (i = 0;i < nodeportal->numpoints*3;i++)
3538 frontpoints[i] = nodeportal->points[i];
3539 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);
3540 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3544 if (nodeportal->numpoints < 3)
3546 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3547 nodeportal->numpoints = 0;
3549 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3551 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3552 nodeportal->numpoints = 0;
3555 AddPortalToNodes(nodeportal, front, back);
3557 // split the portals of this node along this node's plane and assign them to the children of this node
3558 // (migrating the portals downward through the tree)
3559 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3561 if (portal->nodes[0] == portal->nodes[1])
3562 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3563 if (portal->nodes[0] == node)
3565 else if (portal->nodes[1] == node)
3569 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3570 side = 0; // hush warning
3572 nextportal = portal->next[side];
3573 if (!portal->numpoints)
3576 other_node = portal->nodes[!side];
3577 RemovePortalFromNodes(portal);
3579 // cut the portal into two portals, one on each side of the node plane
3580 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);
3582 if (!numfrontpoints)
3585 AddPortalToNodes(portal, back, other_node);
3587 AddPortalToNodes(portal, other_node, back);
3593 AddPortalToNodes(portal, front, other_node);
3595 AddPortalToNodes(portal, other_node, front);
3599 // the portal is split
3600 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3601 temp = splitportal->chain;
3602 *splitportal = *portal;
3603 splitportal->chain = temp;
3604 for (i = 0;i < numbackpoints*3;i++)
3605 splitportal->points[i] = backpoints[i];
3606 splitportal->numpoints = numbackpoints;
3607 for (i = 0;i < numfrontpoints*3;i++)
3608 portal->points[i] = frontpoints[i];
3609 portal->numpoints = numfrontpoints;
3613 AddPortalToNodes(portal, front, other_node);
3614 AddPortalToNodes(splitportal, back, other_node);
3618 AddPortalToNodes(portal, other_node, front);
3619 AddPortalToNodes(splitportal, other_node, back);
3623 Mod_Q1BSP_RecursiveNodePortals(front);
3624 Mod_Q1BSP_RecursiveNodePortals(back);
3626 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3629 static void Mod_Q1BSP_MakePortals(void)
3631 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3632 portalpointsbufferoffset = 0;
3633 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3634 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3635 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3636 Mem_Free(portalpointsbuffer);
3637 portalpointsbuffer = NULL;
3638 portalpointsbufferoffset = 0;
3639 portalpointsbuffersize = 0;
3640 Mod_Q1BSP_FinalizePortals();
3641 Mem_ExpandableArray_FreeArray(&portalarray);
3644 //Returns PVS data for a given point
3645 //(note: can return NULL)
3646 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3649 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3651 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3652 if (((mleaf_t *)node)->clusterindex >= 0)
3653 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3658 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)
3662 float d = PlaneDiff(org, node->plane);
3664 node = node->children[0];
3665 else if (d < -radius)
3666 node = node->children[1];
3669 // go down both sides
3670 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3671 node = node->children[1];
3674 // if this leaf is in a cluster, accumulate the pvs bits
3675 if (((mleaf_t *)node)->clusterindex >= 0)
3678 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3679 for (i = 0;i < pvsbytes;i++)
3680 pvsbuffer[i] |= pvs[i];
3684 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3685 //of the given point.
3686 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3688 int bytes = model->brush.num_pvsclusterbytes;
3689 bytes = min(bytes, pvsbufferlength);
3690 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3692 memset(pvsbuffer, 0xFF, bytes);
3696 memset(pvsbuffer, 0, bytes);
3697 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3701 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3706 VectorSubtract(inmaxs, inmins, size);
3707 if (cmodel->brush.ishlbsp)
3710 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3711 else if (size[0] <= 32)
3713 if (size[2] < 54) // pick the nearest of 36 or 72
3714 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3716 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3719 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3724 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3725 else if (size[0] <= 32)
3726 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3728 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3730 VectorCopy(inmins, outmins);
3731 VectorAdd(inmins, hull->clip_size, outmaxs);
3734 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3737 int numshadowmeshtriangles = 0;
3738 msurface_t *surface;
3739 if (cls.state == ca_dedicated)
3741 // make a single combined shadow mesh to allow optimized shadow volume creation
3743 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3745 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3746 numshadowmeshtriangles += surface->num_triangles;
3748 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3749 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3750 if (surface->num_triangles > 0)
3751 Mod_ShadowMesh_AddMesh(mod->mempool, mod->brush.shadowmesh, NULL, NULL, NULL, mod->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
3752 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3753 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3754 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3756 return numshadowmeshtriangles;
3759 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);
3761 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3764 sizebuf_t lumpsb[HEADER_LUMPS];
3766 float dist, modelyawradius, modelradius;
3767 msurface_t *surface;
3768 hullinfo_t hullinfo;
3769 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3770 model_brush_lightstyleinfo_t styleinfo[256];
3771 unsigned char *datapointer;
3774 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3776 mod->type = mod_brushq1;
3778 mod->brush.isbsp2 = false;
3779 mod->brush.ishlbsp = false;
3780 mod->brush.isq2bsp = false;
3781 i = MSG_ReadLittleLong(&sb);
3785 mod->modeldatatypestring = "Q1BSP";
3788 mod->brush.ishlbsp = true;
3789 mod->modeldatatypestring = "HLBSP";
3791 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3792 mod->brush.isbsp2 = true;
3793 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3794 mod->modeldatatypestring = "Q1BSP2rmqe";
3796 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3797 mod->brush.isbsp2 = true;
3798 mod->modeldatatypestring = "Q1BSP2";
3801 mod->modeldatatypestring = "Unknown BSP";
3802 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);
3806 // fill in hull info
3807 VectorClear (hullinfo.hullsizes[0][0]);
3808 VectorClear (hullinfo.hullsizes[0][1]);
3809 if (mod->brush.ishlbsp)
3811 hullinfo.filehulls = 4;
3812 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3813 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3814 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3815 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3816 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3817 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3821 hullinfo.filehulls = 4;
3822 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3823 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3824 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3825 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3829 for (i = 0; i < HEADER_LUMPS; i++)
3831 int offset = MSG_ReadLittleLong(&sb);
3832 int size = MSG_ReadLittleLong(&sb);
3833 if (offset < 0 || offset + size > sb.cursize)
3834 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);
3835 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3838 mod->soundfromcenter = true;
3839 mod->TraceBox = Mod_Q1BSP_TraceBox;
3840 mod->TraceLine = Mod_Q1BSP_TraceLine;
3841 mod->TracePoint = Mod_Q1BSP_TracePoint;
3842 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3843 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3844 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3845 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3846 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3847 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3848 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3849 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3850 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3851 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3852 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3853 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3854 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3855 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3856 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3857 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3858 mod->Draw = R_Q1BSP_Draw;
3859 mod->DrawDepth = R_Q1BSP_DrawDepth;
3860 mod->DrawDebug = R_Q1BSP_DrawDebug;
3861 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3862 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3863 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3864 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3865 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3866 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3867 mod->DrawLight = R_Q1BSP_DrawLight;
3871 mod->brush.qw_md4sum = 0;
3872 mod->brush.qw_md4sum2 = 0;
3873 for (i = 0;i < HEADER_LUMPS;i++)
3876 if (i == LUMP_ENTITIES)
3878 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3879 mod->brush.qw_md4sum ^= LittleLong(temp);
3880 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3882 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3885 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3886 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3887 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3888 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3889 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3890 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3891 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3892 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3893 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3894 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3895 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3896 // load submodels before leafs because they contain the number of vis leafs
3897 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3898 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3899 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3900 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3902 for (i = 0; i < HEADER_LUMPS; i++)
3903 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3904 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3906 // check if the map supports transparent water rendering
3907 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3909 // we don't need the compressed pvs data anymore
3910 if (mod->brushq1.data_compressedpvs)
3911 Mem_Free(mod->brushq1.data_compressedpvs);
3912 mod->brushq1.data_compressedpvs = NULL;
3913 mod->brushq1.num_compressedpvs = 0;
3915 Mod_Q1BSP_MakeHull0();
3916 if (mod_bsp_portalize.integer)
3917 Mod_Q1BSP_MakePortals();
3919 mod->numframes = 2; // regular and alternate animation
3922 // make a single combined shadow mesh to allow optimized shadow volume creation
3923 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3925 if (loadmodel->brush.numsubmodels)
3926 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3928 // LordHavoc: to clear the fog around the original quake submodel code, I
3930 // first of all, some background info on the submodels:
3931 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3932 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3933 // now the weird for loop itself:
3934 // the loop functions in an odd way, on each iteration it sets up the
3935 // current 'mod' model (which despite the confusing code IS the model of
3936 // the number i), at the end of the loop it duplicates the model to become
3937 // the next submodel, and loops back to set up the new submodel.
3939 // LordHavoc: now the explanation of my sane way (which works identically):
3940 // set up the world model, then on each submodel copy from the world model
3941 // and set up the submodel with the respective model info.
3942 totalstylesurfaces = 0;
3944 for (i = 0;i < mod->brush.numsubmodels;i++)
3946 memset(stylecounts, 0, sizeof(stylecounts));
3947 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3949 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3950 for (j = 0;j < MAXLIGHTMAPS;j++)
3951 stylecounts[surface->lightmapinfo->styles[j]]++;
3953 for (k = 0;k < 255;k++)
3957 totalstylesurfaces += stylecounts[k];
3960 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3961 for (i = 0;i < mod->brush.numsubmodels;i++)
3963 // LordHavoc: this code was originally at the end of this loop, but
3964 // has been transformed to something more readable at the start here.
3969 // duplicate the basic information
3970 dpsnprintf(name, sizeof(name), "*%i", i);
3971 mod = Mod_FindName(name, loadmodel->name);
3972 // copy the base model to this one
3974 // rename the clone back to its proper name
3975 strlcpy(mod->name, name, sizeof(mod->name));
3976 mod->brush.parentmodel = loadmodel;
3977 // textures and memory belong to the main model
3978 mod->texturepool = NULL;
3979 mod->mempool = NULL;
3980 mod->brush.GetPVS = NULL;
3981 mod->brush.FatPVS = NULL;
3982 mod->brush.BoxTouchingPVS = NULL;
3983 mod->brush.BoxTouchingLeafPVS = NULL;
3984 mod->brush.BoxTouchingVisibleLeafs = NULL;
3985 mod->brush.FindBoxClusters = NULL;
3986 mod->brush.LightPoint = NULL;
3987 mod->brush.AmbientSoundLevelsForPoint = NULL;
3990 mod->brush.submodel = i;
3992 if (loadmodel->brush.submodels)
3993 loadmodel->brush.submodels[i] = mod;
3995 bm = &mod->brushq1.submodels[i];
3997 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3998 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4000 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4001 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4004 mod->firstmodelsurface = bm->firstface;
4005 mod->nummodelsurfaces = bm->numfaces;
4007 // set node/leaf parents for this submodel
4008 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4010 // make the model surface list (used by shadowing/lighting)
4011 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4012 Mod_MakeSortedSurfaces(mod);
4014 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4015 // (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)
4016 VectorCopy(bm->mins, mod->normalmins);
4017 VectorCopy(bm->maxs, mod->normalmaxs);
4018 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4019 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4020 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4021 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4022 modelradius = modelyawradius + modelradius * modelradius;
4023 modelyawradius = sqrt(modelyawradius);
4024 modelradius = sqrt(modelradius);
4025 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4026 mod->yawmins[2] = mod->normalmins[2];
4027 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4028 mod->yawmaxs[2] = mod->normalmaxs[2];
4029 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4030 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4031 mod->radius = modelradius;
4032 mod->radius2 = modelradius * modelradius;
4034 // this gets altered below if sky or water is used
4035 mod->DrawSky = NULL;
4036 mod->DrawAddWaterPlanes = NULL;
4038 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4039 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4040 if (mod->nummodelsurfaces)
4042 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4043 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4045 if (j < mod->nummodelsurfaces)
4046 mod->DrawSky = R_Q1BSP_DrawSky;
4048 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4049 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4051 if (j < mod->nummodelsurfaces)
4052 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4054 // build lightstyle update chains
4055 // (used to rapidly mark lightmapupdateflags on many surfaces
4056 // when d_lightstylevalue changes)
4057 memset(stylecounts, 0, sizeof(stylecounts));
4058 for (k = 0;k < mod->nummodelsurfaces;k++)
4060 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4061 for (j = 0;j < MAXLIGHTMAPS;j++)
4062 stylecounts[surface->lightmapinfo->styles[j]]++;
4064 mod->brushq1.num_lightstyles = 0;
4065 for (k = 0;k < 255;k++)
4069 styleinfo[mod->brushq1.num_lightstyles].style = k;
4070 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4071 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4072 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4073 remapstyles[k] = mod->brushq1.num_lightstyles;
4074 mod->brushq1.num_lightstyles++;
4077 for (k = 0;k < mod->nummodelsurfaces;k++)
4079 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4080 for (j = 0;j < MAXLIGHTMAPS;j++)
4082 if (surface->lightmapinfo->styles[j] != 255)
4084 int r = remapstyles[surface->lightmapinfo->styles[j]];
4085 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4089 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4090 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4094 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4095 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4097 //mod->brushq1.num_visleafs = bm->visleafs;
4099 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4100 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4102 if (mod_q1bsp_polygoncollisions.integer)
4104 mod->collision_bih = mod->render_bih;
4105 // point traces and contents checks still use the bsp tree
4106 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4107 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4108 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4109 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4112 // generate VBOs and other shared data before cloning submodels
4116 Mod_Q1BSP_LoadMapBrushes();
4117 //Mod_Q1BSP_ProcessLightList();
4121 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);
4124 int Mod_Q2BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
4126 int supercontents = 0;
4127 if (nativecontents & CONTENTSQ2_SOLID)
4128 supercontents |= SUPERCONTENTS_SOLID;
4129 if (nativecontents & CONTENTSQ2_WATER)
4130 supercontents |= SUPERCONTENTS_WATER;
4131 if (nativecontents & CONTENTSQ2_SLIME)
4132 supercontents |= SUPERCONTENTS_SLIME;
4133 if (nativecontents & CONTENTSQ2_LAVA)
4134 supercontents |= SUPERCONTENTS_LAVA;
4135 if (nativecontents & CONTENTSQ2_MONSTER)
4136 supercontents |= SUPERCONTENTS_BODY;
4137 if (nativecontents & CONTENTSQ2_DEADMONSTER)
4138 supercontents |= SUPERCONTENTS_CORPSE;
4139 if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4140 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4141 if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4142 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4143 if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4144 supercontents |= SUPERCONTENTS_OPAQUE;
4145 return supercontents;
4148 int Mod_Q2BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
4150 int nativecontents = 0;
4151 if (supercontents & SUPERCONTENTS_SOLID)
4152 nativecontents |= CONTENTSQ2_SOLID;
4153 if (supercontents & SUPERCONTENTS_WATER)
4154 nativecontents |= CONTENTSQ2_WATER;
4155 if (supercontents & SUPERCONTENTS_SLIME)
4156 nativecontents |= CONTENTSQ2_SLIME;
4157 if (supercontents & SUPERCONTENTS_LAVA)
4158 nativecontents |= CONTENTSQ2_LAVA;
4159 if (supercontents & SUPERCONTENTS_BODY)
4160 nativecontents |= CONTENTSQ2_MONSTER;
4161 if (supercontents & SUPERCONTENTS_CORPSE)
4162 nativecontents |= CONTENTSQ2_DEADMONSTER;
4163 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4164 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4165 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4166 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4167 if (!(supercontents & SUPERCONTENTS_OPAQUE))
4168 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4169 return nativecontents;
4172 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4175 loadmodel->brushq1.num_compressedpvs = 0;
4176 loadmodel->brushq1.data_compressedpvs = NULL;
4177 loadmodel->brush.num_pvsclusters = 0;
4178 loadmodel->brush.num_pvsclusterbytes = 0;
4179 loadmodel->brush.data_pvsclusters = NULL;
4184 count = MSG_ReadLittleLong(sb);
4185 loadmodel->brush.num_pvsclusters = count;
4186 loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4187 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4188 for (i = 0;i < count;i++)
4190 int pvsofs = MSG_ReadLittleLong(sb);
4191 /*int phsofs = */MSG_ReadLittleLong(sb);
4192 // decompress the vis data for this cluster
4193 // (note this accesses the underlying data store of sb, which is kind of evil)
4194 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);
4196 // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4197 sb->readcount = sb->cursize;
4200 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4202 int i, j, count, p, child[2];
4204 int structsize = 28;
4206 if (sb->cursize % structsize)
4207 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4208 count = sb->cursize / structsize;
4210 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4211 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4213 loadmodel->brush.data_nodes = out;
4214 loadmodel->brush.num_nodes = count;
4216 for ( i=0 ; i<count ; i++, out++)
4218 p = MSG_ReadLittleLong(sb);
4219 out->plane = loadmodel->brush.data_planes + p;
4220 child[0] = MSG_ReadLittleLong(sb);
4221 child[1] = MSG_ReadLittleLong(sb);
4222 out->mins[0] = MSG_ReadLittleShort(sb);
4223 out->mins[1] = MSG_ReadLittleShort(sb);
4224 out->mins[2] = MSG_ReadLittleShort(sb);
4225 out->maxs[0] = MSG_ReadLittleShort(sb);
4226 out->maxs[1] = MSG_ReadLittleShort(sb);
4227 out->maxs[2] = MSG_ReadLittleShort(sb);
4228 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4229 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4230 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4232 Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", p, out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4233 out->firstsurface = 0;
4234 out->numsurfaces = 0;
4236 for (j=0 ; j<2 ; j++)
4241 if (p < loadmodel->brush.num_nodes)
4242 out->children[j] = loadmodel->brush.data_nodes + p;
4245 Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4246 // map it to the solid leaf
4247 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4252 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4254 if (p < loadmodel->brush.num_leafs)
4255 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4258 Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4259 // map it to the solid leaf
4260 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4266 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
4269 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4273 int structsize = 76;
4274 int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4275 char filename[MAX_QPATH];
4277 if (sb->cursize % structsize)
4278 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4279 count = sb->cursize / structsize;
4280 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4281 loadmodel->brushq1.texinfo = out;
4282 loadmodel->brushq1.numtexinfo = count;
4283 loadmodel->num_texturesperskin = 0;
4284 loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4286 for (i = 0;i < count;i++, out++)
4288 for (k = 0;k < 2;k++)
4289 for (j = 0;j < 4;j++)
4290 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4292 out->q2flags = MSG_ReadLittleLong(sb);
4293 out->q2value = MSG_ReadLittleLong(sb);
4294 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4295 out->q2texture[31] = 0; // make absolutely sure it is terminated
4296 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4298 // find an existing match for the texture if possible
4299 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4300 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4301 if (!strcmp(filename, loadmodel->data_textures[j].name) && out->q2flags == loadmodel->data_textures[j].q2flags)
4303 // if we don't find the texture, store the new texture
4304 if (j == loadmodel->num_texturesperskin)
4306 if (loadmodel->num_texturesperskin < maxtextures)
4308 texture_t *tx = loadmodel->data_textures + j;
4309 int q2flags = out->q2flags;
4310 Mod_LoadTextureFromQ3Shader(tx, filename, true, true, MATERIALFLAG_WALL);
4311 tx->q2flags = q2flags; // override the flags from the wal
4312 // also modify the texture to have the correct contents and such based on flags
4313 // note that we create multiple texture_t structures if q2flags differs
4314 if (q2flags & Q2SURF_LIGHT)
4316 // doesn't mean anything to us
4318 if (q2flags & Q2SURF_SLICK)
4320 // would be nice to support...
4322 if (q2flags & Q2SURF_SKY)
4324 // sky is a rather specific thing
4325 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
4326 tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4327 tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4329 if (q2flags & Q2SURF_WARP)
4331 // we use a scroll instead of a warp
4332 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL;
4333 // if it's also transparent, we can enable the WATERSHADER
4334 // but we do not set the WATERALPHA flag because we don't
4335 // want to honor r_wateralpha in q2bsp
4336 // (it would go against the artistic intent)
4337 if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4338 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4340 if (q2flags & Q2SURF_TRANS33)
4342 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4343 tx->basealpha = 0.3333f;
4345 if (q2flags & Q2SURF_TRANS66)
4347 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4348 tx->basealpha = 0.6667f;
4350 if (q2flags & Q2SURF_FLOWING)
4352 tx->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4353 tx->tcmods[0].parms[0] = -1.6f;
4354 tx->tcmods[0].parms[1] = 0.0f;
4356 if (q2flags & Q2SURF_NODRAW)
4358 tx->basematerialflags |= MATERIALFLAG_NODRAW;
4360 loadmodel->num_texturesperskin++;
4361 loadmodel->num_textures = loadmodel->num_texturesperskin;
4365 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4366 j = 0; // use first texture and give up
4369 // store the index we found for this texture
4370 out->textureindex = j;
4373 // realloc the textures array now that we know how many we actually need
4374 loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4376 // now assemble the texture chains
4377 // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier
4378 for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4381 texture_t *t = loadmodel->data_textures + out->textureindex;
4383 // if this is not animated, skip it
4384 // if this is already processed, skip it (part of an existing sequence)
4385 if (out->q2nexttexinfo == 0 || t->animated)
4388 // store the array of frames to use
4389 t->animated = 2; // q2bsp animation
4390 t->anim_total[0] = 0;
4391 t->anim_total[1] = 0;
4392 // gather up to 10 frames (we don't support more)
4393 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)
4395 // detect looping and stop there
4396 if (loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4398 t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4400 // we could look for the +a sequence here if this is the +0 sequence,
4401 // but it seems that quake2 did not implement that (even though the
4402 // files exist in the baseq2 content)
4404 // write the frame sequence to all the textures involved (just like
4405 // in the q1bsp loader)
4407 // note that this can overwrite the rest of the sequence - so if the
4408 // start of a sequence is found later than the other parts of the
4409 // sequence, it will go back and rewrite them correctly.
4410 for (j = i;j >= 0;j = loadmodel->brushq1.texinfo[j].q2nexttexinfo)
4412 texture_t *txj = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4413 txj->animated = t->animated;
4414 txj->anim_total[0] = t->anim_total[0];
4415 txj->anim_total[1] = t->anim_total[1];
4416 for (k = 0;k < t->anim_total[0];k++)
4417 txj->anim_frames[0][k] = t->anim_frames[0][k];
4418 for (k = 0;k < t->anim_total[1];k++)
4419 txj->anim_frames[1][k] = t->anim_frames[1][k];
4424 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4426 // LordHavoc: this fits exactly the same format that we use in .lit files
4427 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4428 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4431 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4434 int i, j, count, firstmarksurface, nummarksurfaces;
4435 int structsize = 28;
4437 if (sb->cursize % structsize)
4438 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4439 count = sb->cursize / structsize;
4440 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4442 loadmodel->brush.data_leafs = out;
4443 loadmodel->brush.num_leafs = count;
4445 // FIXME: this function could really benefit from some error checking
4446 for ( i=0 ; i<count ; i++, out++)
4448 out->contents = MSG_ReadLittleLong(sb);
4449 out->clusterindex = MSG_ReadLittleShort(sb);
4450 out->areaindex = MSG_ReadLittleShort(sb);
4451 out->mins[0] = MSG_ReadLittleShort(sb);
4452 out->mins[1] = MSG_ReadLittleShort(sb);
4453 out->mins[2] = MSG_ReadLittleShort(sb);
4454 out->maxs[0] = MSG_ReadLittleShort(sb);
4455 out->maxs[1] = MSG_ReadLittleShort(sb);
4456 out->maxs[2] = MSG_ReadLittleShort(sb);
4458 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4459 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4461 for (j = 0;j < 4;j++)
4462 out->ambient_sound_level[j] = 0;
4464 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4466 Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4467 out->clusterindex = -1;
4470 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4472 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4473 out->numleafsurfaces = nummarksurfaces;
4477 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4478 out->firstleafsurface = NULL;
4479 out->numleafsurfaces = 0;
4484 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4489 if (sb->cursize % structsize)
4490 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4491 loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4492 loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4494 for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4496 j = (unsigned short) MSG_ReadLittleShort(sb);
4497 if (j >= loadmodel->brush.num_brushes)
4498 Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4499 loadmodel->brush.data_leafbrushes[i] = j;
4503 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4505 q3mbrushside_t *out;
4509 if (sb->cursize % structsize)
4510 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4511 count = sb->cursize / structsize;
4512 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_brushsides * sizeof(*out));
4514 loadmodel->brush.data_brushsides = out;
4515 loadmodel->brush.num_brushsides = count;
4517 for (i = 0;i < count;i++, out++)
4519 n = (unsigned short)MSG_ReadLittleShort(sb);
4520 if (n < 0 || n >= loadmodel->brush.num_planes)
4521 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4522 out->plane = loadmodel->brush.data_planes + n;
4523 n = MSG_ReadLittleShort(sb);
4524 if (n < 0 || n >= loadmodel->num_textures)
4525 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4526 out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4530 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4533 int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4534 colplanef_t *planes;
4535 int structsize = 12;
4537 if (sb->cursize % structsize)
4538 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4539 count = sb->cursize / structsize;
4540 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_brushes * sizeof(*out));
4542 loadmodel->brush.data_brushes = out;
4543 loadmodel->brush.num_brushes = count;
4548 for (i = 0;i < count;i++, out++)
4550 firstside = MSG_ReadLittleLong(sb);
4551 numsides = MSG_ReadLittleLong(sb);
4552 contents = MSG_ReadLittleLong(sb);
4553 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4554 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4556 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4557 out->numbrushsides = numsides;
4558 // not really the same... we should store the q2 contents
4559 out->texture = out->firstbrushside->texture;
4560 // convert the contents to our values
4561 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(loadmodel, contents);
4563 // make a list of mplane_t structs to construct a colbrush from
4564 if (maxplanes < out->numbrushsides)
4566 maxplanes = out->numbrushsides;
4569 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4572 for (j = 0;j < out->numbrushsides;j++)
4574 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4575 planes[j].dist = out->firstbrushside[j].plane->dist;
4576 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4577 planes[j].texture = out->firstbrushside[j].texture;
4578 q3surfaceflags |= planes[j].q3surfaceflags;
4580 // make the colbrush from the planes
4581 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4583 // this whole loop can take a while (e.g. on redstarrepublic4)
4584 CL_KeepaliveMessage(false);
4591 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4593 // we currently don't use areas, they represent closable doors as vis blockers
4596 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4598 // we currently don't use areas, they represent closable doors as vis blockers
4601 static void Mod_Q2BSP_LoadSubmodels(sizebuf_t *sb)
4605 int structsize = 56;
4607 if (sb->cursize % structsize)
4608 Host_Error ("Mod_Q2BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
4610 count = sb->cursize / structsize;
4611 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
4613 loadmodel->brushq1.submodels = out;
4614 loadmodel->brush.numsubmodels = count;
4616 // this is identical to the q1 submodel structure except for having 1 hull
4617 for (i = 0; i < count; i++, out++)
4619 // spread out the mins / maxs by a pixel
4620 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
4621 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
4622 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
4623 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
4624 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
4625 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
4626 out->origin[0] = MSG_ReadLittleFloat(sb);
4627 out->origin[1] = MSG_ReadLittleFloat(sb);
4628 out->origin[2] = MSG_ReadLittleFloat(sb);
4629 out->headnode[0] = MSG_ReadLittleLong(sb);
4630 out->visleafs = MSG_ReadLittleLong(sb);
4631 out->firstface = MSG_ReadLittleLong(sb);
4632 out->numfaces = MSG_ReadLittleLong(sb);
4636 static void Mod_Q2BSP_FindSubmodelBrushRange_r(dp_model_t *mod, mnode_t *node, int *first, int *last)
4642 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4643 node = node->children[1];
4645 leaf = (mleaf_t*)node;
4646 for (i = 0;i < leaf->numleafbrushes;i++)
4648 int brushnum = leaf->firstleafbrush[i];
4649 if (*first > brushnum)
4651 if (*last < brushnum)
4656 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4659 sizebuf_t lumpsb[Q2HEADER_LUMPS];
4661 float dist, modelyawradius, modelradius;
4662 msurface_t *surface;
4663 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4664 model_brush_lightstyleinfo_t styleinfo[256];
4665 unsigned char *datapointer;
4668 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4670 mod->type = mod_brushq2;
4672 mod->brush.isbsp2 = false;
4673 mod->brush.ishlbsp = false;
4674 mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4675 mod->modeldatatypestring = "Q2BSP";
4677 i = MSG_ReadLittleLong(&sb);
4678 if (i != Q2BSPMAGIC)
4679 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4681 i = MSG_ReadLittleLong(&sb);
4682 if (i != Q2BSPVERSION)
4683 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4686 for (i = 0; i < Q2HEADER_LUMPS; i++)
4688 int offset = MSG_ReadLittleLong(&sb);
4689 int size = MSG_ReadLittleLong(&sb);
4690 if (offset < 0 || offset + size > sb.cursize)
4691 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);
4692 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4695 mod->soundfromcenter = true;
4696 mod->TracePoint = Mod_CollisionBIH_TracePoint;
4697 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4698 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4699 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4700 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4701 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4702 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4703 mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4704 mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4705 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
4706 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
4707 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
4708 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
4709 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
4710 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
4711 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
4712 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
4713 mod->brush.AmbientSoundLevelsForPoint = NULL;
4714 mod->brush.RoundUpToHullSize = NULL;
4715 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
4716 mod->Draw = R_Q1BSP_Draw;
4717 mod->DrawDepth = R_Q1BSP_DrawDepth;
4718 mod->DrawDebug = R_Q1BSP_DrawDebug;
4719 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
4720 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
4721 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
4722 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
4723 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
4724 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
4725 mod->DrawLight = R_Q1BSP_DrawLight;
4729 mod->brush.qw_md4sum = 0;
4730 mod->brush.qw_md4sum2 = 0;
4731 for (i = 0;i < Q2HEADER_LUMPS;i++)
4734 if (i == Q2LUMP_ENTITIES)
4736 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4737 mod->brush.qw_md4sum ^= LittleLong(temp);
4738 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4740 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4743 // many of these functions are identical to Q1 loaders, so we use those where possible
4744 Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4745 Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4746 Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4747 Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4748 Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4749 Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4750 Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4751 Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4752 Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4753 Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4754 Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4755 Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4756 Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4757 Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4758 Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4759 Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4760 Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4761 Mod_Q2BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS]);
4763 for (i = 0; i < Q2HEADER_LUMPS; i++)
4764 if (lumpsb[i].readcount != lumpsb[i].cursize)
4765 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4767 // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4768 // doesn't enable the cvar, just indicates that transparent water is OK
4769 loadmodel->brush.supportwateralpha = true;
4771 // we don't need the compressed pvs data anymore
4772 if (mod->brushq1.data_compressedpvs)
4773 Mem_Free(mod->brushq1.data_compressedpvs);
4774 mod->brushq1.data_compressedpvs = NULL;
4775 mod->brushq1.num_compressedpvs = 0;
4777 // the MakePortals code works fine on the q2bsp data as well
4778 if (mod_bsp_portalize.integer)
4779 Mod_Q1BSP_MakePortals();
4781 mod->numframes = 0; // q2bsp animations are kind of special, frame is unbounded...
4784 // make a single combined shadow mesh to allow optimized shadow volume creation
4785 Mod_Q1BSP_CreateShadowMesh(loadmodel);
4787 if (loadmodel->brush.numsubmodels)
4788 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
4790 totalstylesurfaces = 0;
4792 for (i = 0;i < mod->brush.numsubmodels;i++)
4794 memset(stylecounts, 0, sizeof(stylecounts));
4795 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4797 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4798 for (j = 0;j < MAXLIGHTMAPS;j++)
4799 stylecounts[surface->lightmapinfo->styles[j]]++;
4801 for (k = 0;k < 255;k++)
4805 totalstylesurfaces += stylecounts[k];
4808 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4809 // set up the world model, then on each submodel copy from the world model
4810 // and set up the submodel with the respective model info.
4812 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
4814 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
4818 // duplicate the basic information
4819 dpsnprintf(name, sizeof(name), "*%i", i);
4820 mod = Mod_FindName(name, loadmodel->name);
4821 // copy the base model to this one
4823 // rename the clone back to its proper name
4824 strlcpy(mod->name, name, sizeof(mod->name));
4825 mod->brush.parentmodel = loadmodel;
4826 // textures and memory belong to the main model
4827 mod->texturepool = NULL;
4828 mod->mempool = NULL;
4829 mod->brush.GetPVS = NULL;
4830 mod->brush.FatPVS = NULL;
4831 mod->brush.BoxTouchingPVS = NULL;
4832 mod->brush.BoxTouchingLeafPVS = NULL;
4833 mod->brush.BoxTouchingVisibleLeafs = NULL;
4834 mod->brush.FindBoxClusters = NULL;
4835 mod->brush.LightPoint = NULL;
4836 mod->brush.AmbientSoundLevelsForPoint = NULL;
4838 mod->brush.submodel = i;
4839 if (loadmodel->brush.submodels)
4840 loadmodel->brush.submodels[i] = mod;
4842 bm = &mod->brushq1.submodels[i];
4844 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
4845 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4847 mod->firstmodelsurface = bm->firstface;
4848 mod->nummodelsurfaces = bm->numfaces;
4850 // set node/leaf parents for this submodel
4851 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + bm->headnode[0], NULL);
4853 // make the model surface list (used by shadowing/lighting)
4854 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4855 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, mod->brush.data_nodes + bm->headnode[0], &firstbrush, &lastbrush);
4856 if (firstbrush <= lastbrush)
4858 mod->firstmodelbrush = firstbrush;
4859 mod->nummodelbrushes = lastbrush + 1 - firstbrush;
4863 mod->firstmodelbrush = 0;
4864 mod->nummodelbrushes = 0;
4866 Mod_MakeSortedSurfaces(mod);
4868 VectorCopy(bm->mins, mod->normalmins);
4869 VectorCopy(bm->maxs, mod->normalmaxs);
4870 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4871 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4872 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4873 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4874 modelradius = modelyawradius + modelradius * modelradius;
4875 modelyawradius = sqrt(modelyawradius);
4876 modelradius = sqrt(modelradius);
4877 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4878 mod->yawmins[2] = mod->normalmins[2];
4879 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4880 mod->yawmaxs[2] = mod->normalmaxs[2];
4881 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4882 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4883 mod->radius = modelradius;
4884 mod->radius2 = modelradius * modelradius;
4886 // this gets altered below if sky or water is used
4887 mod->DrawSky = NULL;
4888 mod->DrawAddWaterPlanes = NULL;
4890 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4891 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4892 if (mod->nummodelsurfaces)
4894 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4895 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4897 if (j < mod->nummodelsurfaces)
4898 mod->DrawSky = R_Q1BSP_DrawSky;
4900 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4901 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4903 if (j < mod->nummodelsurfaces)
4904 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4906 // build lightstyle update chains
4907 // (used to rapidly mark lightmapupdateflags on many surfaces
4908 // when d_lightstylevalue changes)
4909 memset(stylecounts, 0, sizeof(stylecounts));
4910 for (k = 0;k < mod->nummodelsurfaces;k++)
4912 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4913 for (j = 0;j < MAXLIGHTMAPS;j++)
4914 stylecounts[surface->lightmapinfo->styles[j]]++;
4916 mod->brushq1.num_lightstyles = 0;
4917 for (k = 0;k < 255;k++)
4921 styleinfo[mod->brushq1.num_lightstyles].style = k;
4922 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4923 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4924 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4925 remapstyles[k] = mod->brushq1.num_lightstyles;
4926 mod->brushq1.num_lightstyles++;
4929 for (k = 0;k < mod->nummodelsurfaces;k++)
4931 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4932 for (j = 0;j < MAXLIGHTMAPS;j++)
4934 if (surface->lightmapinfo->styles[j] != 255)
4936 int r = remapstyles[surface->lightmapinfo->styles[j]];
4937 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4941 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4942 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4946 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4948 //mod->brushq1.num_visleafs = bm->visleafs;
4950 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4951 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
4953 // build a Bounding Interval Hierarchy for culling brushes in collision detection
4954 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4956 // generate VBOs and other shared data before cloning submodels
4962 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);
4965 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4966 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4968 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4971 char key[128], value[MAX_INPUTLINE];
4973 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4974 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4975 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4978 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4979 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4980 loadmodel->brush.entities[l->filelen] = 0;
4981 data = loadmodel->brush.entities;
4982 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4983 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4984 loadmodel->brushq3.deluxemapping = false;
4985 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
4989 if (!COM_ParseToken_Simple(&data, false, false, true))
4991 if (com_token[0] == '}')
4992 break; // end of worldspawn
4993 if (com_token[0] == '_')
4994 strlcpy(key, com_token + 1, sizeof(key));
4996 strlcpy(key, com_token, sizeof(key));
4997 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4998 key[strlen(key)-1] = 0;
4999 if (!COM_ParseToken_Simple(&data, false, false, true))
5001 strlcpy(value, com_token, sizeof(value));
5002 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5004 #if _MSC_VER >= 1400
5005 #define sscanf sscanf_s
5008 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5009 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5011 VectorSet(v, 64, 64, 128);
5012 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5013 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]);
5014 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5015 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5018 else if (!strcmp("deluxeMaps", key))
5020 if (!strcmp(com_token, "1"))
5022 loadmodel->brushq3.deluxemapping = true;
5023 loadmodel->brushq3.deluxemapping_modelspace = true;
5025 else if (!strcmp(com_token, "2"))
5027 loadmodel->brushq3.deluxemapping = true;
5028 loadmodel->brushq3.deluxemapping_modelspace = false;
5035 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5041 in = (q3dtexture_t *)(mod_base + l->fileofs);
5042 if (l->filelen % sizeof(*in))
5043 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5044 count = l->filelen / sizeof(*in);
5045 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5047 loadmodel->data_textures = out;
5048 loadmodel->num_textures = count;
5049 loadmodel->num_texturesperskin = loadmodel->num_textures;
5051 for (i = 0;i < count;i++)
5053 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
5054 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5055 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
5056 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
5057 // restore the surfaceflags and supercontents
5058 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5059 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
5063 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5069 in = (q3dplane_t *)(mod_base + l->fileofs);
5070 if (l->filelen % sizeof(*in))
5071 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5072 count = l->filelen / sizeof(*in);
5073 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5075 loadmodel->brush.data_planes = out;
5076 loadmodel->brush.num_planes = count;
5078 for (i = 0;i < count;i++, in++, out++)
5080 out->normal[0] = LittleFloat(in->normal[0]);
5081 out->normal[1] = LittleFloat(in->normal[1]);
5082 out->normal[2] = LittleFloat(in->normal[2]);
5083 out->dist = LittleFloat(in->dist);
5088 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5091 q3mbrushside_t *out;
5094 in = (q3dbrushside_t *)(mod_base + l->fileofs);
5095 if (l->filelen % sizeof(*in))
5096 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5097 count = l->filelen / sizeof(*in);
5098 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5100 loadmodel->brush.data_brushsides = out;
5101 loadmodel->brush.num_brushsides = count;
5103 for (i = 0;i < count;i++, in++, out++)
5105 n = LittleLong(in->planeindex);
5106 if (n < 0 || n >= loadmodel->brush.num_planes)
5107 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5108 out->plane = loadmodel->brush.data_planes + n;
5109 n = LittleLong(in->textureindex);
5110 if (n < 0 || n >= loadmodel->num_textures)
5111 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5112 out->texture = loadmodel->data_textures + n;
5116 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5118 q3dbrushside_ig_t *in;
5119 q3mbrushside_t *out;
5122 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5123 if (l->filelen % sizeof(*in))
5124 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5125 count = l->filelen / sizeof(*in);
5126 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5128 loadmodel->brush.data_brushsides = out;
5129 loadmodel->brush.num_brushsides = count;
5131 for (i = 0;i < count;i++, in++, out++)
5133 n = LittleLong(in->planeindex);
5134 if (n < 0 || n >= loadmodel->brush.num_planes)
5135 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5136 out->plane = loadmodel->brush.data_planes + n;
5137 n = LittleLong(in->textureindex);
5138 if (n < 0 || n >= loadmodel->num_textures)
5139 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5140 out->texture = loadmodel->data_textures + n;
5144 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5148 int i, j, n, c, count, maxplanes, q3surfaceflags;
5149 colplanef_t *planes;
5151 in = (q3dbrush_t *)(mod_base + l->fileofs);
5152 if (l->filelen % sizeof(*in))
5153 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5154 count = l->filelen / sizeof(*in);
5155 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5157 loadmodel->brush.data_brushes = out;
5158 loadmodel->brush.num_brushes = count;
5163 for (i = 0;i < count;i++, in++, out++)
5165 n = LittleLong(in->firstbrushside);
5166 c = LittleLong(in->numbrushsides);
5167 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5168 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5169 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5170 out->numbrushsides = c;
5171 n = LittleLong(in->textureindex);
5172 if (n < 0 || n >= loadmodel->num_textures)
5173 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5174 out->texture = loadmodel->data_textures + n;
5176 // make a list of mplane_t structs to construct a colbrush from
5177 if (maxplanes < out->numbrushsides)
5179 maxplanes = out->numbrushsides;
5182 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5185 for (j = 0;j < out->numbrushsides;j++)
5187 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5188 planes[j].dist = out->firstbrushside[j].plane->dist;
5189 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5190 planes[j].texture = out->firstbrushside[j].texture;
5191 q3surfaceflags |= planes[j].q3surfaceflags;
5193 // make the colbrush from the planes
5194 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5196 // this whole loop can take a while (e.g. on redstarrepublic4)
5197 CL_KeepaliveMessage(false);
5203 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5209 in = (q3deffect_t *)(mod_base + l->fileofs);
5210 if (l->filelen % sizeof(*in))
5211 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5212 count = l->filelen / sizeof(*in);
5213 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5215 loadmodel->brushq3.data_effects = out;
5216 loadmodel->brushq3.num_effects = count;
5218 for (i = 0;i < count;i++, in++, out++)
5220 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5221 n = LittleLong(in->brushindex);
5222 if (n >= loadmodel->brush.num_brushes)
5224 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5227 out->brushindex = n;
5228 out->unknown = LittleLong(in->unknown);
5232 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5237 in = (q3dvertex_t *)(mod_base + l->fileofs);
5238 if (l->filelen % sizeof(*in))
5239 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5240 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5241 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5242 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5243 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5244 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5245 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5247 for (i = 0;i < count;i++, in++)
5249 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5250 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5251 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5252 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5253 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5254 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5255 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5256 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5257 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5258 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5259 // svector/tvector are calculated later in face loading
5260 if(mod_q3bsp_sRGBlightmaps.integer)
5262 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5263 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5264 // working like this may be odd, but matches q3map2 -gamma 2.2
5265 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5267 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5268 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5269 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5270 // we fix the brightness consistently via lightmapscale
5274 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5275 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5276 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5281 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5283 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5284 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5285 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5289 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5290 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5291 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5294 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5295 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5296 loadmodel->lit = true;
5300 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5306 in = (int *)(mod_base + l->fileofs);
5307 if (l->filelen % sizeof(int[3]))
5308 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5309 count = l->filelen / sizeof(*in);
5311 if(!loadmodel->brushq3.num_vertices)
5314 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5315 loadmodel->brushq3.num_triangles = 0;
5319 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5320 loadmodel->brushq3.num_triangles = count / 3;
5321 loadmodel->brushq3.data_element3i = out;
5323 for (i = 0;i < count;i++, in++, out++)
5325 *out = LittleLong(*in);
5326 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5328 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5334 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5336 q3dlightmap_t *input_pointer;
5354 int mergedrowsxcolumns;
5359 unsigned char *mergedpixels;
5360 unsigned char *mergeddeluxepixels;
5361 unsigned char *mergebuf;
5362 char mapname[MAX_QPATH];
5364 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5367 // defaults for q3bsp
5374 loadmodel->brushq3.lightmapsize = 128;
5376 if (cls.state == ca_dedicated)
5379 if(mod_q3bsp_nolightmaps.integer)
5385 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5386 if (developer_loading.integer)
5387 Con_Printf("Using internal lightmaps\n");
5388 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5389 if (l->filelen % sizeof(*input_pointer))
5390 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5391 count = l->filelen / sizeof(*input_pointer);
5392 for(i = 0; i < count; ++i)
5393 inpixels[i] = input_pointer[i].rgb;
5397 // no internal lightmaps
5398 // try external lightmaps
5399 if (developer_loading.integer)
5400 Con_Printf("Using external lightmaps\n");
5401 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5402 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5406 // using EXTERNAL lightmaps instead
5407 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5409 Mem_Free(inpixels[0]);
5410 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5420 for(count = 1; ; ++count)
5422 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5423 if(!inpixels[count])
5424 break; // we got all of them
5425 if(image_width != size || image_height != size)
5427 Mem_Free(inpixels[count]);
5428 inpixels[count] = NULL;
5429 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);
5435 loadmodel->brushq3.lightmapsize = size;
5436 loadmodel->brushq3.num_originallightmaps = count;
5438 // now check the surfaces to see if any of them index an odd numbered
5439 // lightmap, if so this is not a deluxemapped bsp file
5441 // also check what lightmaps are actually used, because q3map2 sometimes
5442 // (always?) makes an unused one at the end, which
5443 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5444 // reason when only one lightmap is used, which can throw off the
5445 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5446 // to see if the second lightmap is blank, if so it is not deluxemapped.
5447 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5448 // in Mod_Q3BSP_LoadEntities was failed
5449 if (!loadmodel->brushq3.deluxemapping)
5451 loadmodel->brushq3.deluxemapping = !(count & 1);
5452 loadmodel->brushq3.deluxemapping_modelspace = true;
5454 if (loadmodel->brushq3.deluxemapping)
5456 int facecount = faceslump->filelen / sizeof(q3dface_t);
5457 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5458 for (i = 0;i < facecount;i++)
5460 j = LittleLong(faces[i].lightmapindex);
5463 endlightmap = max(endlightmap, j + 1);
5464 if ((j & 1) || j + 1 >= count)
5466 loadmodel->brushq3.deluxemapping = false;
5473 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5474 // reason when only one lightmap is used, which can throw off the
5475 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5476 // to see if the second lightmap is blank, if so it is not deluxemapped.
5478 // further research has shown q3map2 sometimes creates a deluxemap and two
5479 // blank lightmaps, which must be handled properly as well
5480 if (endlightmap == 1 && count > 1)
5483 for (i = 0;i < size*size;i++)
5485 if (c[bytesperpixel*i + rgbmap[0]])
5487 if (c[bytesperpixel*i + rgbmap[1]])
5489 if (c[bytesperpixel*i + rgbmap[2]])
5494 // all pixels in the unused lightmap were black...
5495 loadmodel->brushq3.deluxemapping = false;
5500 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5502 // figure out what the most reasonable merge power is within limits
5504 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5505 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5507 // figure out how big the merged texture has to be
5508 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5509 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5510 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5512 mergedwidth = mergegoal;
5513 mergedheight = mergegoal;
5514 // choose non-square size (2x1 aspect) if only half the space is used;
5515 // this really only happens when the entire set fits in one texture, if
5516 // there are multiple textures, we don't worry about shrinking the last
5517 // one to fit, because the driver prefers the same texture size on
5518 // consecutive draw calls...
5519 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5522 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5523 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5524 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5525 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5526 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5527 loadmodel->brushq3.num_lightmapmergedheightpower++;
5528 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5530 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5531 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5532 powerxy = powerx+powery;
5533 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5535 mergedcolumns = 1 << powerx;
5536 mergedrows = 1 << powery;
5537 mergedrowsxcolumns = 1 << powerxy;
5539 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5540 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5541 if (loadmodel->brushq3.deluxemapping)
5542 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5544 // allocate a texture pool if we need it
5545 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5546 loadmodel->texturepool = R_AllocTexturePool();
5548 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5549 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5550 for (i = 0;i < count;i++)
5552 // figure out which merged lightmap texture this fits into
5553 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5554 lightmapindex = i >> powerdxy;
5556 // choose the destination address
5557 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5558 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5559 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5560 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);
5562 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5563 for (j = 0;j < size;j++)
5564 for (k = 0;k < size;k++)
5566 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5567 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5568 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5569 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5572 // upload texture if this was the last tile being written to the texture
5573 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5575 if (loadmodel->brushq3.deluxemapping && (i & 1))
5576 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);
5579 if(mod_q3bsp_sRGBlightmaps.integer)
5582 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5584 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5585 // we fix the brightness consistently via lightmapscale
5588 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5589 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);
5593 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5594 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5595 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);
5601 if (mergeddeluxepixels)
5602 Mem_Free(mergeddeluxepixels);
5603 Mem_Free(mergedpixels);
5606 for(i = 0; i < count; ++i)
5607 Mem_Free(inpixels[i]);
5611 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5616 *collisionstride = stride;
5619 cnt = (num_triangles + stride - 1) / stride;
5620 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5621 for(j = 0; j < cnt; ++j)
5623 mins = &((*collisionbbox6f)[6 * j + 0]);
5624 maxs = &((*collisionbbox6f)[6 * j + 3]);
5625 for(k = 0; k < stride; ++k)
5627 tri = j * stride + k;
5628 if(tri >= num_triangles)
5630 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5631 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5632 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5633 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5634 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5635 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5636 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5637 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5638 if(vert[0] < mins[0]) mins[0] = vert[0];
5639 if(vert[1] < mins[1]) mins[1] = vert[1];
5640 if(vert[2] < mins[2]) mins[2] = vert[2];
5641 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5642 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5643 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5644 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5645 if(vert[0] < mins[0]) mins[0] = vert[0];
5646 if(vert[1] < mins[1]) mins[1] = vert[1];
5647 if(vert[2] < mins[2]) mins[2] = vert[2];
5648 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5649 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5650 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5655 *collisionbbox6f = NULL;
5658 typedef struct patchtess_s
5662 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5665 float *originalvertex3f;
5668 #define PATCHTESS_SAME_LODGROUP(a,b) \
5670 (a).lodgroup[0] == (b).lodgroup[0] && \
5671 (a).lodgroup[1] == (b).lodgroup[1] && \
5672 (a).lodgroup[2] == (b).lodgroup[2] && \
5673 (a).lodgroup[3] == (b).lodgroup[3] && \
5674 (a).lodgroup[4] == (b).lodgroup[4] && \
5675 (a).lodgroup[5] == (b).lodgroup[5] \
5678 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5680 q3dface_t *in, *oldin;
5681 msurface_t *out, *oldout;
5682 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;
5683 float lightmaptcbase[2], lightmaptcscale[2];
5684 //int *originalelement3i;
5685 //int *originalneighbor3i;
5686 float *originalvertex3f;
5687 //float *originalsvector3f;
5688 //float *originaltvector3f;
5689 float *originalnormal3f;
5690 float *originalcolor4f;
5691 float *originaltexcoordtexture2f;
5692 float *originaltexcoordlightmap2f;
5693 float *surfacecollisionvertex3f;
5694 int *surfacecollisionelement3i;
5696 patchtess_t *patchtess = NULL;
5697 int patchtesscount = 0;
5700 in = (q3dface_t *)(mod_base + l->fileofs);
5701 if (l->filelen % sizeof(*in))
5702 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5703 count = l->filelen / sizeof(*in);
5704 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5706 loadmodel->data_surfaces = out;
5707 loadmodel->num_surfaces = count;
5710 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5718 for (;i < count;i++, in++, out++)
5720 // check face type first
5721 type = LittleLong(in->type);
5722 if (type != Q3FACETYPE_FLAT
5723 && type != Q3FACETYPE_PATCH
5724 && type != Q3FACETYPE_MESH
5725 && type != Q3FACETYPE_FLARE)
5727 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5731 n = LittleLong(in->textureindex);
5732 if (n < 0 || n >= loadmodel->num_textures)
5734 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5737 out->texture = loadmodel->data_textures + n;
5738 n = LittleLong(in->effectindex);
5739 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5741 if (developer_extra.integer)
5742 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5748 out->effect = loadmodel->brushq3.data_effects + n;
5750 if (cls.state != ca_dedicated)
5752 out->lightmaptexture = NULL;
5753 out->deluxemaptexture = r_texture_blanknormalmap;
5754 n = LittleLong(in->lightmapindex);
5757 else if (n >= loadmodel->brushq3.num_originallightmaps)
5759 if(loadmodel->brushq3.num_originallightmaps != 0)
5760 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5765 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5766 if (loadmodel->brushq3.deluxemapping)
5767 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5768 loadmodel->lit = true;
5772 firstvertex = LittleLong(in->firstvertex);
5773 numvertices = LittleLong(in->numvertices);
5774 firstelement = LittleLong(in->firstelement);
5775 numtriangles = LittleLong(in->numelements) / 3;
5776 if (numtriangles * 3 != LittleLong(in->numelements))
5778 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));
5781 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5783 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);
5786 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5788 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);
5793 case Q3FACETYPE_FLAT:
5794 case Q3FACETYPE_MESH:
5795 // no processing necessary
5797 case Q3FACETYPE_PATCH:
5798 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5799 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5800 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))
5802 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5805 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5807 // convert patch to Q3FACETYPE_MESH
5808 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5809 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5810 // bound to user settings
5811 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5812 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5813 // bound to sanity settings
5814 xtess = bound(0, xtess, 1024);
5815 ytess = bound(0, ytess, 1024);
5817 // lower quality collision patches! Same procedure as before, but different cvars
5818 // convert patch to Q3FACETYPE_MESH
5819 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5820 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5821 // bound to user settings
5822 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5823 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5824 // bound to sanity settings
5825 cxtess = bound(0, cxtess, 1024);
5826 cytess = bound(0, cytess, 1024);
5828 // store it for the LOD grouping step
5829 patchtess[patchtesscount].info.xsize = patchsize[0];
5830 patchtess[patchtesscount].info.ysize = patchsize[1];
5831 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5832 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5833 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5834 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5836 patchtess[patchtesscount].surface_id = i;
5837 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5838 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5839 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5840 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5841 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5842 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5843 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5846 case Q3FACETYPE_FLARE:
5847 if (developer_extra.integer)
5848 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5852 out->num_vertices = numvertices;
5853 out->num_triangles = numtriangles;
5854 meshvertices += out->num_vertices;
5855 meshtriangles += out->num_triangles;
5858 // Fix patches tesselations so that they make no seams
5862 for(i = 0; i < patchtesscount; ++i)
5864 for(j = i+1; j < patchtesscount; ++j)
5866 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5869 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5876 // Calculate resulting number of triangles
5877 collisionvertices = 0;
5878 collisiontriangles = 0;
5879 for(i = 0; i < patchtesscount; ++i)
5881 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5882 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5883 numvertices = finalwidth * finalheight;
5884 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5886 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5887 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5888 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5889 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5891 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5892 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5893 numvertices = finalwidth * finalheight;
5894 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5896 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5897 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5898 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5899 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5905 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5906 if (collisiontriangles)
5908 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5909 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5913 collisionvertices = 0;
5914 collisiontriangles = 0;
5915 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5917 if (out->num_vertices < 3 || out->num_triangles < 1)
5920 type = LittleLong(in->type);
5921 firstvertex = LittleLong(in->firstvertex);
5922 firstelement = LittleLong(in->firstelement);
5923 out->num_firstvertex = meshvertices;
5924 out->num_firsttriangle = meshtriangles;
5925 out->num_firstcollisiontriangle = collisiontriangles;
5928 case Q3FACETYPE_FLAT:
5929 case Q3FACETYPE_MESH:
5930 // no processing necessary, except for lightmap merging
5931 for (j = 0;j < out->num_vertices;j++)
5933 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5934 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5935 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5936 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5937 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5938 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5939 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5940 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5941 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5942 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5943 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5944 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5945 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5946 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5948 for (j = 0;j < out->num_triangles*3;j++)
5949 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5951 case Q3FACETYPE_PATCH:
5952 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5953 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5954 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5955 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5956 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5957 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5958 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5960 xtess = ytess = cxtess = cytess = -1;
5961 for(j = 0; j < patchtesscount; ++j)
5962 if(patchtess[j].surface_id == i)
5964 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5965 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5966 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5967 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5972 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5973 xtess = ytess = cxtess = cytess = 0;
5976 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5977 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5978 finalvertices = finalwidth * finalheight;
5979 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5980 type = Q3FACETYPE_MESH;
5981 // generate geometry
5982 // (note: normals are skipped because they get recalculated)
5983 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5984 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5985 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5986 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5987 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5988 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5990 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);
5992 if (developer_extra.integer)
5994 if (out->num_triangles < finaltriangles)
5995 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);
5997 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);
5999 // q3map does not put in collision brushes for curves... ugh
6000 // build the lower quality collision geometry
6001 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6002 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6003 finalvertices = finalwidth * finalheight;
6004 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6006 // legacy collision geometry implementation
6007 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
6008 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
6009 out->num_collisionvertices = finalvertices;
6010 out->num_collisiontriangles = finaltriangles;
6011 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6012 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
6014 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
6015 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
6017 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
6019 // now optimize the collision mesh by finding triangle bboxes...
6020 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
6021 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);
6023 // store collision geometry for BIH collision tree
6024 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6025 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6026 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6027 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6028 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6030 // remove this once the legacy code is removed
6032 int nc = out->num_collisiontriangles;
6034 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6036 if(nc != out->num_collisiontriangles)
6038 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
6043 if (developer_extra.integer)
6044 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);
6046 collisionvertices += finalvertices;
6047 collisiontriangles += out->num_collisiontriangles;
6052 meshvertices += out->num_vertices;
6053 meshtriangles += out->num_triangles;
6054 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6055 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)
6057 if (invalidelements)
6059 Con_Printf("Mod_Q3BSP_LoadFaces: Warning: face #%i has %i invalid elements, type = %i, texture->name = \"%s\", texture->surfaceflags = %i, firstvertex = %i, numvertices = %i, firstelement = %i, numelements = %i, elements list:\n", i, invalidelements, type, out->texture->name, out->texture->surfaceflags, firstvertex, out->num_vertices, firstelement, out->num_triangles * 3);
6060 for (j = 0;j < out->num_triangles * 3;j++)
6062 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6063 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)
6064 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6068 // calculate a bounding box
6069 VectorClear(out->mins);
6070 VectorClear(out->maxs);
6071 if (out->num_vertices)
6073 if (cls.state != ca_dedicated && out->lightmaptexture)
6075 // figure out which part of the merged lightmap this fits into
6076 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6077 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6078 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6079 lightmapindex &= mergewidth * mergeheight - 1;
6080 lightmaptcscale[0] = 1.0f / mergewidth;
6081 lightmaptcscale[1] = 1.0f / mergeheight;
6082 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6083 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6084 // modify the lightmap texcoords to match this region of the merged lightmap
6085 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6087 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6088 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6091 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6092 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6093 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6095 out->mins[0] = min(out->mins[0], v[0]);
6096 out->maxs[0] = max(out->maxs[0], v[0]);
6097 out->mins[1] = min(out->mins[1], v[1]);
6098 out->maxs[1] = max(out->maxs[1], v[1]);
6099 out->mins[2] = min(out->mins[2], v[2]);
6100 out->maxs[2] = max(out->maxs[2], v[2]);
6102 out->mins[0] -= 1.0f;
6103 out->mins[1] -= 1.0f;
6104 out->mins[2] -= 1.0f;
6105 out->maxs[0] += 1.0f;
6106 out->maxs[1] += 1.0f;
6107 out->maxs[2] += 1.0f;
6109 // set lightmap styles for consistency with q1bsp
6110 //out->lightmapinfo->styles[0] = 0;
6111 //out->lightmapinfo->styles[1] = 255;
6112 //out->lightmapinfo->styles[2] = 255;
6113 //out->lightmapinfo->styles[3] = 255;
6118 for (;i < count;i++, out++)
6120 if(out->num_vertices && out->num_triangles)
6122 if(out->num_vertices == 0)
6124 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6125 if(out->num_triangles == 0)
6126 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6128 else if(out->num_triangles == 0)
6129 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)",
6130 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6131 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6132 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6135 // for per pixel lighting
6136 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);
6138 // generate ushort elements array if possible
6139 if (loadmodel->surfmesh.data_element3s)
6140 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6141 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6143 // free the no longer needed vertex data
6144 loadmodel->brushq3.num_vertices = 0;
6145 if (loadmodel->brushq3.data_vertex3f)
6146 Mem_Free(loadmodel->brushq3.data_vertex3f);
6147 loadmodel->brushq3.data_vertex3f = NULL;
6148 loadmodel->brushq3.data_normal3f = NULL;
6149 loadmodel->brushq3.data_texcoordtexture2f = NULL;
6150 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6151 loadmodel->brushq3.data_color4f = NULL;
6152 // free the no longer needed triangle data
6153 loadmodel->brushq3.num_triangles = 0;
6154 if (loadmodel->brushq3.data_element3i)
6155 Mem_Free(loadmodel->brushq3.data_element3i);
6156 loadmodel->brushq3.data_element3i = NULL;
6159 Mem_Free(patchtess);
6162 static void Mod_Q3BSP_LoadModels(lump_t *l)
6166 int i, j, n, c, count;
6168 in = (q3dmodel_t *)(mod_base + l->fileofs);
6169 if (l->filelen % sizeof(*in))
6170 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6171 count = l->filelen / sizeof(*in);
6172 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6174 loadmodel->brushq3.data_models = out;
6175 loadmodel->brushq3.num_models = count;
6177 for (i = 0;i < count;i++, in++, out++)
6179 for (j = 0;j < 3;j++)
6181 out->mins[j] = LittleFloat(in->mins[j]);
6182 out->maxs[j] = LittleFloat(in->maxs[j]);
6184 n = LittleLong(in->firstface);
6185 c = LittleLong(in->numfaces);
6186 if (n < 0 || n + c > loadmodel->num_surfaces)
6187 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6190 n = LittleLong(in->firstbrush);
6191 c = LittleLong(in->numbrushes);
6192 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6193 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6194 out->firstbrush = n;
6195 out->numbrushes = c;
6199 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6205 in = (int *)(mod_base + l->fileofs);
6206 if (l->filelen % sizeof(*in))
6207 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6208 count = l->filelen / sizeof(*in);
6209 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6211 loadmodel->brush.data_leafbrushes = out;
6212 loadmodel->brush.num_leafbrushes = count;
6214 for (i = 0;i < count;i++, in++, out++)
6216 n = LittleLong(*in);
6217 if (n < 0 || n >= loadmodel->brush.num_brushes)
6218 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6223 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6229 in = (int *)(mod_base + l->fileofs);
6230 if (l->filelen % sizeof(*in))
6231 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6232 count = l->filelen / sizeof(*in);
6233 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6235 loadmodel->brush.data_leafsurfaces = out;
6236 loadmodel->brush.num_leafsurfaces = count;
6238 for (i = 0;i < count;i++, in++, out++)
6240 n = LittleLong(*in);
6241 if (n < 0 || n >= loadmodel->num_surfaces)
6242 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6247 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6251 int i, j, n, c, count;
6253 in = (q3dleaf_t *)(mod_base + l->fileofs);
6254 if (l->filelen % sizeof(*in))
6255 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6256 count = l->filelen / sizeof(*in);
6257 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6259 loadmodel->brush.data_leafs = out;
6260 loadmodel->brush.num_leafs = count;
6262 for (i = 0;i < count;i++, in++, out++)
6266 out->clusterindex = LittleLong(in->clusterindex);
6267 out->areaindex = LittleLong(in->areaindex);
6268 for (j = 0;j < 3;j++)
6270 // yes the mins/maxs are ints
6271 out->mins[j] = LittleLong(in->mins[j]) - 1;
6272 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6274 n = LittleLong(in->firstleafface);
6275 c = LittleLong(in->numleaffaces);
6276 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6277 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6278 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6279 out->numleafsurfaces = c;
6280 n = LittleLong(in->firstleafbrush);
6281 c = LittleLong(in->numleafbrushes);
6282 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6283 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6284 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6285 out->numleafbrushes = c;
6289 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6295 in = (q3dnode_t *)(mod_base + l->fileofs);
6296 if (l->filelen % sizeof(*in))
6297 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6298 count = l->filelen / sizeof(*in);
6300 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6301 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6303 loadmodel->brush.data_nodes = out;
6304 loadmodel->brush.num_nodes = count;
6306 for (i = 0;i < count;i++, in++, out++)
6309 n = LittleLong(in->planeindex);
6310 if (n < 0 || n >= loadmodel->brush.num_planes)
6311 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6312 out->plane = loadmodel->brush.data_planes + n;
6313 for (j = 0;j < 2;j++)
6315 n = LittleLong(in->childrenindex[j]);
6318 if (n >= loadmodel->brush.num_nodes)
6319 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6320 out->children[j] = loadmodel->brush.data_nodes + n;
6325 if (n >= loadmodel->brush.num_leafs)
6326 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6327 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6330 for (j = 0;j < 3;j++)
6332 // yes the mins/maxs are ints
6333 out->mins[j] = LittleLong(in->mins[j]) - 1;
6334 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6338 // set the parent pointers
6339 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6342 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6345 q3dlightgrid_t *out;
6349 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6350 if (l->filelen % sizeof(*in))
6351 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6352 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6353 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6354 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6355 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6356 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6357 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6358 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6359 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6360 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6361 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6362 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6363 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6364 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6365 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]);
6366 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]);
6368 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6371 if (l->filelen < count * (int)sizeof(*in))
6373 Con_Printf("Mod_Q3BSP_LoadLightGrid: invalid lightgrid lump size %i bytes, should be %i bytes (%ix%ix%i)", l->filelen, (int)(count * sizeof(*in)), loadmodel->brushq3.num_lightgrid_isize[0], loadmodel->brushq3.num_lightgrid_isize[1], loadmodel->brushq3.num_lightgrid_isize[2]);
6374 return; // ignore the grid if we cannot understand it
6376 if (l->filelen != count * (int)sizeof(*in))
6377 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
6378 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6379 loadmodel->brushq3.data_lightgrid = out;
6380 loadmodel->brushq3.num_lightgrid = count;
6381 // no swapping or validation necessary
6382 memcpy(out, in, count * (int)sizeof(*out));
6384 if(mod_q3bsp_sRGBlightmaps.integer)
6386 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6388 // we fix the brightness consistently via lightmapscale
6392 for(i = 0; i < count; ++i)
6394 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6395 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6396 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6397 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6398 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6399 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6405 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6407 for(i = 0; i < count; ++i)
6409 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6410 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6411 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6412 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6413 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6414 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6425 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6430 if (l->filelen == 0)
6433 // unvised maps often have cluster indices even without pvs, so check
6434 // leafs to find real number of clusters
6435 loadmodel->brush.num_pvsclusters = 1;
6436 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6437 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6440 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6441 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6442 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6443 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6447 in = (q3dpvs_t *)(mod_base + l->fileofs);
6449 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6451 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6452 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6453 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6454 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6455 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6456 if (l->filelen < totalchains + (int)sizeof(*in))
6457 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);
6459 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6460 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6463 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6465 int i, j, k, index[3];
6466 float transformed[3], blend1, blend2, blend, stylescale = 1;
6467 q3dlightgrid_t *a, *s;
6469 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6470 switch(vid.renderpath)
6472 case RENDERPATH_GL20:
6473 case RENDERPATH_D3D9:
6474 case RENDERPATH_D3D10:
6475 case RENDERPATH_D3D11:
6476 case RENDERPATH_SOFT:
6477 case RENDERPATH_GLES2:
6478 // LordHavoc: FIXME: is this true?
6479 stylescale = 1; // added while render
6481 case RENDERPATH_GL11:
6482 case RENDERPATH_GL13:
6483 case RENDERPATH_GLES1:
6484 stylescale = r_refdef.scene.rtlightstylevalue[0];
6488 if (!model->brushq3.num_lightgrid)
6490 ambientcolor[0] = stylescale;
6491 ambientcolor[1] = stylescale;
6492 ambientcolor[2] = stylescale;
6496 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6497 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6498 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6499 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6500 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6501 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6502 index[0] = (int)floor(transformed[0]);
6503 index[1] = (int)floor(transformed[1]);
6504 index[2] = (int)floor(transformed[2]);
6505 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6507 // now lerp the values
6508 VectorClear(diffusenormal);
6509 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6510 for (k = 0;k < 2;k++)
6512 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6513 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6515 for (j = 0;j < 2;j++)
6517 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6518 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6520 for (i = 0;i < 2;i++)
6522 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6523 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6525 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6526 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6527 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6528 // this uses the mod_md3_sin table because the values are
6529 // already in the 0-255 range, the 64+ bias fetches a cosine
6530 // instead of a sine value
6531 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6532 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6533 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6534 //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)));
6539 // normalize the light direction before turning
6540 VectorNormalize(diffusenormal);
6541 //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]);
6544 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6547 double midf, mid[3];
6553 // find the point distances
6554 mplane_t *plane = node->plane;
6555 if (plane->type < 3)
6557 t1 = p1[plane->type] - plane->dist;
6558 t2 = p2[plane->type] - plane->dist;
6562 t1 = DotProduct (plane->normal, p1) - plane->dist;
6563 t2 = DotProduct (plane->normal, p2) - plane->dist;
6570 node = node->children[1];
6579 node = node->children[0];
6585 midf = t1 / (t1 - t2);
6586 VectorLerp(p1, midf, p2, mid);
6588 // recurse both sides, front side first
6589 // return 2 if empty is followed by solid (hit something)
6590 // do not return 2 if both are solid or both empty,
6591 // or if start is solid and end is empty
6592 // as these degenerate cases usually indicate the eye is in solid and
6593 // should see the target point anyway
6594 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6597 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6602 return ((mleaf_t *)node)->clusterindex < 0;
6605 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6607 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6610 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6611 return trace.fraction == 1;
6615 double tracestart[3], traceend[3];
6616 VectorCopy(start, tracestart);
6617 VectorCopy(end, traceend);
6618 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6622 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)
6625 const bih_leaf_t *leaf;
6626 const bih_node_t *node;
6627 const colbrushf_t *brush;
6630 int nodestackpos = 0;
6631 int nodestack[1024];
6633 memset(trace, 0, sizeof(*trace));
6634 trace->fraction = 1;
6635 trace->hitsupercontentsmask = hitsupercontentsmask;
6637 bih = &model->collision_bih;
6641 nodenum = bih->rootnode;
6642 nodestack[nodestackpos++] = nodenum;
6643 while (nodestackpos)
6645 nodenum = nodestack[--nodestackpos];
6646 node = bih->nodes + nodenum;
6648 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6651 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6653 axis = node->type - BIH_SPLITX;
6654 if (start[axis] >= node->frontmin)
6655 nodestack[nodestackpos++] = node->front;
6656 if (start[axis] <= node->backmax)
6657 nodestack[nodestackpos++] = node->back;
6659 else if (node->type == BIH_UNORDERED)
6661 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6663 leaf = bih->leafs + node->children[axis];
6665 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6671 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6672 Collision_TracePointBrushFloat(trace, start, brush);
6674 case BIH_COLLISIONTRIANGLE:
6675 // collision triangle - skipped because they have no volume
6677 case BIH_RENDERTRIANGLE:
6678 // render triangle - skipped because they have no volume
6686 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, const bih_t *bih)
6688 const bih_leaf_t *leaf;
6689 const bih_node_t *node;
6690 const colbrushf_t *brush;
6692 const texture_t *texture;
6693 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6694 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6695 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6700 if (VectorCompare(start, end))
6702 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6706 nodenum = bih->rootnode;
6708 memset(trace, 0, sizeof(*trace));
6709 trace->fraction = 1;
6710 trace->hitsupercontentsmask = hitsupercontentsmask;
6713 nodestackline[nodestackpos][0] = start[0];
6714 nodestackline[nodestackpos][1] = start[1];
6715 nodestackline[nodestackpos][2] = start[2];
6716 nodestackline[nodestackpos][3] = end[0];
6717 nodestackline[nodestackpos][4] = end[1];
6718 nodestackline[nodestackpos][5] = end[2];
6719 nodestack[nodestackpos++] = nodenum;
6720 while (nodestackpos)
6722 nodenum = nodestack[--nodestackpos];
6723 node = bih->nodes + nodenum;
6724 VectorCopy(nodestackline[nodestackpos], nodestart);
6725 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6726 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6727 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6728 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6729 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6730 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6731 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6732 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6734 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6736 // recurse children of the split
6737 axis = node->type - BIH_SPLITX;
6738 d1 = node->backmax - nodestart[axis];
6739 d2 = node->backmax - nodeend[axis];
6740 d3 = nodestart[axis] - node->frontmin;
6741 d4 = nodeend[axis] - node->frontmin;
6742 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6744 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;
6745 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;
6746 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;
6747 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6748 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;
6749 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;
6750 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;
6751 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6752 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;
6753 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;
6754 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;
6755 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6756 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6757 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6758 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6759 case 15: /* <<<< */ break;
6762 else if (node->type == BIH_UNORDERED)
6764 // calculate sweep bounds for this node
6765 // copy node bounds into local variables
6766 VectorCopy(node->mins, nodebigmins);
6767 VectorCopy(node->maxs, nodebigmaxs);
6768 // clip line to this node bounds
6769 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); }
6770 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); }
6771 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); }
6772 // some of the line intersected the enlarged node box
6773 // calculate sweep bounds for this node
6774 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6775 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6776 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6777 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6778 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6779 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6780 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6782 leaf = bih->leafs + node->children[axis];
6783 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6788 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6789 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6791 case BIH_COLLISIONTRIANGLE:
6792 if (!mod_q3bsp_curves_collisions.integer)
6794 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6795 texture = model->data_textures + leaf->textureindex;
6796 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);
6798 case BIH_RENDERTRIANGLE:
6799 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6800 texture = model->data_textures + leaf->textureindex;
6801 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);
6809 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)
6811 if (VectorCompare(start, end))
6813 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6816 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6819 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)
6822 const bih_leaf_t *leaf;
6823 const bih_node_t *node;
6824 const colbrushf_t *brush;
6826 const texture_t *texture;
6827 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6828 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6829 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6830 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6832 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6834 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6835 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6837 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6841 bih = &model->collision_bih;
6844 nodenum = bih->rootnode;
6846 // box trace, performed as brush trace
6847 memset(trace, 0, sizeof(*trace));
6848 trace->fraction = 1;
6849 trace->hitsupercontentsmask = hitsupercontentsmask;
6851 // calculate tracebox-like parameters for efficient culling
6852 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6853 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6854 VectorSubtract(thisbrush_start->mins, start, startmins);
6855 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6856 VectorSubtract(thisbrush_end->mins, end, endmins);
6857 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6858 mins[0] = min(startmins[0], endmins[0]);
6859 mins[1] = min(startmins[1], endmins[1]);
6860 mins[2] = min(startmins[2], endmins[2]);
6861 maxs[0] = max(startmaxs[0], endmaxs[0]);
6862 maxs[1] = max(startmaxs[1], endmaxs[1]);
6863 maxs[2] = max(startmaxs[2], endmaxs[2]);
6866 nodestackline[nodestackpos][0] = start[0];
6867 nodestackline[nodestackpos][1] = start[1];
6868 nodestackline[nodestackpos][2] = start[2];
6869 nodestackline[nodestackpos][3] = end[0];
6870 nodestackline[nodestackpos][4] = end[1];
6871 nodestackline[nodestackpos][5] = end[2];
6872 nodestack[nodestackpos++] = nodenum;
6873 while (nodestackpos)
6875 nodenum = nodestack[--nodestackpos];
6876 node = bih->nodes + nodenum;
6877 VectorCopy(nodestackline[nodestackpos], nodestart);
6878 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6879 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
6880 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
6881 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
6882 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
6883 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
6884 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
6885 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6887 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6889 // recurse children of the split
6890 axis = node->type - BIH_SPLITX;
6891 d1 = node->backmax - nodestart[axis] - mins[axis];
6892 d2 = node->backmax - nodeend[axis] - mins[axis];
6893 d3 = nodestart[axis] - node->frontmin + maxs[axis];
6894 d4 = nodeend[axis] - node->frontmin + maxs[axis];
6895 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6897 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;
6898 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;
6899 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;
6900 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6901 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;
6902 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;
6903 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;
6904 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6905 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;
6906 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;
6907 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;
6908 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6909 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6910 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6911 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6912 case 15: /* <<<< */ break;
6915 else if (node->type == BIH_UNORDERED)
6917 // calculate sweep bounds for this node
6918 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6919 VectorSubtract(node->mins, maxs, nodebigmins);
6920 VectorSubtract(node->maxs, mins, nodebigmaxs);
6921 // clip line to this node bounds
6922 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); }
6923 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); }
6924 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); }
6925 // some of the line intersected the enlarged node box
6926 // calculate sweep bounds for this node
6927 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
6928 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
6929 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
6930 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
6931 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
6932 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
6933 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6935 leaf = bih->leafs + node->children[axis];
6936 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6941 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6942 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6944 case BIH_COLLISIONTRIANGLE:
6945 if (!mod_q3bsp_curves_collisions.integer)
6947 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6948 texture = model->data_textures + leaf->textureindex;
6949 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);
6951 case BIH_RENDERTRIANGLE:
6952 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6953 texture = model->data_textures + leaf->textureindex;
6954 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);
6962 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)
6964 colboxbrushf_t thisbrush_start, thisbrush_end;
6965 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6967 // box trace, performed as brush trace
6968 VectorAdd(start, boxmins, boxstartmins);
6969 VectorAdd(start, boxmaxs, boxstartmaxs);
6970 VectorAdd(end, boxmins, boxendmins);
6971 VectorAdd(end, boxmaxs, boxendmaxs);
6972 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6973 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6974 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6978 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6981 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6982 return trace.startsupercontents;
6985 qboolean Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6988 Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6989 return trace.fraction == 1;
6992 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)
6995 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6997 int hitsupercontents;
6998 VectorSet(end, start[0], start[1], model->normalmins[2]);
7000 memset(trace, 0, sizeof(*trace));
7001 trace->fraction = 1;
7002 trace->hitsupercontentsmask = hitsupercontentsmask;
7004 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
7005 hitsupercontents = trace->hitsupercontents;
7006 memset(trace, 0, sizeof(*trace));
7007 trace->fraction = 1;
7008 trace->hitsupercontentsmask = hitsupercontentsmask;
7009 trace->startsupercontents = hitsupercontents;
7013 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7016 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7019 VectorSet(end, start[0], start[1], model->normalmins[2]);
7020 memset(&trace, 0, sizeof(trace));
7022 trace.hitsupercontentsmask = 0;
7023 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
7024 return trace.hitsupercontents;
7030 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
7035 // find which leaf the point is in
7037 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7038 // point trace the brushes
7039 leaf = (mleaf_t *)node;
7040 for (i = 0;i < leaf->numleafbrushes;i++)
7042 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7043 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
7045 brush->markframe = markframe;
7046 Collision_TracePointBrushFloat(trace, point, brush);
7049 // can't do point traces on curves (they have no thickness)
7052 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)
7054 int i, startside, endside;
7055 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
7057 msurface_t *surface;
7060 // walk the tree until we hit a leaf, recursing for any split cases
7064 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7066 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7067 node = node->children[1];
7069 // abort if this part of the bsp tree can not be hit by this trace
7070 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7072 plane = node->plane;
7073 // axial planes are much more common than non-axial, so an optimized
7074 // axial case pays off here
7075 if (plane->type < 3)
7077 dist1 = start[plane->type] - plane->dist;
7078 dist2 = end[plane->type] - plane->dist;
7082 dist1 = DotProduct(start, plane->normal) - plane->dist;
7083 dist2 = DotProduct(end, plane->normal) - plane->dist;
7085 startside = dist1 < 0;
7086 endside = dist2 < 0;
7087 if (startside == endside)
7089 // most of the time the line fragment is on one side of the plane
7090 node = node->children[startside];
7094 // line crosses node plane, split the line
7095 dist1 = PlaneDiff(linestart, plane);
7096 dist2 = PlaneDiff(lineend, plane);
7097 midfrac = dist1 / (dist1 - dist2);
7098 VectorLerp(linestart, midfrac, lineend, mid);
7099 // take the near side first
7100 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7101 // if we found an impact on the front side, don't waste time
7102 // exploring the far side
7103 if (midfrac <= trace->fraction)
7104 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7109 // abort if this part of the bsp tree can not be hit by this trace
7110 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7113 nodesegmentmins[0] = min(start[0], end[0]) - 1;
7114 nodesegmentmins[1] = min(start[1], end[1]) - 1;
7115 nodesegmentmins[2] = min(start[2], end[2]) - 1;
7116 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
7117 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
7118 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
7119 // line trace the brushes
7120 leaf = (mleaf_t *)node;
7122 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7125 for (i = 0;i < leaf->numleafbrushes;i++)
7127 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7128 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7130 brush->markframe = markframe;
7131 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
7134 // can't do point traces on curves (they have no thickness)
7135 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
7137 // line trace the curves
7138 for (i = 0;i < leaf->numleafsurfaces;i++)
7140 surface = model->data_surfaces + leaf->firstleafsurface[i];
7141 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7143 surface->deprecatedq3collisionmarkframe = markframe;
7144 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);
7150 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)
7156 msurface_t *surface;
7158 float nodesegmentmins[3], nodesegmentmaxs[3];
7159 // walk the tree until we hit a leaf, recursing for any split cases
7163 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7165 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7166 node = node->children[1];
7168 // abort if this part of the bsp tree can not be hit by this trace
7169 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7171 plane = node->plane;
7172 // axial planes are much more common than non-axial, so an optimized
7173 // axial case pays off here
7174 if (plane->type < 3)
7176 // this is an axial plane, compare bounding box directly to it and
7177 // recurse sides accordingly
7178 // recurse down node sides
7179 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
7180 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
7181 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
7182 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
7186 // this is a non-axial plane, so check if the start and end boxes
7187 // are both on one side of the plane to handle 'diagonal' cases
7188 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
7192 // segment crosses plane
7193 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7196 // if sides == 0 then the trace itself is bogus (Not A Number values),
7197 // in this case we simply pretend the trace hit nothing
7199 return; // ERROR: NAN bounding box!
7200 // take whichever side the segment box is on
7201 node = node->children[sides - 1];
7204 // abort if this part of the bsp tree can not be hit by this trace
7205 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7207 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
7208 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
7209 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
7210 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
7211 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
7212 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
7214 leaf = (mleaf_t *)node;
7216 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7219 for (i = 0;i < leaf->numleafbrushes;i++)
7221 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7222 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7224 brush->markframe = markframe;
7225 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7228 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
7230 for (i = 0;i < leaf->numleafsurfaces;i++)
7232 surface = model->data_surfaces + leaf->firstleafsurface[i];
7233 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7235 surface->deprecatedq3collisionmarkframe = markframe;
7236 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);
7243 static int markframe = 0;
7245 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)
7249 memset(trace, 0, sizeof(*trace));
7250 trace->fraction = 1;
7251 trace->hitsupercontentsmask = hitsupercontentsmask;
7252 if (mod_collision_bih.integer)
7253 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
7254 else if (model->brush.submodel)
7256 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7257 if (brush->colbrushf)
7258 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
7261 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
7264 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)
7267 float segmentmins[3], segmentmaxs[3];
7268 msurface_t *surface;
7271 if (VectorCompare(start, end))
7273 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
7277 memset(trace, 0, sizeof(*trace));
7278 trace->fraction = 1;
7279 trace->hitsupercontentsmask = hitsupercontentsmask;
7280 segmentmins[0] = min(start[0], end[0]) - 1;
7281 segmentmins[1] = min(start[1], end[1]) - 1;
7282 segmentmins[2] = min(start[2], end[2]) - 1;
7283 segmentmaxs[0] = max(start[0], end[0]) + 1;
7284 segmentmaxs[1] = max(start[1], end[1]) + 1;
7285 segmentmaxs[2] = max(start[2], end[2]) + 1;
7286 if (mod_collision_bih.integer)
7287 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
7288 else if (model->brush.submodel)
7290 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7291 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7292 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7293 if (mod_q3bsp_curves_collisions.integer)
7294 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7295 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7296 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);
7299 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
7302 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)
7304 float segmentmins[3], segmentmaxs[3];
7306 msurface_t *surface;
7309 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
7311 if (VectorCompare(start->mins, end->mins))
7312 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
7314 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
7318 // box trace, performed as brush trace
7319 memset(trace, 0, sizeof(*trace));
7320 trace->fraction = 1;
7321 trace->hitsupercontentsmask = hitsupercontentsmask;
7322 segmentmins[0] = min(start->mins[0], end->mins[0]) - 1;
7323 segmentmins[1] = min(start->mins[1], end->mins[1]) - 1;
7324 segmentmins[2] = min(start->mins[2], end->mins[2]) - 1;
7325 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]) + 1;
7326 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]) + 1;
7327 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]) + 1;
7328 if (mod_collision_bih.integer)
7329 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
7330 else if (model->brush.submodel)
7332 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7333 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7334 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7335 if (mod_q3bsp_curves_collisions.integer)
7336 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7337 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7338 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);
7341 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
7344 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)
7346 colboxbrushf_t thisbrush_start, thisbrush_end;
7347 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7349 // box trace, performed as brush trace
7350 VectorAdd(start, boxmins, boxstartmins);
7351 VectorAdd(start, boxmaxs, boxstartmaxs);
7352 VectorAdd(end, boxmins, boxendmins);
7353 VectorAdd(end, boxmaxs, boxendmaxs);
7354 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7355 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7356 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
7359 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7362 int supercontents = 0;
7364 if (mod_collision_bih.integer)
7366 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
7368 // test if the point is inside each brush
7369 else if (model->brush.submodel)
7371 // submodels are effectively one leaf
7372 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7373 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7374 supercontents |= brush->colbrushf->supercontents;
7378 mnode_t *node = model->brush.data_nodes;
7380 // find which leaf the point is in
7382 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7383 leaf = (mleaf_t *)node;
7384 // now check the brushes in the leaf
7385 for (i = 0;i < leaf->numleafbrushes;i++)
7387 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
7388 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7389 supercontents |= brush->colbrushf->supercontents;
7392 return supercontents;
7395 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)
7397 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
7401 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
7409 int nummodelbrushes = model->nummodelbrushes;
7410 int nummodelsurfaces = model->nummodelsurfaces;
7412 const int *collisionelement3i;
7413 const float *collisionvertex3f;
7414 const int *renderelement3i;
7415 const float *rendervertex3f;
7416 bih_leaf_t *bihleafs;
7417 bih_node_t *bihnodes;
7419 int *temp_leafsortscratch;
7420 const msurface_t *surface;
7421 const q3mbrush_t *brush;
7423 // find out how many BIH leaf nodes we need
7425 if (userendersurfaces)
7427 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7428 bihnumleafs += surface->num_triangles;
7432 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7433 if (brush->colbrushf)
7435 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7437 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7438 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7440 bihnumleafs += surface->num_collisiontriangles;
7447 // allocate the memory for the BIH leaf nodes
7448 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7450 // now populate the BIH leaf nodes
7453 // add render surfaces
7454 renderelement3i = model->surfmesh.data_element3i;
7455 rendervertex3f = model->surfmesh.data_vertex3f;
7456 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7458 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7460 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7462 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7463 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7464 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7465 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7466 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7467 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7468 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7469 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7470 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7471 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7476 if (!userendersurfaces)
7478 // add collision brushes
7479 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7481 if (!brush->colbrushf)
7483 bihleafs[bihleafindex].type = BIH_BRUSH;
7484 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7485 bihleafs[bihleafindex].surfaceindex = -1;
7486 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7487 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7488 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7492 // add collision surfaces
7493 collisionelement3i = model->brush.data_collisionelement3i;
7494 collisionvertex3f = model->brush.data_collisionvertex3f;
7495 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7497 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7499 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7500 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7501 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7502 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7503 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7504 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7505 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7506 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7507 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7508 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7514 // allocate buffers for the produced and temporary data
7515 bihmaxnodes = bihnumleafs + 1;
7516 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7517 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7518 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7521 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7523 // we're done with the temporary data
7524 Mem_Free(temp_leafsort);
7526 // resize the BIH nodes array if it over-allocated
7527 if (out->maxnodes > out->numnodes)
7529 out->maxnodes = out->numnodes;
7530 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7536 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7538 int supercontents = 0;
7539 if (nativecontents & CONTENTSQ3_SOLID)
7540 supercontents |= SUPERCONTENTS_SOLID;
7541 if (nativecontents & CONTENTSQ3_WATER)
7542 supercontents |= SUPERCONTENTS_WATER;
7543 if (nativecontents & CONTENTSQ3_SLIME)
7544 supercontents |= SUPERCONTENTS_SLIME;
7545 if (nativecontents & CONTENTSQ3_LAVA)
7546 supercontents |= SUPERCONTENTS_LAVA;
7547 if (nativecontents & CONTENTSQ3_BODY)
7548 supercontents |= SUPERCONTENTS_BODY;
7549 if (nativecontents & CONTENTSQ3_CORPSE)
7550 supercontents |= SUPERCONTENTS_CORPSE;
7551 if (nativecontents & CONTENTSQ3_NODROP)
7552 supercontents |= SUPERCONTENTS_NODROP;
7553 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7554 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7555 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7556 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7557 if (nativecontents & CONTENTSQ3_DONOTENTER)
7558 supercontents |= SUPERCONTENTS_DONOTENTER;
7559 if (nativecontents & CONTENTSQ3_BOTCLIP)
7560 supercontents |= SUPERCONTENTS_BOTCLIP;
7561 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7562 supercontents |= SUPERCONTENTS_OPAQUE;
7563 return supercontents;
7566 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7568 int nativecontents = 0;
7569 if (supercontents & SUPERCONTENTS_SOLID)
7570 nativecontents |= CONTENTSQ3_SOLID;
7571 if (supercontents & SUPERCONTENTS_WATER)
7572 nativecontents |= CONTENTSQ3_WATER;
7573 if (supercontents & SUPERCONTENTS_SLIME)
7574 nativecontents |= CONTENTSQ3_SLIME;
7575 if (supercontents & SUPERCONTENTS_LAVA)
7576 nativecontents |= CONTENTSQ3_LAVA;
7577 if (supercontents & SUPERCONTENTS_BODY)
7578 nativecontents |= CONTENTSQ3_BODY;
7579 if (supercontents & SUPERCONTENTS_CORPSE)
7580 nativecontents |= CONTENTSQ3_CORPSE;
7581 if (supercontents & SUPERCONTENTS_NODROP)
7582 nativecontents |= CONTENTSQ3_NODROP;
7583 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7584 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7585 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7586 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7587 if (supercontents & SUPERCONTENTS_DONOTENTER)
7588 nativecontents |= CONTENTSQ3_DONOTENTER;
7589 if (supercontents & SUPERCONTENTS_BOTCLIP)
7590 nativecontents |= CONTENTSQ3_BOTCLIP;
7591 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7592 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7593 return nativecontents;
7596 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7601 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7602 node = node->children[1];
7604 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7605 if (loadmodel->brush.num_leafs < numleafs)
7606 loadmodel->brush.num_leafs = numleafs;
7609 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7612 q3dheader_t *header;
7613 float corner[3], yawradius, modelradius;
7615 mod->modeldatatypestring = "Q3BSP";
7617 mod->type = mod_brushq3;
7618 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7621 header = (q3dheader_t *)buffer;
7622 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7623 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7625 i = LittleLong(header->version);
7626 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7627 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7629 mod->soundfromcenter = true;
7630 mod->TraceBox = Mod_Q3BSP_TraceBox;
7631 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7632 mod->TraceLine = Mod_Q3BSP_TraceLine;
7633 mod->TracePoint = Mod_Q3BSP_TracePoint;
7634 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7635 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7636 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7637 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7638 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7639 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7640 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7641 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7642 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7643 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7644 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7645 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7646 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7647 mod->brush.AmbientSoundLevelsForPoint = NULL;
7648 mod->brush.RoundUpToHullSize = NULL;
7649 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7650 mod->Draw = R_Q1BSP_Draw;
7651 mod->DrawDepth = R_Q1BSP_DrawDepth;
7652 mod->DrawDebug = R_Q1BSP_DrawDebug;
7653 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7654 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7655 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7656 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7657 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7658 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7659 mod->DrawLight = R_Q1BSP_DrawLight;
7661 mod_base = (unsigned char *)header;
7663 // swap all the lumps
7664 header->ident = LittleLong(header->ident);
7665 header->version = LittleLong(header->version);
7666 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7667 for (i = 0;i < lumps;i++)
7669 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7670 if((char *) bufferend < (char *) buffer + j)
7671 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7672 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7673 if((char *) bufferend < (char *) buffer + j)
7674 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7677 * NO, do NOT clear them!
7678 * they contain actual data referenced by other stuff.
7679 * Instead, before using the advertisements lump, check header->versio
7681 * Sorry, but otherwise it breaks memory of the first lump.
7682 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7684 header->lumps[i].fileofs = 0;
7685 header->lumps[i].filelen = 0;
7689 mod->brush.qw_md4sum = 0;
7690 mod->brush.qw_md4sum2 = 0;
7691 for (i = 0;i < lumps;i++)
7693 if (i == Q3LUMP_ENTITIES)
7695 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7696 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7698 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7700 // all this checksumming can take a while, so let's send keepalives here too
7701 CL_KeepaliveMessage(false);
7704 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7705 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7706 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7707 if (header->version == Q3BSPVERSION_IG)
7708 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7710 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7711 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7712 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7713 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7714 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7715 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7716 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7717 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7718 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7719 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7720 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7721 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7722 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7723 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7724 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7726 // the MakePortals code works fine on the q3bsp data as well
7727 if (mod_bsp_portalize.integer)
7728 Mod_Q1BSP_MakePortals();
7730 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7731 loadmodel->brush.supportwateralpha = true;
7733 // make a single combined shadow mesh to allow optimized shadow volume creation
7734 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7736 loadmodel->brush.num_leafs = 0;
7737 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7739 if (loadmodel->brush.numsubmodels)
7740 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7743 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7748 // duplicate the basic information
7749 dpsnprintf(name, sizeof(name), "*%i", i);
7750 mod = Mod_FindName(name, loadmodel->name);
7751 // copy the base model to this one
7753 // rename the clone back to its proper name
7754 strlcpy(mod->name, name, sizeof(mod->name));
7755 mod->brush.parentmodel = loadmodel;
7756 // textures and memory belong to the main model
7757 mod->texturepool = NULL;
7758 mod->mempool = NULL;
7759 mod->brush.GetPVS = NULL;
7760 mod->brush.FatPVS = NULL;
7761 mod->brush.BoxTouchingPVS = NULL;
7762 mod->brush.BoxTouchingLeafPVS = NULL;
7763 mod->brush.BoxTouchingVisibleLeafs = NULL;
7764 mod->brush.FindBoxClusters = NULL;
7765 mod->brush.LightPoint = NULL;
7766 mod->brush.AmbientSoundLevelsForPoint = NULL;
7768 mod->brush.submodel = i;
7769 if (loadmodel->brush.submodels)
7770 loadmodel->brush.submodels[i] = mod;
7772 // make the model surface list (used by shadowing/lighting)
7773 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7774 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7775 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7776 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7777 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7778 Mod_MakeSortedSurfaces(mod);
7780 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7781 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7782 // enlarge the bounding box to enclose all geometry of this model,
7783 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7784 // which can in turn mess up the farclip (as well as culling when
7785 // outside the level - an unimportant concern)
7787 //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]);
7788 for (j = 0;j < mod->nummodelsurfaces;j++)
7790 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7791 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7793 if (!surface->num_vertices)
7795 for (k = 0;k < surface->num_vertices;k++, v += 3)
7797 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7798 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7799 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7800 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7801 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7802 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7805 //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]);
7806 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7807 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7808 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7809 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7810 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7811 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7812 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7813 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7814 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7815 mod->yawmins[2] = mod->normalmins[2];
7816 mod->yawmaxs[2] = mod->normalmaxs[2];
7817 mod->radius = modelradius;
7818 mod->radius2 = modelradius * modelradius;
7820 // this gets altered below if sky or water is used
7821 mod->DrawSky = NULL;
7822 mod->DrawAddWaterPlanes = NULL;
7824 for (j = 0;j < mod->nummodelsurfaces;j++)
7825 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7827 if (j < mod->nummodelsurfaces)
7828 mod->DrawSky = R_Q1BSP_DrawSky;
7830 for (j = 0;j < mod->nummodelsurfaces;j++)
7831 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7833 if (j < mod->nummodelsurfaces)
7834 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7836 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7837 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7839 // generate VBOs and other shared data before cloning submodels
7844 if (mod_q3bsp_sRGBlightmaps.integer)
7846 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7848 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7849 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7850 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7851 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7852 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7854 else // if this is NOT set, regular rendering looks right by this requirement anyway
7857 // we want color 1 to do the same as without sRGB
7858 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7859 loadmodel->lightmapscale *= 2.476923f; // fixes max level
7862 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7863 // we need to undo that
7864 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7868 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);
7871 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7873 int i = LittleLong(((int *)buffer)[1]);
7874 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7875 Mod_Q3BSP_Load(mod,buffer, bufferend);
7876 else if (i == Q2BSPVERSION)
7877 Mod_Q2BSP_Load(mod,buffer, bufferend);
7879 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7882 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7884 Host_Error("Mod_MAP_Load: not yet implemented");
7887 typedef struct objvertex_s
7898 static unsigned char nobsp_pvs[1] = {1};
7900 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7902 const char *textbase = (char *)buffer, *text = textbase;
7906 char materialname[MAX_QPATH];
7907 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7908 int index1, index2, index3;
7909 objvertex_t vfirst, vprev, vcurrent;
7912 int numtriangles = 0;
7913 int maxtriangles = 0;
7914 objvertex_t *vertices = NULL;
7916 int maxtextures = 0, numtextures = 0, textureindex = 0;
7917 int maxv = 0, numv = 1;
7918 int maxvt = 0, numvt = 1;
7919 int maxvn = 0, numvn = 1;
7920 char *texturenames = NULL;
7921 float dist, modelradius, modelyawradius, yawradius;
7928 objvertex_t *thisvertex = NULL;
7929 int vertexhashindex;
7930 int *vertexhashtable = NULL;
7931 objvertex_t *vertexhashdata = NULL;
7932 objvertex_t *vdata = NULL;
7933 int vertexhashsize = 0;
7934 int vertexhashcount = 0;
7935 skinfile_t *skinfiles = NULL;
7936 unsigned char *data = NULL;
7937 int *submodelfirstsurface;
7938 msurface_t *surface;
7939 msurface_t *tempsurfaces;
7941 memset(&vfirst, 0, sizeof(vfirst));
7942 memset(&vprev, 0, sizeof(vprev));
7943 memset(&vcurrent, 0, sizeof(vcurrent));
7945 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7947 loadmodel->modeldatatypestring = "OBJ";
7949 loadmodel->type = mod_obj;
7950 loadmodel->soundfromcenter = true;
7951 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7952 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7953 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7954 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7955 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7956 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7957 loadmodel->brush.TraceLineOfSight = NULL;
7958 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7959 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7960 loadmodel->brush.GetPVS = NULL;
7961 loadmodel->brush.FatPVS = NULL;
7962 loadmodel->brush.BoxTouchingPVS = NULL;
7963 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7964 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7965 loadmodel->brush.FindBoxClusters = NULL;
7966 loadmodel->brush.LightPoint = NULL;
7967 loadmodel->brush.FindNonSolidLocation = NULL;
7968 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7969 loadmodel->brush.RoundUpToHullSize = NULL;
7970 loadmodel->brush.PointInLeaf = NULL;
7971 loadmodel->Draw = R_Q1BSP_Draw;
7972 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7973 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7974 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7975 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7976 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7977 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7978 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7979 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7980 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7982 skinfiles = Mod_LoadSkinFiles();
7983 if (loadmodel->numskins < 1)
7984 loadmodel->numskins = 1;
7986 // make skinscenes for the skins (no groups)
7987 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7988 for (i = 0;i < loadmodel->numskins;i++)
7990 loadmodel->skinscenes[i].firstframe = i;
7991 loadmodel->skinscenes[i].framecount = 1;
7992 loadmodel->skinscenes[i].loop = true;
7993 loadmodel->skinscenes[i].framerate = 10;
7999 // we always have model 0, i.e. the first "submodel"
8000 loadmodel->brush.numsubmodels = 1;
8002 // parse the OBJ text now
8005 static char emptyarg[1] = "";
8010 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8011 line[linelen] = text[linelen];
8013 for (argc = 0;argc < 4;argc++)
8014 argv[argc] = emptyarg;
8017 while (*s == ' ' || *s == '\t')
8027 while (*s == ' ' || *s == '\t')
8037 if (argv[0][0] == '#')
8039 if (!strcmp(argv[0], "v"))
8043 maxv = max(maxv * 2, 1024);
8044 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
8046 if(mod_obj_orientation.integer)
8048 v[numv*3+0] = atof(argv[1]);
8049 v[numv*3+2] = atof(argv[2]);
8050 v[numv*3+1] = atof(argv[3]);
8054 v[numv*3+0] = atof(argv[1]);
8055 v[numv*3+1] = atof(argv[2]);
8056 v[numv*3+2] = atof(argv[3]);
8060 else if (!strcmp(argv[0], "vt"))
8064 maxvt = max(maxvt * 2, 1024);
8065 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
8067 vt[numvt*2+0] = atof(argv[1]);
8068 vt[numvt*2+1] = 1-atof(argv[2]);
8071 else if (!strcmp(argv[0], "vn"))
8075 maxvn = max(maxvn * 2, 1024);
8076 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
8078 if(mod_obj_orientation.integer)
8080 vn[numvn*3+0] = atof(argv[1]);
8081 vn[numvn*3+2] = atof(argv[2]);
8082 vn[numvn*3+1] = atof(argv[3]);
8086 vn[numvn*3+0] = atof(argv[1]);
8087 vn[numvn*3+1] = atof(argv[2]);
8088 vn[numvn*3+2] = atof(argv[3]);
8092 else if (!strcmp(argv[0], "f"))
8096 if (maxtextures <= numtextures)
8098 maxtextures = max(maxtextures * 2, 256);
8099 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8101 textureindex = numtextures++;
8102 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
8104 for (j = 1;j < argc;j++)
8106 index1 = atoi(argv[j]);
8107 while(argv[j][0] && argv[j][0] != '/')
8111 index2 = atoi(argv[j]);
8112 while(argv[j][0] && argv[j][0] != '/')
8116 index3 = atoi(argv[j]);
8117 // negative refers to a recent vertex
8118 // zero means not specified
8119 // positive means an absolute vertex index
8121 index1 = numv - index1;
8123 index2 = numvt - index2;
8125 index3 = numvn - index3;
8126 vcurrent.nextindex = -1;
8127 vcurrent.textureindex = textureindex;
8128 vcurrent.submodelindex = submodelindex;
8129 if (v && index1 >= 0 && index1 < numv)
8130 VectorCopy(v + 3*index1, vcurrent.v);
8131 if (vt && index2 >= 0 && index2 < numvt)
8132 Vector2Copy(vt + 2*index2, vcurrent.vt);
8133 if (vn && index3 >= 0 && index3 < numvn)
8134 VectorCopy(vn + 3*index3, vcurrent.vn);
8135 if (numtriangles == 0)
8137 VectorCopy(vcurrent.v, mins);
8138 VectorCopy(vcurrent.v, maxs);
8142 mins[0] = min(mins[0], vcurrent.v[0]);
8143 mins[1] = min(mins[1], vcurrent.v[1]);
8144 mins[2] = min(mins[2], vcurrent.v[2]);
8145 maxs[0] = max(maxs[0], vcurrent.v[0]);
8146 maxs[1] = max(maxs[1], vcurrent.v[1]);
8147 maxs[2] = max(maxs[2], vcurrent.v[2]);
8153 if (maxtriangles <= numtriangles)
8155 maxtriangles = max(maxtriangles * 2, 32768);
8156 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8158 if(mod_obj_orientation.integer)
8160 vertices[numtriangles*3+0] = vfirst;
8161 vertices[numtriangles*3+1] = vprev;
8162 vertices[numtriangles*3+2] = vcurrent;
8166 vertices[numtriangles*3+0] = vfirst;
8167 vertices[numtriangles*3+2] = vprev;
8168 vertices[numtriangles*3+1] = vcurrent;
8175 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8177 submodelindex = atof(argv[1]);
8178 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8180 else if (!strcmp(argv[0], "usemtl"))
8182 for (i = 0;i < numtextures;i++)
8183 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8185 if (i < numtextures)
8189 if (maxtextures <= numtextures)
8191 maxtextures = max(maxtextures * 2, 256);
8192 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8194 textureindex = numtextures++;
8195 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8200 // now that we have the OBJ data loaded as-is, we can convert it
8202 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8203 VectorCopy(mins, loadmodel->normalmins);
8204 VectorCopy(maxs, loadmodel->normalmaxs);
8205 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8206 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8207 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8208 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8209 modelradius = modelyawradius + modelradius * modelradius;
8210 modelyawradius = sqrt(modelyawradius);
8211 modelradius = sqrt(modelradius);
8212 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8213 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8214 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8215 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8216 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8217 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8218 loadmodel->radius = modelradius;
8219 loadmodel->radius2 = modelradius * modelradius;
8221 // allocate storage for triangles
8222 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8223 // allocate vertex hash structures to build an optimal vertex subset
8224 vertexhashsize = numtriangles*2;
8225 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8226 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8227 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8228 vertexhashcount = 0;
8230 // gather surface stats for assigning vertex/triangle ranges
8234 loadmodel->num_surfaces = 0;
8235 // allocate storage for the worst case number of surfaces, later we resize
8236 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8237 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8238 surface = tempsurfaces;
8239 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8241 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8242 for (textureindex = 0;textureindex < numtextures;textureindex++)
8244 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8246 thisvertex = vertices + vertexindex;
8247 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8250 // skip the surface creation if there are no triangles for it
8251 if (vertexindex == numtriangles*3)
8253 // create a surface for these vertices
8254 surfacevertices = 0;
8255 surfaceelements = 0;
8256 // we hack in a texture index in the surface to be fixed up later...
8257 surface->texture = (texture_t *)((size_t)textureindex);
8258 // calculate bounds as we go
8259 VectorCopy(thisvertex->v, surface->mins);
8260 VectorCopy(thisvertex->v, surface->maxs);
8261 for (;vertexindex < numtriangles*3;vertexindex++)
8263 thisvertex = vertices + vertexindex;
8264 if (thisvertex->submodelindex != submodelindex)
8266 if (thisvertex->textureindex != textureindex)
8268 // add vertex to surface bounds
8269 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
8270 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
8271 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
8272 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
8273 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
8274 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
8275 // add the vertex if it is not found in the merged set, and
8276 // get its index (triangle element) for the surface
8277 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8278 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8280 vdata = vertexhashdata + i;
8281 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8286 i = vertexhashcount++;
8287 vdata = vertexhashdata + i;
8288 *vdata = *thisvertex;
8289 vdata->nextindex = vertexhashtable[vertexhashindex];
8290 vertexhashtable[vertexhashindex] = i;
8293 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8296 surfacetriangles = surfaceelements / 3;
8297 surface->num_vertices = surfacevertices;
8298 surface->num_triangles = surfacetriangles;
8299 surface->num_firstvertex = firstvertex;
8300 surface->num_firsttriangle = firsttriangle;
8301 firstvertex += surface->num_vertices;
8302 firsttriangle += surface->num_triangles;
8304 loadmodel->num_surfaces++;
8307 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8308 numvertices = firstvertex;
8309 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8310 tempsurfaces = NULL;
8312 // allocate storage for final mesh data
8313 loadmodel->num_textures = numtextures * loadmodel->numskins;
8314 loadmodel->num_texturesperskin = numtextures;
8315 data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0) + (r_enableshadowvolumes.integer ? numtriangles * sizeof(int[3]) : 0) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8316 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
8317 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8318 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8319 loadmodel->surfmesh.num_vertices = numvertices;
8320 loadmodel->surfmesh.num_triangles = numtriangles;
8321 if (r_enableshadowvolumes.integer)
8322 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
8323 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8324 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8325 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8326 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8327 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8328 if (loadmodel->surfmesh.num_vertices <= 65536)
8329 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8331 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8333 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8334 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8335 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8338 // load the textures
8339 for (textureindex = 0;textureindex < numtextures;textureindex++)
8340 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8341 Mod_FreeSkinFiles(skinfiles);
8343 // set the surface textures to their real values now that we loaded them...
8344 for (i = 0;i < loadmodel->num_surfaces;i++)
8345 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8349 Mem_Free(texturenames);
8353 Mem_Free(vertexhashtable);
8354 Mem_Free(vertexhashdata);
8356 // make a single combined shadow mesh to allow optimized shadow volume creation
8357 Mod_Q1BSP_CreateShadowMesh(loadmodel);
8359 // compute all the mesh information that was not loaded from the file
8360 if (loadmodel->surfmesh.data_element3s)
8361 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8362 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8363 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8364 // generate normals if the file did not have them
8365 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8366 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);
8367 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);
8368 if (loadmodel->surfmesh.data_neighbor3i)
8369 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8371 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8372 loadmodel->brush.num_visleafs = 1;
8373 loadmodel->brush.num_leafs = 1;
8374 loadmodel->brush.num_nodes = 0;
8375 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8376 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8377 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8378 loadmodel->brush.num_pvsclusters = 1;
8379 loadmodel->brush.num_pvsclusterbytes = 1;
8380 loadmodel->brush.data_pvsclusters = nobsp_pvs;
8381 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8382 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8383 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
8384 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8385 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8386 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8387 loadmodel->brush.data_leafs->clusterindex = 0;
8388 loadmodel->brush.data_leafs->areaindex = 0;
8389 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8390 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8391 loadmodel->brush.data_leafs->numleafbrushes = 0;
8392 loadmodel->brush.data_leafs->firstleafbrush = NULL;
8393 loadmodel->brush.supportwateralpha = true;
8395 if (loadmodel->brush.numsubmodels)
8396 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8399 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8404 // duplicate the basic information
8405 dpsnprintf(name, sizeof(name), "*%i", i);
8406 mod = Mod_FindName(name, loadmodel->name);
8407 // copy the base model to this one
8409 // rename the clone back to its proper name
8410 strlcpy(mod->name, name, sizeof(mod->name));
8411 mod->brush.parentmodel = loadmodel;
8412 // textures and memory belong to the main model
8413 mod->texturepool = NULL;
8414 mod->mempool = NULL;
8415 mod->brush.GetPVS = NULL;
8416 mod->brush.FatPVS = NULL;
8417 mod->brush.BoxTouchingPVS = NULL;
8418 mod->brush.BoxTouchingLeafPVS = NULL;
8419 mod->brush.BoxTouchingVisibleLeafs = NULL;
8420 mod->brush.FindBoxClusters = NULL;
8421 mod->brush.LightPoint = NULL;
8422 mod->brush.AmbientSoundLevelsForPoint = NULL;
8424 mod->brush.submodel = i;
8425 if (loadmodel->brush.submodels)
8426 loadmodel->brush.submodels[i] = mod;
8428 // make the model surface list (used by shadowing/lighting)
8429 mod->firstmodelsurface = submodelfirstsurface[i];
8430 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8431 mod->firstmodelbrush = 0;
8432 mod->nummodelbrushes = 0;
8433 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8434 Mod_MakeSortedSurfaces(mod);
8436 VectorClear(mod->normalmins);
8437 VectorClear(mod->normalmaxs);
8439 for (j = 0;j < mod->nummodelsurfaces;j++)
8441 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8442 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8444 if (!surface->num_vertices)
8449 VectorCopy(v, mod->normalmins);
8450 VectorCopy(v, mod->normalmaxs);
8452 for (k = 0;k < surface->num_vertices;k++, v += 3)
8454 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
8455 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
8456 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
8457 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
8458 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
8459 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
8462 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8463 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8464 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8465 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8466 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8467 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8468 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8469 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8470 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8471 mod->yawmins[2] = mod->normalmins[2];
8472 mod->yawmaxs[2] = mod->normalmaxs[2];
8473 mod->radius = modelradius;
8474 mod->radius2 = modelradius * modelradius;
8476 // this gets altered below if sky or water is used
8477 mod->DrawSky = NULL;
8478 mod->DrawAddWaterPlanes = NULL;
8480 for (j = 0;j < mod->nummodelsurfaces;j++)
8481 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8483 if (j < mod->nummodelsurfaces)
8484 mod->DrawSky = R_Q1BSP_DrawSky;
8486 for (j = 0;j < mod->nummodelsurfaces;j++)
8487 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8489 if (j < mod->nummodelsurfaces)
8490 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8492 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8493 mod->render_bih = mod->collision_bih;
8495 // generate VBOs and other shared data before cloning submodels
8500 Mem_Free(submodelfirstsurface);
8502 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);