2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
30 cvar_t mod_bsp_portalize = {0, "mod_bsp_portalize", "1", "enables portal generation from BSP tree (may take several seconds per map), used by r_drawportals, r_useportalculling, r_shadow_realtime_world_compileportalculling, sv_cullentities_portal"};
31 cvar_t r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
34 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
35 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
38 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
39 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
40 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t r_trippy = {0, "r_trippy", "0", "easter egg"};
42 cvar_t r_fxaa = {CVAR_SAVE, "r_fxaa", "0", "fast approximate anti aliasing"};
43 cvar_t mod_noshader_default_offsetmapping = {CVAR_SAVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
44 cvar_t mod_obj_orientation = {0, "mod_obj_orientation", "1", "fix orientation of OBJ models to the usual conventions (if zero, use coordinates as is)"};
45 cvar_t mod_q2bsp_littransparentsurfaces = {0, "mod_q2bsp_littransparentsurfaces", "0", "allows lighting on rain in 3v3gloom3 and other cases of transparent surfaces that have lightmaps that were ignored by quake2"};
46 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
47 cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
48 cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
49 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
50 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
51 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
52 cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
53 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
54 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
55 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
56 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
57 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
58 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
59 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
60 cvar_t mod_q3shader_force_addalpha = {0, "mod_q3shader_force_addalpha", "0", "treat GL_ONE GL_ONE (or add) blendfunc as GL_SRC_ALPHA GL_ONE for compatibility with older DarkPlaces releases"};
61 cvar_t mod_q3shader_force_terrain_alphaflag = {0, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
63 cvar_t mod_q1bsp_polygoncollisions = {0, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
64 cvar_t mod_collision_bih = {0, "mod_collision_bih", "1", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
65 cvar_t mod_recalculatenodeboxes = {0, "mod_recalculatenodeboxes", "1", "enables use of generated node bounding boxes based on BSP tree portal reconstruction, rather than the node boxes supplied by the map compiler"};
67 static texture_t mod_q1bsp_texture_solid;
68 static texture_t mod_q1bsp_texture_sky;
69 static texture_t mod_q1bsp_texture_lava;
70 static texture_t mod_q1bsp_texture_slime;
71 static texture_t mod_q1bsp_texture_water;
73 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end);
75 void Mod_BrushInit(void)
77 // Cvar_RegisterVariable(&r_subdivide_size);
78 Cvar_RegisterVariable(&mod_bsp_portalize);
79 Cvar_RegisterVariable(&r_novis);
80 Cvar_RegisterVariable(&r_nosurftextures);
81 Cvar_RegisterVariable(&r_subdivisions_tolerance);
82 Cvar_RegisterVariable(&r_subdivisions_mintess);
83 Cvar_RegisterVariable(&r_subdivisions_maxtess);
84 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
85 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
86 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
87 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
88 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
89 Cvar_RegisterVariable(&r_trippy);
90 Cvar_RegisterVariable(&r_fxaa);
91 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
92 Cvar_RegisterVariable(&mod_obj_orientation);
93 Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
94 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
95 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
96 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
97 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
98 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
99 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
100 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
101 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
102 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
103 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
104 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
105 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
106 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
107 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
108 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
109 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
110 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
111 Cvar_RegisterVariable(&mod_collision_bih);
112 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
114 // these games were made for older DP engines and are no longer
115 // maintained; use this hack to show their textures properly
116 if(gamemode == GAME_NEXUIZ)
117 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
119 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
120 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
121 mod_q1bsp_texture_solid.surfaceflags = 0;
122 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
124 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
125 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
126 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
127 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
129 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
130 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
131 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
132 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
134 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
135 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
136 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
137 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
139 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
140 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
141 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
142 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
145 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
152 // LordHavoc: modified to start at first clip node,
153 // in other words: first node of the (sub)model
154 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
156 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
158 return (mleaf_t *)node;
161 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
165 leaf = Mod_Q1BSP_PointInLeaf(model, p);
168 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
171 memcpy(out, leaf->ambient_sound_level, i);
177 memset(out, 0, outsize);
180 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
183 int nodestackindex = 0;
184 mnode_t *node, *nodestack[1024];
185 if (!model->brush.num_pvsclusters)
187 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
193 // node - recurse down the BSP tree
194 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
198 return -1; // ERROR: NAN bounding box!
199 // box is on one side of plane, take that path
200 node = node->children[sides-1];
204 // box crosses plane, take one path and remember the other
205 if (nodestackindex < 1024)
206 nodestack[nodestackindex++] = node->children[0];
207 node = node->children[1];
213 // leaf - add clusterindex to list
214 if (numclusters < maxclusters)
215 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
219 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
223 if (nodestackindex < 1024)
224 nodestack[nodestackindex++] = node->children[0];
225 node = node->children[1];
230 // leaf - add clusterindex to list
231 if (numclusters < maxclusters)
232 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
237 // try another path we didn't take earlier
238 if (nodestackindex == 0)
240 node = nodestack[--nodestackindex];
242 // return number of clusters found (even if more than the maxclusters)
246 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
248 int nodestackindex = 0;
249 mnode_t *node, *nodestack[1024];
250 if (!model->brush.num_pvsclusters)
252 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
258 // node - recurse down the BSP tree
259 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
263 return -1; // ERROR: NAN bounding box!
264 // box is on one side of plane, take that path
265 node = node->children[sides-1];
269 // box crosses plane, take one path and remember the other
270 if (nodestackindex < 1024)
271 nodestack[nodestackindex++] = node->children[0];
272 node = node->children[1];
278 // leaf - check cluster bit
279 int clusterindex = ((mleaf_t *)node)->clusterindex;
280 if (CHECKPVSBIT(pvs, clusterindex))
282 // it is visible, return immediately with the news
287 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
291 if (nodestackindex < 1024)
292 nodestack[nodestackindex++] = node->children[0];
293 node = node->children[1];
298 // leaf - check cluster bit
299 int clusterindex = ((mleaf_t *)node)->clusterindex;
300 if (CHECKPVSBIT(pvs, clusterindex))
302 // it is visible, return immediately with the news
308 // nothing to see here, try another path we didn't take earlier
309 if (nodestackindex == 0)
311 node = nodestack[--nodestackindex];
317 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
319 int nodestackindex = 0;
320 mnode_t *node, *nodestack[1024];
321 if (!model->brush.num_leafs)
323 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
329 // node - recurse down the BSP tree
330 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
334 return -1; // ERROR: NAN bounding box!
335 // box is on one side of plane, take that path
336 node = node->children[sides-1];
340 // box crosses plane, take one path and remember the other
341 if (nodestackindex < 1024)
342 nodestack[nodestackindex++] = node->children[0];
343 node = node->children[1];
349 // leaf - check cluster bit
350 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
351 if (CHECKPVSBIT(pvs, clusterindex))
353 // it is visible, return immediately with the news
358 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
362 if (nodestackindex < 1024)
363 nodestack[nodestackindex++] = node->children[0];
364 node = node->children[1];
369 // leaf - check cluster bit
370 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
371 if (CHECKPVSBIT(pvs, clusterindex))
373 // it is visible, return immediately with the news
379 // nothing to see here, try another path we didn't take earlier
380 if (nodestackindex == 0)
382 node = nodestack[--nodestackindex];
388 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
390 int nodestackindex = 0;
391 mnode_t *node, *nodestack[1024];
392 if (!model->brush.num_leafs)
394 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
400 // node - recurse down the BSP tree
401 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
405 return -1; // ERROR: NAN bounding box!
406 // box is on one side of plane, take that path
407 node = node->children[sides-1];
411 // box crosses plane, take one path and remember the other
412 if (nodestackindex < 1024)
413 nodestack[nodestackindex++] = node->children[0];
414 node = node->children[1];
420 // leaf - check if it is visible
421 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
423 // it is visible, return immediately with the news
428 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
432 if (nodestackindex < 1024)
433 nodestack[nodestackindex++] = node->children[0];
434 node = node->children[1];
439 // leaf - check if it is visible
440 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
442 // it is visible, return immediately with the news
448 // nothing to see here, try another path we didn't take earlier
449 if (nodestackindex == 0)
451 node = nodestack[--nodestackindex];
457 typedef struct findnonsolidlocationinfo_s
460 vec3_t absmin, absmax;
466 findnonsolidlocationinfo_t;
468 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
471 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
473 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
474 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
475 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
476 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
477 VectorSubtract(vert[1], vert[0], edge[0]);
478 VectorSubtract(vert[2], vert[1], edge[1]);
479 CrossProduct(edge[1], edge[0], facenormal);
480 if (facenormal[0] || facenormal[1] || facenormal[2])
482 VectorNormalize(facenormal);
483 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
484 if (f <= info->bestdist && f >= -info->bestdist)
486 VectorSubtract(vert[0], vert[2], edge[2]);
487 VectorNormalize(edge[0]);
488 VectorNormalize(edge[1]);
489 VectorNormalize(edge[2]);
490 CrossProduct(facenormal, edge[0], edgenormal[0]);
491 CrossProduct(facenormal, edge[1], edgenormal[1]);
492 CrossProduct(facenormal, edge[2], edgenormal[2]);
494 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
495 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
496 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
498 // we got lucky, the center is within the face
499 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
503 if (info->bestdist > dist)
505 info->bestdist = dist;
506 VectorScale(facenormal, (info->radius - -dist), info->nudge);
511 if (info->bestdist > dist)
513 info->bestdist = dist;
514 VectorScale(facenormal, (info->radius - dist), info->nudge);
520 // check which edge or vertex the center is nearest
521 for (i = 0;i < 3;i++)
523 f = DotProduct(info->center, edge[i]);
524 if (f >= DotProduct(vert[0], edge[i])
525 && f <= DotProduct(vert[1], edge[i]))
528 VectorMA(info->center, -f, edge[i], point);
529 dist = sqrt(DotProduct(point, point));
530 if (info->bestdist > dist)
532 info->bestdist = dist;
533 VectorScale(point, (info->radius / dist), info->nudge);
535 // skip both vertex checks
536 // (both are further away than this edge)
541 // not on edge, check first vertex of edge
542 VectorSubtract(info->center, vert[i], point);
543 dist = sqrt(DotProduct(point, point));
544 if (info->bestdist > dist)
546 info->bestdist = dist;
547 VectorScale(point, (info->radius / dist), info->nudge);
556 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
558 int surfacenum, k, *mark;
560 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
562 surface = info->model->data_surfaces + *mark;
563 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
565 if(surface->deprecatedq3num_bboxstride > 0)
568 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
569 for(i = 0; i < cnt; ++i)
571 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
573 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
575 tri = i * surface->deprecatedq3num_bboxstride + k;
576 if(tri >= surface->num_triangles)
578 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
585 for (k = 0;k < surface->num_triangles;k++)
587 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
594 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
598 float f = PlaneDiff(info->center, node->plane);
599 if (f >= -info->bestdist)
600 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
601 if (f <= info->bestdist)
602 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
606 if (((mleaf_t *)node)->numleafsurfaces)
607 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
611 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
614 findnonsolidlocationinfo_t info;
620 VectorCopy(in, info.center);
621 info.radius = radius;
626 VectorClear(info.nudge);
627 info.bestdist = radius;
628 VectorCopy(info.center, info.absmin);
629 VectorCopy(info.center, info.absmax);
630 info.absmin[0] -= info.radius + 1;
631 info.absmin[1] -= info.radius + 1;
632 info.absmin[2] -= info.radius + 1;
633 info.absmax[0] += info.radius + 1;
634 info.absmax[1] += info.radius + 1;
635 info.absmax[2] += info.radius + 1;
636 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
637 VectorAdd(info.center, info.nudge, info.center);
639 while (info.bestdist < radius && ++i < 10);
640 VectorCopy(info.center, out);
643 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
645 switch(nativecontents)
650 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
652 return SUPERCONTENTS_WATER;
654 return SUPERCONTENTS_SLIME;
656 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
658 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
663 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
665 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
666 return CONTENTS_SOLID;
667 if (supercontents & SUPERCONTENTS_SKY)
669 if (supercontents & SUPERCONTENTS_LAVA)
670 return CONTENTS_LAVA;
671 if (supercontents & SUPERCONTENTS_SLIME)
672 return CONTENTS_SLIME;
673 if (supercontents & SUPERCONTENTS_WATER)
674 return CONTENTS_WATER;
675 return CONTENTS_EMPTY;
678 typedef struct RecursiveHullCheckTraceInfo_s
680 // the hull we're tracing through
683 // the trace structure to fill in
686 // start, end, and end - start (in model space)
691 RecursiveHullCheckTraceInfo_t;
693 // 1/32 epsilon to keep floating point happy
694 #define DIST_EPSILON (0.03125)
696 #define HULLCHECKSTATE_EMPTY 0
697 #define HULLCHECKSTATE_SOLID 1
698 #define HULLCHECKSTATE_DONE 2
700 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
702 // status variables, these don't need to be saved on the stack when
703 // recursing... but are because this should be thread-safe
704 // (note: tracing against a bbox is not thread-safe, yet)
709 // variables that need to be stored on the stack when recursing
714 // keep looping until we hit a leaf
717 // find the point distances
718 node = t->hull->clipnodes + num;
719 plane = t->hull->planes + node->planenum;
721 // axial planes can be calculated more quickly without the DotProduct
724 t1 = p1[plane->type] - plane->dist;
725 t2 = p2[plane->type] - plane->dist;
729 t1 = DotProduct (plane->normal, p1) - plane->dist;
730 t2 = DotProduct (plane->normal, p2) - plane->dist;
733 // negative plane distances indicate children[1] (behind plane)
737 // if the line starts and ends on the same side of the plane, recurse
738 // into that child instantly
739 if (p1side == p2side)
741 #if COLLISIONPARANOID >= 3
747 // loop back and process the start child
748 num = node->children[p1side];
752 // find the midpoint where the line crosses the plane, use the
753 // original line for best accuracy
754 #if COLLISIONPARANOID >= 3
759 t1 = t->start[plane->type] - plane->dist;
760 t2 = t->end[plane->type] - plane->dist;
764 t1 = DotProduct (plane->normal, t->start) - plane->dist;
765 t2 = DotProduct (plane->normal, t->end) - plane->dist;
767 midf = t1 / (t1 - t2);
768 midf = bound(p1f, midf, p2f);
769 VectorMA(t->start, midf, t->dist, mid);
771 // we now have a mid point, essentially splitting the line into
772 // the segments in the near child and the far child, we can now
773 // recurse those in order and get their results
775 // recurse both sides, front side first
776 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
777 // if this side is not empty, return what it is (solid or done)
778 if (ret != HULLCHECKSTATE_EMPTY)
781 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
782 // if other side is not solid, return what it is (empty or done)
783 if (ret != HULLCHECKSTATE_SOLID)
786 // front is air and back is solid, this is the impact point...
788 // copy the plane information, flipping it if needed
791 t->trace->plane.dist = -plane->dist;
792 VectorNegate (plane->normal, t->trace->plane.normal);
796 t->trace->plane.dist = plane->dist;
797 VectorCopy (plane->normal, t->trace->plane.normal);
800 // calculate the return fraction which is nudged off the surface a bit
801 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
802 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
803 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
804 t->trace->fraction = bound(0, midf, 1);
806 #if COLLISIONPARANOID >= 3
809 return HULLCHECKSTATE_DONE;
813 // we reached a leaf contents
816 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
817 if (!t->trace->startfound)
819 t->trace->startfound = true;
820 t->trace->startsupercontents |= num;
822 if (num & SUPERCONTENTS_LIQUIDSMASK)
823 t->trace->inwater = true;
825 t->trace->inopen = true;
826 if (num & SUPERCONTENTS_SOLID)
827 t->trace->hittexture = &mod_q1bsp_texture_solid;
828 else if (num & SUPERCONTENTS_SKY)
829 t->trace->hittexture = &mod_q1bsp_texture_sky;
830 else if (num & SUPERCONTENTS_LAVA)
831 t->trace->hittexture = &mod_q1bsp_texture_lava;
832 else if (num & SUPERCONTENTS_SLIME)
833 t->trace->hittexture = &mod_q1bsp_texture_slime;
835 t->trace->hittexture = &mod_q1bsp_texture_water;
836 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
837 t->trace->hitsupercontents = num;
838 if (num & t->trace->hitsupercontentsmask)
840 // if the first leaf is solid, set startsolid
841 if (t->trace->allsolid)
842 t->trace->startsolid = true;
843 #if COLLISIONPARANOID >= 3
846 return HULLCHECKSTATE_SOLID;
850 t->trace->allsolid = false;
851 #if COLLISIONPARANOID >= 3
854 return HULLCHECKSTATE_EMPTY;
858 //#if COLLISIONPARANOID < 2
859 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
862 mclipnode_t *nodes = t->hull->clipnodes;
863 mplane_t *planes = t->hull->planes;
865 VectorCopy(t->start, point);
868 plane = planes + nodes[num].planenum;
869 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
871 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
872 t->trace->startsupercontents |= num;
873 if (num & SUPERCONTENTS_LIQUIDSMASK)
874 t->trace->inwater = true;
876 t->trace->inopen = true;
877 if (num & t->trace->hitsupercontentsmask)
879 t->trace->allsolid = t->trace->startsolid = true;
880 return HULLCHECKSTATE_SOLID;
884 t->trace->allsolid = t->trace->startsolid = false;
885 return HULLCHECKSTATE_EMPTY;
890 static void Mod_Q1BSP_TracePoint(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
892 RecursiveHullCheckTraceInfo_t rhc;
894 memset(&rhc, 0, sizeof(rhc));
895 memset(trace, 0, sizeof(trace_t));
897 rhc.trace->fraction = 1;
898 rhc.trace->allsolid = true;
899 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
900 VectorCopy(start, rhc.start);
901 VectorCopy(start, rhc.end);
902 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
905 static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask);
907 static void Mod_Q1BSP_TraceLine(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
909 RecursiveHullCheckTraceInfo_t rhc;
911 if (VectorCompare(start, end))
913 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
917 // sometimes we want to traceline against polygons so we can report the texture that was hit rather than merely a contents, but using this method breaks one of negke's maps so it must be a cvar check...
918 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
920 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
924 memset(&rhc, 0, sizeof(rhc));
925 memset(trace, 0, sizeof(trace_t));
927 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
928 rhc.trace->fraction = 1;
929 rhc.trace->allsolid = true;
930 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
931 VectorCopy(start, rhc.start);
932 VectorCopy(end, rhc.end);
933 VectorSubtract(rhc.end, rhc.start, rhc.dist);
934 #if COLLISIONPARANOID >= 2
935 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]);
936 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
941 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
942 memset(&testtrace, 0, sizeof(trace_t));
943 rhc.trace = &testtrace;
944 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
945 rhc.trace->fraction = 1;
946 rhc.trace->allsolid = true;
947 VectorCopy(test, rhc.start);
948 VectorCopy(test, rhc.end);
949 VectorClear(rhc.dist);
950 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
951 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
952 if (!trace->startsolid && testtrace.startsolid)
953 Con_Printf(" - ended in solid!\n");
957 if (VectorLength2(rhc.dist))
958 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
960 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
964 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)
966 // this function currently only supports same size start and end
968 RecursiveHullCheckTraceInfo_t rhc;
970 if (VectorCompare(boxmins, boxmaxs))
972 if (VectorCompare(start, end))
973 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
975 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
979 memset(&rhc, 0, sizeof(rhc));
980 memset(trace, 0, sizeof(trace_t));
982 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
983 rhc.trace->fraction = 1;
984 rhc.trace->allsolid = true;
985 VectorSubtract(boxmaxs, boxmins, boxsize);
987 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
988 else if (model->brush.ishlbsp)
990 // LordHavoc: this has to have a minor tolerance (the .1) because of
991 // minor float precision errors from the box being transformed around
992 if (boxsize[0] < 32.1)
994 if (boxsize[2] < 54) // pick the nearest of 36 or 72
995 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
997 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
1000 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1004 // LordHavoc: this has to have a minor tolerance (the .1) because of
1005 // minor float precision errors from the box being transformed around
1006 if (boxsize[0] < 32.1)
1007 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1009 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1011 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1012 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1013 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1014 #if COLLISIONPARANOID >= 2
1015 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]);
1016 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1021 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1022 memset(&testtrace, 0, sizeof(trace_t));
1023 rhc.trace = &testtrace;
1024 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1025 rhc.trace->fraction = 1;
1026 rhc.trace->allsolid = true;
1027 VectorCopy(test, rhc.start);
1028 VectorCopy(test, rhc.end);
1029 VectorClear(rhc.dist);
1030 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1031 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1032 if (!trace->startsolid && testtrace.startsolid)
1033 Con_Printf(" - ended in solid!\n");
1037 if (VectorLength2(rhc.dist))
1038 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1040 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1044 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1046 int num = model->brushq1.hulls[0].firstclipnode;
1048 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1049 mplane_t *planes = model->brushq1.hulls[0].planes;
1052 plane = planes + nodes[num].planenum;
1053 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1055 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1058 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)
1062 colplanef_t cbox_planes[6];
1064 cbox.hasaabbplanes = true;
1065 cbox.supercontents = boxsupercontents;
1068 cbox.numtriangles = 0;
1069 cbox.planes = cbox_planes;
1071 cbox.elements = NULL;
1079 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];
1080 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];
1081 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];
1082 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];
1083 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];
1084 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];
1085 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1086 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1087 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1088 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1089 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1090 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1091 memset(trace, 0, sizeof(trace_t));
1092 trace->hitsupercontentsmask = hitsupercontentsmask;
1093 trace->fraction = 1;
1094 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1096 RecursiveHullCheckTraceInfo_t rhc;
1097 static hull_t box_hull;
1098 static mclipnode_t box_clipnodes[6];
1099 static mplane_t box_planes[6];
1100 // fill in a default trace
1101 memset(&rhc, 0, sizeof(rhc));
1102 memset(trace, 0, sizeof(trace_t));
1103 //To keep everything totally uniform, bounding boxes are turned into small
1104 //BSP trees instead of being compared directly.
1105 // create a temp hull from bounding box sizes
1106 box_planes[0].dist = cmaxs[0] - mins[0];
1107 box_planes[1].dist = cmins[0] - maxs[0];
1108 box_planes[2].dist = cmaxs[1] - mins[1];
1109 box_planes[3].dist = cmins[1] - maxs[1];
1110 box_planes[4].dist = cmaxs[2] - mins[2];
1111 box_planes[5].dist = cmins[2] - maxs[2];
1112 #if COLLISIONPARANOID >= 3
1113 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]);
1116 if (box_hull.clipnodes == NULL)
1120 //Set up the planes and clipnodes so that the six floats of a bounding box
1121 //can just be stored out and get a proper hull_t structure.
1123 box_hull.clipnodes = box_clipnodes;
1124 box_hull.planes = box_planes;
1125 box_hull.firstclipnode = 0;
1126 box_hull.lastclipnode = 5;
1128 for (i = 0;i < 6;i++)
1130 box_clipnodes[i].planenum = i;
1134 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1136 box_clipnodes[i].children[side^1] = i + 1;
1138 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1140 box_planes[i].type = i>>1;
1141 box_planes[i].normal[i>>1] = 1;
1145 // trace a line through the generated clipping hull
1146 //rhc.boxsupercontents = boxsupercontents;
1147 rhc.hull = &box_hull;
1149 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1150 rhc.trace->fraction = 1;
1151 rhc.trace->allsolid = true;
1152 VectorCopy(start, rhc.start);
1153 VectorCopy(end, rhc.end);
1154 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1155 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1156 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1157 if (rhc.trace->startsupercontents)
1158 rhc.trace->startsupercontents = boxsupercontents;
1162 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)
1164 memset(trace, 0, sizeof(trace_t));
1165 trace->fraction = 1;
1166 if (BoxesOverlap(start, start, cmins, cmaxs))
1168 trace->startsupercontents |= boxsupercontents;
1169 if (hitsupercontentsmask & boxsupercontents)
1171 trace->startsolid = true;
1172 trace->allsolid = true;
1177 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1180 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1181 return trace.fraction == 1;
1184 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(dp_model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
1188 float mid, distz = endz - startz;
1192 switch (node->plane->type)
1195 node = node->children[x < node->plane->dist];
1196 continue; // loop back and process the new node
1198 node = node->children[y < node->plane->dist];
1199 continue; // loop back and process the new node
1201 side = startz < node->plane->dist;
1202 if ((endz < node->plane->dist) == side)
1204 node = node->children[side];
1205 continue; // loop back and process the new node
1207 // found an intersection
1208 mid = node->plane->dist;
1211 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1212 front += startz * node->plane->normal[2];
1213 back += endz * node->plane->normal[2];
1214 side = front < node->plane->dist;
1215 if ((back < node->plane->dist) == side)
1217 node = node->children[side];
1218 continue; // loop back and process the new node
1220 // found an intersection
1221 mid = startz + distz * (front - node->plane->dist) / (front - back);
1225 // go down front side
1226 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1227 return true; // hit something
1229 // check for impact on this node
1230 if (node->numsurfaces)
1233 int dsi, dti, lmwidth, lmheight;
1235 msurface_t *surface;
1236 unsigned char *lightmap;
1237 int maps, line3, size3;
1240 float scale, w, w00, w01, w10, w11;
1242 surface = model->data_surfaces + node->firstsurface;
1243 for (i = 0;i < node->numsurfaces;i++, surface++)
1245 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1246 continue; // no lightmaps
1248 // location we want to sample in the lightmap
1249 ds = ((x * surface->lightmapinfo->texinfo->vecs[0][0] + y * surface->lightmapinfo->texinfo->vecs[0][1] + mid * surface->lightmapinfo->texinfo->vecs[0][2] + surface->lightmapinfo->texinfo->vecs[0][3]) - surface->lightmapinfo->texturemins[0]) * 0.0625f;
1250 dt = ((x * surface->lightmapinfo->texinfo->vecs[1][0] + y * surface->lightmapinfo->texinfo->vecs[1][1] + mid * surface->lightmapinfo->texinfo->vecs[1][2] + surface->lightmapinfo->texinfo->vecs[1][3]) - surface->lightmapinfo->texturemins[1]) * 0.0625f;
1253 // thanks to jitspoe for pointing out that this int cast was
1254 // rounding toward zero, so we floor it
1255 dsi = (int)floor(ds);
1256 dti = (int)floor(dt);
1257 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1258 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1261 // we have to tolerate a position of lmwidth-1 for some rare
1262 // cases - in which case the sampling position still gets
1263 // clamped but the color gets interpolated to that edge.
1264 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1266 // in the rare cases where we're sampling slightly off
1267 // the polygon, clamp the sampling position (we can still
1268 // interpolate outside it, where it becomes extrapolation)
1273 if (dsi > lmwidth-2)
1275 if (dti > lmheight-2)
1278 // calculate bilinear interpolation factors
1279 // and also multiply by fixedpoint conversion factors to
1280 // compensate for lightmaps being 0-255 (as 0-2), we use
1281 // r_refdef.scene.rtlightstylevalue here which is already
1282 // 0.000-2.148 range
1283 // (if we used r_refdef.scene.lightstylevalue this
1284 // divisor would be 32768 rather than 128)
1287 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1288 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1289 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1290 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1292 // values for pointer math
1293 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1294 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1296 // look up the pixel
1297 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1299 // bilinear filter each lightmap style, and sum them
1300 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1302 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1303 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1304 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1305 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1306 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1310 return true; // success
1315 // go down back side
1316 node = node->children[side ^ 1];
1318 distz = endz - startz;
1319 // loop back and process the new node
1322 // did not hit anything
1326 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1328 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1329 VectorSet(diffusenormal, 0, 0, 1);
1331 if (!model->brushq1.lightdata)
1333 VectorSet(ambientcolor, 1, 1, 1);
1334 VectorSet(diffusecolor, 0, 0, 0);
1338 Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2] + 0.125, p[2] - 65536);
1341 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1346 const msurface_t *surface;
1351 float edgenormal[3];
1358 surface = model->data_surfaces + node->firstsurface;
1359 for (i = 0;i < node->numsurfaces;i++, surface++)
1361 // skip surfaces whose bounding box does not include the point
1362 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1364 // skip faces with contents we don't care about
1365 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1367 // get the surface normal - since it is flat we know any vertex normal will suffice
1368 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1370 if (DotProduct(t->dist, normal) > 0)
1372 // iterate edges and see if the point is outside one of them
1373 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1375 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1376 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1377 VectorSubtract(v0, v1, edgedir);
1378 CrossProduct(edgedir, normal, edgenormal);
1379 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1382 // if the point is outside one of the edges, it is not within the surface
1383 if (j < surface->num_vertices)
1386 // we hit a surface, this is the impact point...
1387 VectorCopy(normal, t->trace->plane.normal);
1388 t->trace->plane.dist = DotProduct(normal, p);
1390 // calculate the return fraction which is nudged off the surface a bit
1391 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1392 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1393 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1394 t->trace->fraction = bound(0, midf, 1);
1396 t->trace->hittexture = surface->texture->currentframe;
1397 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1398 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1399 return surface->texture->currentframe;
1404 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])
1406 const mplane_t *plane;
1409 double midf, mid[3];
1410 const mleaf_t *leaf;
1414 plane = node->plane;
1415 if (plane->type < 3)
1417 t1 = p1[plane->type] - plane->dist;
1418 t2 = p2[plane->type] - plane->dist;
1422 t1 = DotProduct (plane->normal, p1) - plane->dist;
1423 t2 = DotProduct (plane->normal, p2) - plane->dist;
1429 node = node->children[1];
1438 node = node->children[0];
1444 // the line intersects, find intersection point
1445 // LordHavoc: this uses the original trace for maximum accuracy
1446 if (plane->type < 3)
1448 t1 = t->start[plane->type] - plane->dist;
1449 t2 = t->end[plane->type] - plane->dist;
1453 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1454 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1457 midf = t1 / (t1 - t2);
1458 VectorMA(t->start, midf, t->dist, mid);
1460 // recurse both sides, front side first, return if we hit a surface
1461 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1462 return HULLCHECKSTATE_DONE;
1464 // test each surface on the node
1465 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1466 if (t->trace->hittexture)
1467 return HULLCHECKSTATE_DONE;
1469 // recurse back side
1470 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1472 leaf = (const mleaf_t *)node;
1473 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1474 if (!t->trace->startfound)
1476 t->trace->startfound = true;
1477 t->trace->startsupercontents |= side;
1479 if (side & SUPERCONTENTS_LIQUIDSMASK)
1480 t->trace->inwater = true;
1482 t->trace->inopen = true;
1483 if (side & t->trace->hitsupercontentsmask)
1485 // if the first leaf is solid, set startsolid
1486 if (t->trace->allsolid)
1487 t->trace->startsolid = true;
1488 return HULLCHECKSTATE_SOLID;
1492 t->trace->allsolid = false;
1493 return HULLCHECKSTATE_EMPTY;
1497 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)
1499 RecursiveHullCheckTraceInfo_t rhc;
1501 memset(&rhc, 0, sizeof(rhc));
1502 memset(trace, 0, sizeof(trace_t));
1504 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1505 rhc.trace->fraction = 1;
1506 rhc.trace->allsolid = true;
1507 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1508 VectorCopy(start, rhc.start);
1509 VectorCopy(end, rhc.end);
1510 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1511 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1512 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1515 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1518 unsigned char *outstart = out;
1519 while (out < outend)
1523 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));
1533 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));
1536 for (c = *in++;c > 0;c--)
1540 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));
1551 R_Q1BSP_LoadSplitSky
1553 A sky texture is 256*128, with the right side being a masked overlay
1556 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1561 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1562 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1564 // allocate a texture pool if we need it
1565 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1566 loadmodel->texturepool = R_AllocTexturePool();
1568 if (bytesperpixel == 4)
1570 for (y = 0;y < h;y++)
1572 for (x = 0;x < w;x++)
1574 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1575 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1581 // make an average value for the back to avoid
1582 // a fringe on the top level
1591 for (y = 0;y < h;y++)
1593 for (x = 0;x < w;x++)
1595 p = src[x*width+y+w];
1596 r += palette_rgb[p][0];
1597 g += palette_rgb[p][1];
1598 b += palette_rgb[p][2];
1601 bgra.b[2] = r/(w*h);
1602 bgra.b[1] = g/(w*h);
1603 bgra.b[0] = b/(w*h);
1605 for (y = 0;y < h;y++)
1607 for (x = 0;x < w;x++)
1609 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1611 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1616 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1617 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1618 Mem_Free(solidpixels);
1619 Mem_Free(alphapixels);
1622 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1624 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1625 skinframe_t *skinframemissing;
1626 texture_t *tx, *tx2, *anims[10], *altanims[10];
1627 texture_t backuptex;
1628 unsigned char *data, *mtdata;
1630 char mapname[MAX_QPATH], name[MAX_QPATH];
1631 unsigned char zeroopaque[4], zerotrans[4];
1634 Vector4Set(zeroopaque, 0, 0, 0, 255);
1635 Vector4Set(zerotrans, 0, 0, 0, 128);
1637 loadmodel->data_textures = NULL;
1639 // add two slots for notexture walls and notexture liquids
1642 nummiptex = MSG_ReadLittleLong(sb);
1643 loadmodel->num_textures = nummiptex + 2;
1644 loadmodel->num_texturesperskin = loadmodel->num_textures;
1648 loadmodel->num_textures = 2;
1649 loadmodel->num_texturesperskin = loadmodel->num_textures;
1652 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1654 // fill out all slots with notexture
1655 if (cls.state != ca_dedicated)
1656 skinframemissing = R_SkinFrame_LoadMissing();
1658 skinframemissing = NULL;
1659 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1661 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1664 tx->basealpha = 1.0f;
1665 if (cls.state != ca_dedicated)
1667 tx->materialshaderpass = tx->shaderpasses[0] = Mod_CreateShaderPass(skinframemissing);
1668 tx->currentskinframe = skinframemissing;
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_t *skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
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 has already been assigned to this
1859 tx->materialshaderpass->skinframes[0] = skinframe;
1861 // LordHavoc: some Tenebrae textures get replaced by black
1862 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1863 tx->materialshaderpass->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->materialshaderpass->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->materialshaderpass->skinframes[0]->hasalpha)
1881 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1883 else if (tx->name[0] == '{') // fence textures
1885 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1887 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1889 // replace the texture with black
1890 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1892 else if (!strncmp(tx->name, "sky", 3))
1893 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1894 else if (!strcmp(tx->name, "caulk"))
1895 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1896 else if (tx->materialshaderpass->skinframes[0]->hasalpha)
1897 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1899 // start out with no animation
1900 tx->currentframe = tx;
1901 tx->currentskinframe = tx->materialshaderpass->skinframes[0];
1902 tx->currentmaterialflags = tx->basematerialflags;
1905 // sequence the animations
1906 for (i = 0;i < nummiptex;i++)
1908 tx = loadmodel->data_textures + i;
1909 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1912 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1914 Con_Printf("Bad animating texture %s\n", tx->name);
1917 if (tx->anim_total[0] || tx->anim_total[1])
1918 continue; // already sequenced
1920 // find the number of frames in the animation
1921 memset(anims, 0, sizeof(anims));
1922 memset(altanims, 0, sizeof(altanims));
1924 for (j = i;j < nummiptex;j++)
1926 tx2 = loadmodel->data_textures + j;
1927 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1931 if (num >= '0' && num <= '9')
1932 anims[num - '0'] = tx2;
1933 else if (num >= 'a' && num <= 'j')
1934 altanims[num - 'a'] = tx2;
1935 // No need to warn otherwise - we already did above.
1939 for (j = 0;j < 10;j++)
1946 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1949 for (j = 0;j < max;j++)
1953 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1957 for (j = 0;j < altmax;j++)
1961 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1968 // If we have exactly one frame, something's wrong.
1969 if (max + altmax <= 1)
1971 Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
1976 // if there is no alternate animation, duplicate the primary
1977 // animation into the alternate
1979 for (k = 0;k < 10;k++)
1980 altanims[k] = anims[k];
1986 Con_Printf("Missing frame 0 of %s\n", tx->name);
1988 // however, we can handle this by duplicating the alternate animation into the primary
1990 for (k = 0;k < 10;k++)
1991 anims[k] = altanims[k];
1995 // link together the primary animation
1996 for (j = 0;j < max;j++)
1999 tx2->animated = 1; // q1bsp
2000 tx2->anim_total[0] = max;
2001 tx2->anim_total[1] = altmax;
2002 for (k = 0;k < 10;k++)
2004 tx2->anim_frames[0][k] = anims[k];
2005 tx2->anim_frames[1][k] = altanims[k];
2009 // if there really is an alternate anim...
2010 if (anims[0] != altanims[0])
2012 // link together the alternate animation
2013 for (j = 0;j < altmax;j++)
2016 tx2->animated = 1; // q1bsp
2017 // the primary/alternate are reversed here
2018 tx2->anim_total[0] = altmax;
2019 tx2->anim_total[1] = max;
2020 for (k = 0;k < 10;k++)
2022 tx2->anim_frames[0][k] = altanims[k];
2023 tx2->anim_frames[1][k] = anims[k];
2030 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2033 unsigned char *in, *out, *data, d;
2034 char litfilename[MAX_QPATH];
2035 char dlitfilename[MAX_QPATH];
2036 fs_offset_t filesize;
2037 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2039 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2040 for (i = 0;i < sb->cursize;i++)
2041 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2043 else // LordHavoc: bsp version 29 (normal white lighting)
2045 // LordHavoc: hope is not lost yet, check for a .lit file to load
2046 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2047 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2048 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2049 strlcat (litfilename, ".lit", sizeof (litfilename));
2050 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2051 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2054 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2056 i = LittleLong(((int *)data)[1]);
2059 if (developer_loading.integer)
2060 Con_Printf("loaded %s\n", litfilename);
2061 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2062 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2064 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2067 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2069 i = LittleLong(((int *)data)[1]);
2072 if (developer_loading.integer)
2073 Con_Printf("loaded %s\n", dlitfilename);
2074 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2075 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2076 loadmodel->brushq3.deluxemapping_modelspace = false;
2077 loadmodel->brushq3.deluxemapping = true;
2086 Con_Printf("Unknown .lit file version (%d)\n", i);
2088 else if (filesize == 8)
2089 Con_Print("Empty .lit file, ignoring\n");
2091 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2098 // LordHavoc: oh well, expand the white lighting data
2101 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2103 out = loadmodel->brushq1.lightdata;
2104 for (i = 0;i < sb->cursize;i++)
2114 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2116 loadmodel->brushq1.num_compressedpvs = 0;
2117 loadmodel->brushq1.data_compressedpvs = NULL;
2120 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2121 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2122 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2125 // used only for HalfLife maps
2126 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2128 char key[128], value[4096];
2132 if (!COM_ParseToken_Simple(&data, false, false, true))
2134 if (com_token[0] != '{')
2138 if (!COM_ParseToken_Simple(&data, false, false, true))
2140 if (com_token[0] == '}')
2141 break; // end of worldspawn
2142 if (com_token[0] == '_')
2143 strlcpy(key, com_token + 1, sizeof(key));
2145 strlcpy(key, com_token, sizeof(key));
2146 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2147 key[strlen(key)-1] = 0;
2148 if (!COM_ParseToken_Simple(&data, false, false, true))
2150 dpsnprintf(value, sizeof(value), "%s", com_token);
2151 if (!strcmp("wad", key)) // for HalfLife maps
2153 if (loadmodel->brush.ishlbsp)
2156 for (i = 0;i < (int)sizeof(value);i++)
2157 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2159 if (i < (int)sizeof(value) && value[i])
2161 for (;i < (int)sizeof(value);i++)
2163 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2164 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2166 else if (value[i] == ';' || value[i] == 0)
2170 W_LoadTextureWadFile(&value[j], false);
2182 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2184 loadmodel->brush.entities = NULL;
2187 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2188 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2189 loadmodel->brush.entities[sb->cursize] = 0;
2190 if (loadmodel->brush.ishlbsp)
2191 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2195 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2199 int structsize = 12;
2201 if (sb->cursize % structsize)
2202 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2203 count = sb->cursize / structsize;
2204 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2206 loadmodel->brushq1.vertexes = out;
2207 loadmodel->brushq1.numvertexes = count;
2209 for ( i=0 ; i<count ; i++, out++)
2211 out->position[0] = MSG_ReadLittleFloat(sb);
2212 out->position[1] = MSG_ReadLittleFloat(sb);
2213 out->position[2] = MSG_ReadLittleFloat(sb);
2217 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2221 int structsize = (48+4*hullinfo->filehulls);
2223 if (sb->cursize % structsize)
2224 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2226 count = sb->cursize / structsize;
2227 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2229 loadmodel->brushq1.submodels = out;
2230 loadmodel->brush.numsubmodels = count;
2232 for (i = 0; i < count; i++, out++)
2234 // spread out the mins / maxs by a pixel
2235 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2236 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2237 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2238 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2239 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2240 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2241 out->origin[0] = MSG_ReadLittleFloat(sb);
2242 out->origin[1] = MSG_ReadLittleFloat(sb);
2243 out->origin[2] = MSG_ReadLittleFloat(sb);
2244 for (j = 0; j < hullinfo->filehulls; j++)
2245 out->headnode[j] = MSG_ReadLittleLong(sb);
2246 out->visleafs = MSG_ReadLittleLong(sb);
2247 out->firstface = MSG_ReadLittleLong(sb);
2248 out->numfaces = MSG_ReadLittleLong(sb);
2252 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2256 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2258 if (sb->cursize % structsize)
2259 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2260 count = sb->cursize / structsize;
2261 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2263 loadmodel->brushq1.edges = out;
2264 loadmodel->brushq1.numedges = count;
2266 for ( i=0 ; i<count ; i++, out++)
2268 if (loadmodel->brush.isbsp2)
2270 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2271 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2275 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2276 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2278 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2280 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);
2281 if(!loadmodel->brushq1.numvertexes)
2282 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2290 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2293 int i, j, k, count, miptex;
2294 int structsize = 40;
2296 if (sb->cursize % structsize)
2297 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2298 count = sb->cursize / structsize;
2299 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2301 loadmodel->brushq1.texinfo = out;
2302 loadmodel->brushq1.numtexinfo = count;
2304 for (i = 0;i < count;i++, out++)
2306 for (k = 0;k < 2;k++)
2307 for (j = 0;j < 4;j++)
2308 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2310 miptex = MSG_ReadLittleLong(sb);
2311 out->q1flags = MSG_ReadLittleLong(sb);
2313 if (out->q1flags & TEX_SPECIAL)
2315 // if texture chosen is NULL or the shader needs a lightmap,
2316 // force to notexture water shader
2317 out->textureindex = loadmodel->num_textures - 1;
2321 // if texture chosen is NULL, force to notexture
2322 out->textureindex = loadmodel->num_textures - 2;
2324 // see if the specified miptex is valid and try to use it instead
2325 if (loadmodel->data_textures)
2327 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2328 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2330 out->textureindex = miptex;
2336 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2341 mins[0] = mins[1] = mins[2] = 9999;
2342 maxs[0] = maxs[1] = maxs[2] = -9999;
2344 for (i = 0;i < numverts;i++)
2346 for (j = 0;j < 3;j++, v++)
2356 #define MAX_SUBDIVPOLYTRIANGLES 4096
2357 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2359 static int subdivpolyverts, subdivpolytriangles;
2360 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2361 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2363 static int subdivpolylookupvert(vec3_t v)
2366 for (i = 0;i < subdivpolyverts;i++)
2367 if (subdivpolyvert[i][0] == v[0]
2368 && subdivpolyvert[i][1] == v[1]
2369 && subdivpolyvert[i][2] == v[2])
2371 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2372 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2373 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2374 return subdivpolyverts++;
2377 static void SubdividePolygon(int numverts, float *verts)
2379 int i, i1, i2, i3, f, b, c, p;
2380 vec3_t mins, maxs, front[256], back[256];
2381 float m, *pv, *cv, dist[256], frac;
2384 Host_Error("SubdividePolygon: ran out of verts in buffer");
2386 BoundPoly(numverts, verts, mins, maxs);
2388 for (i = 0;i < 3;i++)
2390 m = (mins[i] + maxs[i]) * 0.5;
2391 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2392 if (maxs[i] - m < 8)
2394 if (m - mins[i] < 8)
2398 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2399 dist[c] = cv[i] - m;
2402 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2406 VectorCopy(pv, front[f]);
2411 VectorCopy(pv, back[b]);
2414 if (dist[p] == 0 || dist[c] == 0)
2416 if ((dist[p] > 0) != (dist[c] > 0) )
2419 frac = dist[p] / (dist[p] - dist[c]);
2420 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2421 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2422 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2428 SubdividePolygon(f, front[0]);
2429 SubdividePolygon(b, back[0]);
2433 i1 = subdivpolylookupvert(verts);
2434 i2 = subdivpolylookupvert(verts + 3);
2435 for (i = 2;i < numverts;i++)
2437 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2439 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2443 i3 = subdivpolylookupvert(verts + i * 3);
2444 subdivpolyindex[subdivpolytriangles][0] = i1;
2445 subdivpolyindex[subdivpolytriangles][1] = i2;
2446 subdivpolyindex[subdivpolytriangles][2] = i3;
2448 subdivpolytriangles++;
2452 //Breaks a polygon up along axial 64 unit
2453 //boundaries so that turbulent and sky warps
2454 //can be done reasonably.
2455 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2461 subdivpolytriangles = 0;
2462 subdivpolyverts = 0;
2463 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2464 if (subdivpolytriangles < 1)
2465 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2467 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2468 mesh->num_vertices = subdivpolyverts;
2469 mesh->num_triangles = subdivpolytriangles;
2470 mesh->vertex = (surfvertex_t *)(mesh + 1);
2471 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2472 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2474 for (i = 0;i < mesh->num_triangles;i++)
2475 for (j = 0;j < 3;j++)
2476 mesh->index[i*3+j] = subdivpolyindex[i][j];
2478 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2480 VectorCopy(subdivpolyvert[i], v->v);
2481 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2482 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2487 extern cvar_t gl_max_lightmapsize;
2488 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2490 msurface_t *surface;
2491 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2492 float texmins[2], texmaxs[2], val;
2493 rtexture_t *lightmaptexture, *deluxemaptexture;
2495 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2497 if (sb->cursize % structsize)
2498 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2499 count = sb->cursize / structsize;
2500 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2501 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2503 loadmodel->num_surfaces = count;
2505 loadmodel->brushq1.firstrender = true;
2506 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2510 for (surfacenum = 0;surfacenum < count;surfacenum++)
2512 if (loadmodel->brush.isbsp2)
2513 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2515 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2516 totalverts += numedges;
2517 totaltris += numedges - 2;
2520 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2522 lightmaptexture = NULL;
2523 deluxemaptexture = r_texture_blanknormalmap;
2525 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2526 totallightmapsamples = 0;
2530 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2532 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2533 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2534 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2535 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2536 firstedge = MSG_ReadLittleLong(sb);
2537 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2538 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2539 for (i = 0;i < MAXLIGHTMAPS;i++)
2540 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2541 lightmapoffset = MSG_ReadLittleLong(sb);
2543 // FIXME: validate edges, texinfo, etc?
2544 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)
2545 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2546 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2547 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2548 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2549 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2551 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2552 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2554 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2555 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2556 lightmapoffset = -1;
2558 //surface->flags = surface->texture->flags;
2559 //if (LittleShort(in->side))
2560 // surface->flags |= SURF_PLANEBACK;
2561 //surface->plane = loadmodel->brush.data_planes + planenum;
2563 surface->num_firstvertex = totalverts;
2564 surface->num_vertices = numedges;
2565 surface->num_firsttriangle = totaltris;
2566 surface->num_triangles = numedges - 2;
2567 totalverts += numedges;
2568 totaltris += numedges - 2;
2570 // convert edges back to a normal polygon
2571 for (i = 0;i < surface->num_vertices;i++)
2573 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2575 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2577 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2579 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2580 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2581 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2582 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2583 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2584 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2585 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2586 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2589 for (i = 0;i < surface->num_triangles;i++)
2591 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2592 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2593 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2596 // compile additional data about the surface geometry
2597 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);
2598 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);
2599 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2601 // generate surface extents information
2602 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2603 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2604 for (i = 1;i < surface->num_vertices;i++)
2606 for (j = 0;j < 2;j++)
2608 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2609 texmins[j] = min(texmins[j], val);
2610 texmaxs[j] = max(texmaxs[j], val);
2613 for (i = 0;i < 2;i++)
2615 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2616 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2619 smax = surface->lightmapinfo->extents[0] >> 4;
2620 tmax = surface->lightmapinfo->extents[1] >> 4;
2621 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2622 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2625 surface->lightmaptexture = NULL;
2626 surface->deluxemaptexture = r_texture_blanknormalmap;
2627 if (lightmapoffset == -1)
2629 surface->lightmapinfo->samples = NULL;
2631 // give non-lightmapped water a 1x white lightmap
2632 if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2634 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2635 surface->lightmapinfo->styles[0] = 0;
2636 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2640 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LordHavoc: HalfLife map (bsp version 30)
2641 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2642 else // LordHavoc: white lighting (bsp version 29)
2644 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2645 if (loadmodel->brushq1.nmaplightdata)
2646 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2649 // check if we should apply a lightmap to this
2650 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2652 if (ssize > 256 || tsize > 256)
2653 Host_Error("Bad surface extents");
2655 if (lightmapsize < ssize)
2656 lightmapsize = ssize;
2657 if (lightmapsize < tsize)
2658 lightmapsize = tsize;
2660 totallightmapsamples += ssize*tsize;
2662 // force lightmap upload on first time seeing the surface
2664 // additionally this is used by the later code to see if a
2665 // lightmap is needed on this surface (rather than duplicating the
2667 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2668 loadmodel->lit = true;
2672 // small maps (such as ammo boxes especially) don't need big lightmap
2673 // textures, so this code tries to guess a good size based on
2674 // totallightmapsamples (size of the lightmaps lump basically), as well as
2675 // trying to max out the size if there is a lot of lightmap data to store
2676 // additionally, never choose a lightmapsize that is smaller than the
2677 // largest surface encountered (as it would fail)
2679 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2682 // now that we've decided the lightmap texture size, we can do the rest
2683 if (cls.state != ca_dedicated)
2685 int stainmapsize = 0;
2686 mod_alloclightmap_state_t allocState;
2688 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2689 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2691 int iu, iv, lightmapx = 0, lightmapy = 0;
2692 float u, v, ubase, vbase, uscale, vscale;
2694 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2697 smax = surface->lightmapinfo->extents[0] >> 4;
2698 tmax = surface->lightmapinfo->extents[1] >> 4;
2699 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2700 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2701 stainmapsize += ssize * tsize * 3;
2703 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2705 // allocate a texture pool if we need it
2706 if (loadmodel->texturepool == NULL)
2707 loadmodel->texturepool = R_AllocTexturePool();
2708 // could not find room, make a new lightmap
2709 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2710 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2711 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2712 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);
2713 if (loadmodel->brushq1.nmaplightdata)
2714 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);
2716 Mod_AllocLightmap_Reset(&allocState);
2717 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2719 surface->lightmaptexture = lightmaptexture;
2720 surface->deluxemaptexture = deluxemaptexture;
2721 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2722 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2724 uscale = 1.0f / (float)lightmapsize;
2725 vscale = 1.0f / (float)lightmapsize;
2726 ubase = lightmapx * uscale;
2727 vbase = lightmapy * vscale;
2729 for (i = 0;i < surface->num_vertices;i++)
2731 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);
2732 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);
2733 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2734 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2735 // LordHavoc: calc lightmap data offset for vertex lighting to use
2738 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2742 if (cl_stainmaps.integer)
2744 // allocate stainmaps for permanent marks on walls and clear white
2745 unsigned char *stainsamples = NULL;
2746 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2747 memset(stainsamples, 255, stainmapsize);
2749 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2751 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2753 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2754 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2755 surface->lightmapinfo->stainsamples = stainsamples;
2756 stainsamples += ssize * tsize * 3;
2761 // generate ushort elements array if possible
2762 if (loadmodel->surfmesh.data_element3s)
2763 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2764 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2767 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2770 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2771 node->parent = parent;
2774 // this is a node, recurse to children
2775 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2776 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2777 // combine supercontents of children
2778 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2783 mleaf_t *leaf = (mleaf_t *)node;
2784 // if this is a leaf, calculate supercontents mask from all collidable
2785 // primitives in the leaf (brushes and collision surfaces)
2786 // also flag if the leaf contains any collision surfaces
2787 leaf->combinedsupercontents = 0;
2788 // combine the supercontents values of all brushes in this leaf
2789 for (j = 0;j < leaf->numleafbrushes;j++)
2790 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2791 // check if this leaf contains any collision surfaces (q3 patches)
2792 for (j = 0;j < leaf->numleafsurfaces;j++)
2794 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2795 if (surface->num_collisiontriangles)
2797 leaf->containscollisionsurfaces = true;
2798 leaf->combinedsupercontents |= surface->texture->supercontents;
2804 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2806 int i, j, count, p, child[2];
2808 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2810 if (sb->cursize % structsize)
2811 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2812 count = sb->cursize / structsize;
2814 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2815 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2817 loadmodel->brush.data_nodes = out;
2818 loadmodel->brush.num_nodes = count;
2820 for ( i=0 ; i<count ; i++, out++)
2822 p = MSG_ReadLittleLong(sb);
2823 out->plane = loadmodel->brush.data_planes + p;
2825 if (loadmodel->brush.isbsp2rmqe)
2827 child[0] = MSG_ReadLittleLong(sb);
2828 child[1] = MSG_ReadLittleLong(sb);
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);
2835 out->firstsurface = MSG_ReadLittleLong(sb);
2836 out->numsurfaces = MSG_ReadLittleLong(sb);
2838 else if (loadmodel->brush.isbsp2)
2840 child[0] = MSG_ReadLittleLong(sb);
2841 child[1] = MSG_ReadLittleLong(sb);
2842 out->mins[0] = MSG_ReadLittleFloat(sb);
2843 out->mins[1] = MSG_ReadLittleFloat(sb);
2844 out->mins[2] = MSG_ReadLittleFloat(sb);
2845 out->maxs[0] = MSG_ReadLittleFloat(sb);
2846 out->maxs[1] = MSG_ReadLittleFloat(sb);
2847 out->maxs[2] = MSG_ReadLittleFloat(sb);
2848 out->firstsurface = MSG_ReadLittleLong(sb);
2849 out->numsurfaces = MSG_ReadLittleLong(sb);
2853 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2854 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2855 if (child[0] >= count)
2857 if (child[1] >= count)
2860 out->mins[0] = MSG_ReadLittleShort(sb);
2861 out->mins[1] = MSG_ReadLittleShort(sb);
2862 out->mins[2] = MSG_ReadLittleShort(sb);
2863 out->maxs[0] = MSG_ReadLittleShort(sb);
2864 out->maxs[1] = MSG_ReadLittleShort(sb);
2865 out->maxs[2] = MSG_ReadLittleShort(sb);
2867 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2868 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2871 for (j=0 ; j<2 ; j++)
2873 // LordHavoc: this code supports broken bsp files produced by
2874 // arguire qbsp which can produce more than 32768 nodes, any value
2875 // below count is assumed to be a node number, any other value is
2876 // assumed to be a leaf number
2880 if (p < loadmodel->brush.num_nodes)
2881 out->children[j] = loadmodel->brush.data_nodes + p;
2884 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2885 // map it to the solid leaf
2886 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2891 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2893 if (p < loadmodel->brush.num_leafs)
2894 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2897 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2898 // map it to the solid leaf
2899 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2905 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2908 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2911 int i, j, count, p, firstmarksurface, nummarksurfaces;
2912 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2914 if (sb->cursize % structsize)
2915 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2916 count = sb->cursize / structsize;
2917 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2919 loadmodel->brush.data_leafs = out;
2920 loadmodel->brush.num_leafs = count;
2921 // get visleafs from the submodel data
2922 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2923 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2924 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2925 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2927 // FIXME: this function could really benefit from some error checking
2928 for ( i=0 ; i<count ; i++, out++)
2930 out->contents = MSG_ReadLittleLong(sb);
2932 out->clusterindex = i - 1;
2933 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2934 out->clusterindex = -1;
2936 p = MSG_ReadLittleLong(sb);
2937 // ignore visofs errors on leaf 0 (solid)
2938 if (p >= 0 && out->clusterindex >= 0)
2940 if (p >= loadmodel->brushq1.num_compressedpvs)
2941 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2943 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);
2946 if (loadmodel->brush.isbsp2rmqe)
2948 out->mins[0] = MSG_ReadLittleShort(sb);
2949 out->mins[1] = MSG_ReadLittleShort(sb);
2950 out->mins[2] = MSG_ReadLittleShort(sb);
2951 out->maxs[0] = MSG_ReadLittleShort(sb);
2952 out->maxs[1] = MSG_ReadLittleShort(sb);
2953 out->maxs[2] = MSG_ReadLittleShort(sb);
2955 firstmarksurface = MSG_ReadLittleLong(sb);
2956 nummarksurfaces = MSG_ReadLittleLong(sb);
2958 else if (loadmodel->brush.isbsp2)
2960 out->mins[0] = MSG_ReadLittleFloat(sb);
2961 out->mins[1] = MSG_ReadLittleFloat(sb);
2962 out->mins[2] = MSG_ReadLittleFloat(sb);
2963 out->maxs[0] = MSG_ReadLittleFloat(sb);
2964 out->maxs[1] = MSG_ReadLittleFloat(sb);
2965 out->maxs[2] = MSG_ReadLittleFloat(sb);
2967 firstmarksurface = MSG_ReadLittleLong(sb);
2968 nummarksurfaces = MSG_ReadLittleLong(sb);
2972 out->mins[0] = MSG_ReadLittleShort(sb);
2973 out->mins[1] = MSG_ReadLittleShort(sb);
2974 out->mins[2] = MSG_ReadLittleShort(sb);
2975 out->maxs[0] = MSG_ReadLittleShort(sb);
2976 out->maxs[1] = MSG_ReadLittleShort(sb);
2977 out->maxs[2] = MSG_ReadLittleShort(sb);
2979 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2980 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2983 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2985 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2986 out->numleafsurfaces = nummarksurfaces;
2990 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2991 out->firstleafsurface = NULL;
2992 out->numleafsurfaces = 0;
2995 for (j = 0;j < 4;j++)
2996 out->ambient_sound_level[j] = MSG_ReadByte(sb);
3000 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
3004 const unsigned char *pvs;
3005 // if there's no vis data, assume supported (because everything is visible all the time)
3006 if (!loadmodel->brush.data_pvsclusters)
3008 // check all liquid leafs to see if they can see into empty leafs, if any
3009 // can we can assume this map supports r_wateralpha
3010 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3012 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3014 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3015 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3016 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3023 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3028 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3030 if (sb->cursize % structsize)
3031 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3032 count = sb->cursize / structsize;
3033 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3035 loadmodel->brushq1.clipnodes = out;
3036 loadmodel->brushq1.numclipnodes = count;
3038 for (i = 1; i < MAX_MAP_HULLS; i++)
3040 hull = &loadmodel->brushq1.hulls[i];
3041 hull->clipnodes = out;
3042 hull->firstclipnode = 0;
3043 hull->lastclipnode = count-1;
3044 hull->planes = loadmodel->brush.data_planes;
3045 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3046 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3047 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3048 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3049 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3050 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3051 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3054 for (i=0 ; i<count ; i++, out++)
3056 out->planenum = MSG_ReadLittleLong(sb);
3057 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3058 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3059 if (loadmodel->brush.isbsp2)
3061 out->children[0] = MSG_ReadLittleLong(sb);
3062 out->children[1] = MSG_ReadLittleLong(sb);
3063 if (out->children[0] >= count)
3064 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3065 if (out->children[1] >= count)
3066 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3070 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3071 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3072 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3073 if (out->children[0] >= count)
3074 out->children[0] -= 65536;
3075 if (out->children[1] >= count)
3076 out->children[1] -= 65536;
3081 //Duplicate the drawing hull structure as a clipping hull
3082 static void Mod_Q1BSP_MakeHull0(void)
3089 hull = &loadmodel->brushq1.hulls[0];
3091 in = loadmodel->brush.data_nodes;
3092 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3094 hull->clipnodes = out;
3095 hull->firstclipnode = 0;
3096 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3097 hull->planes = loadmodel->brush.data_planes;
3099 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3101 out->planenum = in->plane - loadmodel->brush.data_planes;
3102 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3103 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3107 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3110 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3112 if (sb->cursize % structsize)
3113 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3114 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3115 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3117 if (loadmodel->brush.isbsp2)
3119 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3121 j = MSG_ReadLittleLong(sb);
3122 if (j < 0 || j >= loadmodel->num_surfaces)
3123 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3124 loadmodel->brush.data_leafsurfaces[i] = j;
3129 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3131 j = (unsigned short) MSG_ReadLittleShort(sb);
3132 if (j >= loadmodel->num_surfaces)
3133 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3134 loadmodel->brush.data_leafsurfaces[i] = j;
3139 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3144 if (sb->cursize % structsize)
3145 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3146 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3147 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3149 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3150 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3154 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3158 int structsize = 20;
3160 if (sb->cursize % structsize)
3161 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3162 loadmodel->brush.num_planes = sb->cursize / structsize;
3163 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3165 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3167 out->normal[0] = MSG_ReadLittleFloat(sb);
3168 out->normal[1] = MSG_ReadLittleFloat(sb);
3169 out->normal[2] = MSG_ReadLittleFloat(sb);
3170 out->dist = MSG_ReadLittleFloat(sb);
3171 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3176 static void Mod_Q1BSP_LoadMapBrushes(void)
3180 int submodel, numbrushes;
3181 qboolean firstbrush;
3182 char *text, *maptext;
3183 char mapfilename[MAX_QPATH];
3184 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3185 strlcat (mapfilename, ".map", sizeof (mapfilename));
3186 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3190 if (!COM_ParseToken_Simple(&data, false, false, true))
3195 if (!COM_ParseToken_Simple(&data, false, false, true))
3197 if (com_token[0] != '{')
3203 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3206 if (!COM_ParseToken_Simple(&data, false, false, true))
3208 if (com_token[0] == '}')
3209 break; // end of entity
3210 if (com_token[0] == '{')
3217 if (submodel > loadmodel->brush.numsubmodels)
3219 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3223 model = loadmodel->brush.submodels[submodel];
3230 if (!COM_ParseToken_Simple(&data, false, false, true))
3232 if (com_token[0] == '}')
3233 break; // end of brush
3234 // each brush face should be this format:
3235 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3236 // FIXME: support hl .map format
3237 for (pointnum = 0;pointnum < 3;pointnum++)
3239 COM_ParseToken_Simple(&data, false, false, true);
3240 for (componentnum = 0;componentnum < 3;componentnum++)
3242 COM_ParseToken_Simple(&data, false, false, true);
3243 point[pointnum][componentnum] = atof(com_token);
3245 COM_ParseToken_Simple(&data, false, false, true);
3247 COM_ParseToken_Simple(&data, false, false, true);
3248 strlcpy(facetexture, com_token, sizeof(facetexture));
3249 COM_ParseToken_Simple(&data, false, false, true);
3250 //scroll_s = atof(com_token);
3251 COM_ParseToken_Simple(&data, false, false, true);
3252 //scroll_t = atof(com_token);
3253 COM_ParseToken_Simple(&data, false, false, true);
3254 //rotate = atof(com_token);
3255 COM_ParseToken_Simple(&data, false, false, true);
3256 //scale_s = atof(com_token);
3257 COM_ParseToken_Simple(&data, false, false, true);
3258 //scale_t = atof(com_token);
3259 TriangleNormal(point[0], point[1], point[2], planenormal);
3260 VectorNormalizeDouble(planenormal);
3261 planedist = DotProduct(point[0], planenormal);
3262 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3272 #define MAX_PORTALPOINTS 64
3274 typedef struct portal_s
3277 mnode_t *nodes[2]; // [0] = front side of plane
3278 struct portal_s *next[2];
3280 double points[3*MAX_PORTALPOINTS];
3281 struct portal_s *chain; // all portals are linked into a list
3285 static memexpandablearray_t portalarray;
3287 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3289 // process only nodes (leafs already had their box calculated)
3293 // calculate children first
3294 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3295 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3297 // make combined bounding box from children
3298 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3299 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3300 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3301 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3302 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3303 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3306 static void Mod_Q1BSP_FinalizePortals(void)
3308 int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3312 mleaf_t *leaf, *endleaf;
3314 // tally up portal and point counts and recalculate bounding boxes for all
3315 // leafs (because qbsp is very sloppy)
3316 leaf = loadmodel->brush.data_leafs;
3317 endleaf = leaf + loadmodel->brush.num_leafs;
3318 if (mod_recalculatenodeboxes.integer)
3320 for (;leaf < endleaf;leaf++)
3322 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3323 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3328 for (portalindex = 0;portalindex < portalrange;portalindex++)
3330 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3333 // note: this check must match the one below or it will usually corrupt memory
3334 // 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
3335 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3338 numpoints += p->numpoints * 2;
3341 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3342 loadmodel->brush.num_portals = numportals;
3343 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3344 loadmodel->brush.num_portalpoints = numpoints;
3345 // clear all leaf portal chains
3346 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3347 loadmodel->brush.data_leafs[i].portals = NULL;
3348 // process all portals in the global portal chain, while freeing them
3349 portal = loadmodel->brush.data_portals;
3350 point = loadmodel->brush.data_portalpoints;
3351 for (portalindex = 0;portalindex < portalrange;portalindex++)
3353 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3356 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3358 // note: this check must match the one above or it will usually corrupt memory
3359 // 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
3360 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3362 // first make the back to front portal(forward portal)
3363 portal->points = point;
3364 portal->numpoints = p->numpoints;
3365 portal->plane.dist = p->plane.dist;
3366 VectorCopy(p->plane.normal, portal->plane.normal);
3367 portal->here = (mleaf_t *)p->nodes[1];
3368 portal->past = (mleaf_t *)p->nodes[0];
3370 for (j = 0;j < portal->numpoints;j++)
3372 VectorCopy(p->points + j*3, point->position);
3375 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3376 PlaneClassify(&portal->plane);
3378 // link into leaf's portal chain
3379 portal->next = portal->here->portals;
3380 portal->here->portals = portal;
3382 // advance to next portal
3385 // then make the front to back portal(backward portal)
3386 portal->points = point;
3387 portal->numpoints = p->numpoints;
3388 portal->plane.dist = -p->plane.dist;
3389 VectorNegate(p->plane.normal, portal->plane.normal);
3390 portal->here = (mleaf_t *)p->nodes[0];
3391 portal->past = (mleaf_t *)p->nodes[1];
3393 for (j = portal->numpoints - 1;j >= 0;j--)
3395 VectorCopy(p->points + j*3, point->position);
3398 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3399 PlaneClassify(&portal->plane);
3401 // link into leaf's portal chain
3402 portal->next = portal->here->portals;
3403 portal->here->portals = portal;
3405 // advance to next portal
3408 // add the portal's polygon points to the leaf bounding boxes
3409 if (mod_recalculatenodeboxes.integer)
3411 for (i = 0;i < 2;i++)
3413 leaf = (mleaf_t *)p->nodes[i];
3414 for (j = 0;j < p->numpoints;j++)
3416 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3417 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3418 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3419 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3420 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3421 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3427 // now recalculate the node bounding boxes from the leafs
3428 if (mod_recalculatenodeboxes.integer)
3429 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3437 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3440 Host_Error("AddPortalToNodes: NULL front node");
3442 Host_Error("AddPortalToNodes: NULL back node");
3443 if (p->nodes[0] || p->nodes[1])
3444 Host_Error("AddPortalToNodes: already included");
3445 // 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
3447 p->nodes[0] = front;
3448 p->next[0] = (portal_t *)front->portals;
3449 front->portals = (mportal_t *)p;
3452 p->next[1] = (portal_t *)back->portals;
3453 back->portals = (mportal_t *)p;
3458 RemovePortalFromNode
3461 static void RemovePortalFromNodes(portal_t *portal)
3465 void **portalpointer;
3467 for (i = 0;i < 2;i++)
3469 node = portal->nodes[i];
3471 portalpointer = (void **) &node->portals;
3474 t = (portal_t *)*portalpointer;
3476 Host_Error("RemovePortalFromNodes: portal not in leaf");
3480 if (portal->nodes[0] == node)
3482 *portalpointer = portal->next[0];
3483 portal->nodes[0] = NULL;
3485 else if (portal->nodes[1] == node)
3487 *portalpointer = portal->next[1];
3488 portal->nodes[1] = NULL;
3491 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3495 if (t->nodes[0] == node)
3496 portalpointer = (void **) &t->next[0];
3497 else if (t->nodes[1] == node)
3498 portalpointer = (void **) &t->next[1];
3500 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3505 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3506 static double *portalpointsbuffer;
3507 static int portalpointsbufferoffset;
3508 static int portalpointsbuffersize;
3509 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3512 mnode_t *front, *back, *other_node;
3513 mplane_t clipplane, *plane;
3514 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3515 int numfrontpoints, numbackpoints;
3516 double *frontpoints, *backpoints;
3518 // if a leaf, we're done
3522 // get some space for our clipping operations to use
3523 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3525 portalpointsbuffersize = portalpointsbufferoffset * 2;
3526 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3528 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3529 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3530 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3531 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3533 plane = node->plane;
3535 front = node->children[0];
3536 back = node->children[1];
3538 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3540 // create the new portal by generating a polygon for the node plane,
3541 // and clipping it by all of the other portals(which came from nodes above this one)
3542 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3543 nodeportal->plane = *plane;
3545 // 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)
3546 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);
3547 nodeportal->numpoints = 4;
3548 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3549 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3551 clipplane = portal->plane;
3552 if (portal->nodes[0] == portal->nodes[1])
3553 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3554 if (portal->nodes[0] == node)
3556 else if (portal->nodes[1] == node)
3558 clipplane.dist = -clipplane.dist;
3559 VectorNegate(clipplane.normal, clipplane.normal);
3564 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3565 side = 0; // hush warning
3568 for (i = 0;i < nodeportal->numpoints*3;i++)
3569 frontpoints[i] = nodeportal->points[i];
3570 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);
3571 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3575 if (nodeportal->numpoints < 3)
3577 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3578 nodeportal->numpoints = 0;
3580 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3582 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3583 nodeportal->numpoints = 0;
3586 AddPortalToNodes(nodeportal, front, back);
3588 // split the portals of this node along this node's plane and assign them to the children of this node
3589 // (migrating the portals downward through the tree)
3590 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3592 if (portal->nodes[0] == portal->nodes[1])
3593 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3594 if (portal->nodes[0] == node)
3596 else if (portal->nodes[1] == node)
3600 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3601 side = 0; // hush warning
3603 nextportal = portal->next[side];
3604 if (!portal->numpoints)
3607 other_node = portal->nodes[!side];
3608 RemovePortalFromNodes(portal);
3610 // cut the portal into two portals, one on each side of the node plane
3611 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);
3613 if (!numfrontpoints)
3616 AddPortalToNodes(portal, back, other_node);
3618 AddPortalToNodes(portal, other_node, back);
3624 AddPortalToNodes(portal, front, other_node);
3626 AddPortalToNodes(portal, other_node, front);
3630 // the portal is split
3631 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3632 temp = splitportal->chain;
3633 *splitportal = *portal;
3634 splitportal->chain = temp;
3635 for (i = 0;i < numbackpoints*3;i++)
3636 splitportal->points[i] = backpoints[i];
3637 splitportal->numpoints = numbackpoints;
3638 for (i = 0;i < numfrontpoints*3;i++)
3639 portal->points[i] = frontpoints[i];
3640 portal->numpoints = numfrontpoints;
3644 AddPortalToNodes(portal, front, other_node);
3645 AddPortalToNodes(splitportal, back, other_node);
3649 AddPortalToNodes(portal, other_node, front);
3650 AddPortalToNodes(splitportal, other_node, back);
3654 Mod_Q1BSP_RecursiveNodePortals(front);
3655 Mod_Q1BSP_RecursiveNodePortals(back);
3657 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3660 static void Mod_Q1BSP_MakePortals(void)
3662 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3663 portalpointsbufferoffset = 0;
3664 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3665 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3666 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3667 Mem_Free(portalpointsbuffer);
3668 portalpointsbuffer = NULL;
3669 portalpointsbufferoffset = 0;
3670 portalpointsbuffersize = 0;
3671 Mod_Q1BSP_FinalizePortals();
3672 Mem_ExpandableArray_FreeArray(&portalarray);
3675 //Returns PVS data for a given point
3676 //(note: can return NULL)
3677 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3680 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3682 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3683 if (((mleaf_t *)node)->clusterindex >= 0)
3684 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3689 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)
3693 float d = PlaneDiff(org, node->plane);
3695 node = node->children[0];
3696 else if (d < -radius)
3697 node = node->children[1];
3700 // go down both sides
3701 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3702 node = node->children[1];
3705 // if this leaf is in a cluster, accumulate the pvs bits
3706 if (((mleaf_t *)node)->clusterindex >= 0)
3709 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3710 for (i = 0;i < pvsbytes;i++)
3711 pvsbuffer[i] |= pvs[i];
3715 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3716 //of the given point.
3717 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3719 int bytes = model->brush.num_pvsclusterbytes;
3720 bytes = min(bytes, pvsbufferlength);
3721 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3723 memset(pvsbuffer, 0xFF, bytes);
3727 memset(pvsbuffer, 0, bytes);
3728 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3732 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3737 VectorSubtract(inmaxs, inmins, size);
3738 if (cmodel->brush.ishlbsp)
3741 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3742 else if (size[0] <= 32)
3744 if (size[2] < 54) // pick the nearest of 36 or 72
3745 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3747 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3750 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3755 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3756 else if (size[0] <= 32)
3757 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3759 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3761 VectorCopy(inmins, outmins);
3762 VectorAdd(inmins, hull->clip_size, outmaxs);
3765 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3768 int numshadowmeshtriangles = 0;
3769 msurface_t *surface;
3770 if (cls.state == ca_dedicated)
3772 // make a single combined shadow mesh to allow optimized shadow volume creation
3774 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3776 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3777 numshadowmeshtriangles += surface->num_triangles;
3779 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3780 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3781 if (surface->num_triangles > 0)
3782 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));
3783 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3784 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3785 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3787 return numshadowmeshtriangles;
3790 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);
3792 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3795 sizebuf_t lumpsb[HEADER_LUMPS];
3797 float dist, modelyawradius, modelradius;
3798 msurface_t *surface;
3799 hullinfo_t hullinfo;
3800 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3801 model_brush_lightstyleinfo_t styleinfo[256];
3802 unsigned char *datapointer;
3805 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3807 mod->type = mod_brushq1;
3809 mod->brush.ishlbsp = false;
3810 mod->brush.isbsp2rmqe = false;
3811 mod->brush.isbsp2 = false;
3812 mod->brush.isq2bsp = false;
3813 mod->brush.isq3bsp = false;
3814 mod->brush.skymasking = true;
3815 i = MSG_ReadLittleLong(&sb);
3819 mod->modeldatatypestring = "Q1BSP";
3822 mod->brush.ishlbsp = true;
3823 mod->modeldatatypestring = "HLBSP";
3825 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3826 mod->brush.isbsp2 = true;
3827 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3828 mod->modeldatatypestring = "Q1BSP2rmqe";
3830 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3831 mod->brush.isbsp2 = true;
3832 mod->modeldatatypestring = "Q1BSP2";
3835 mod->modeldatatypestring = "Unknown BSP";
3836 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);
3840 // fill in hull info
3841 VectorClear (hullinfo.hullsizes[0][0]);
3842 VectorClear (hullinfo.hullsizes[0][1]);
3843 if (mod->brush.ishlbsp)
3845 hullinfo.filehulls = 4;
3846 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3847 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3848 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3849 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3850 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3851 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3855 hullinfo.filehulls = 4;
3856 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3857 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3858 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3859 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3863 for (i = 0; i < HEADER_LUMPS; i++)
3865 int offset = MSG_ReadLittleLong(&sb);
3866 int size = MSG_ReadLittleLong(&sb);
3867 if (offset < 0 || offset + size > sb.cursize)
3868 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);
3869 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3872 mod->soundfromcenter = true;
3873 mod->TraceBox = Mod_Q1BSP_TraceBox;
3874 mod->TraceLine = Mod_Q1BSP_TraceLine;
3875 mod->TracePoint = Mod_Q1BSP_TracePoint;
3876 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3877 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3878 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3879 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3880 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3881 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3882 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3883 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3884 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3885 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3886 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3887 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3888 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3889 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3890 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3891 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3892 mod->Draw = R_Q1BSP_Draw;
3893 mod->DrawDepth = R_Q1BSP_DrawDepth;
3894 mod->DrawDebug = R_Q1BSP_DrawDebug;
3895 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3896 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3897 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3898 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3899 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3900 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3901 mod->DrawLight = R_Q1BSP_DrawLight;
3905 mod->brush.qw_md4sum = 0;
3906 mod->brush.qw_md4sum2 = 0;
3907 for (i = 0;i < HEADER_LUMPS;i++)
3910 if (i == LUMP_ENTITIES)
3912 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3913 mod->brush.qw_md4sum ^= LittleLong(temp);
3914 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3916 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3919 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3920 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3921 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3922 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3923 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3924 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3925 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3926 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3927 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3928 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3929 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3930 // load submodels before leafs because they contain the number of vis leafs
3931 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3932 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3933 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3934 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3936 for (i = 0; i < HEADER_LUMPS; i++)
3937 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3938 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3940 // check if the map supports transparent water rendering
3941 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3943 // we don't need the compressed pvs data anymore
3944 if (mod->brushq1.data_compressedpvs)
3945 Mem_Free(mod->brushq1.data_compressedpvs);
3946 mod->brushq1.data_compressedpvs = NULL;
3947 mod->brushq1.num_compressedpvs = 0;
3949 Mod_Q1BSP_MakeHull0();
3950 if (mod_bsp_portalize.integer)
3951 Mod_Q1BSP_MakePortals();
3953 mod->numframes = 2; // regular and alternate animation
3956 // make a single combined shadow mesh to allow optimized shadow volume creation
3957 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3959 if (loadmodel->brush.numsubmodels)
3960 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3962 // LordHavoc: to clear the fog around the original quake submodel code, I
3964 // first of all, some background info on the submodels:
3965 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3966 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3967 // now the weird for loop itself:
3968 // the loop functions in an odd way, on each iteration it sets up the
3969 // current 'mod' model (which despite the confusing code IS the model of
3970 // the number i), at the end of the loop it duplicates the model to become
3971 // the next submodel, and loops back to set up the new submodel.
3973 // LordHavoc: now the explanation of my sane way (which works identically):
3974 // set up the world model, then on each submodel copy from the world model
3975 // and set up the submodel with the respective model info.
3976 totalstylesurfaces = 0;
3978 for (i = 0;i < mod->brush.numsubmodels;i++)
3980 memset(stylecounts, 0, sizeof(stylecounts));
3981 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3983 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3984 for (j = 0;j < MAXLIGHTMAPS;j++)
3985 stylecounts[surface->lightmapinfo->styles[j]]++;
3987 for (k = 0;k < 255;k++)
3991 totalstylesurfaces += stylecounts[k];
3994 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3995 for (i = 0;i < mod->brush.numsubmodels;i++)
3997 // LordHavoc: this code was originally at the end of this loop, but
3998 // has been transformed to something more readable at the start here.
4003 // duplicate the basic information
4004 dpsnprintf(name, sizeof(name), "*%i", i);
4005 mod = Mod_FindName(name, loadmodel->name);
4006 // copy the base model to this one
4008 // rename the clone back to its proper name
4009 strlcpy(mod->name, name, sizeof(mod->name));
4010 mod->brush.parentmodel = loadmodel;
4011 // textures and memory belong to the main model
4012 mod->texturepool = NULL;
4013 mod->mempool = NULL;
4014 mod->brush.GetPVS = NULL;
4015 mod->brush.FatPVS = NULL;
4016 mod->brush.BoxTouchingPVS = NULL;
4017 mod->brush.BoxTouchingLeafPVS = NULL;
4018 mod->brush.BoxTouchingVisibleLeafs = NULL;
4019 mod->brush.FindBoxClusters = NULL;
4020 mod->brush.LightPoint = NULL;
4021 mod->brush.AmbientSoundLevelsForPoint = NULL;
4024 mod->brush.submodel = i;
4026 if (loadmodel->brush.submodels)
4027 loadmodel->brush.submodels[i] = mod;
4029 bm = &mod->brushq1.submodels[i];
4031 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4032 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4034 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4035 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4038 mod->firstmodelsurface = bm->firstface;
4039 mod->nummodelsurfaces = bm->numfaces;
4041 // set node/leaf parents for this submodel
4042 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4044 // make the model surface list (used by shadowing/lighting)
4045 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4046 Mod_MakeSortedSurfaces(mod);
4048 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4049 // (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)
4050 VectorCopy(bm->mins, mod->normalmins);
4051 VectorCopy(bm->maxs, mod->normalmaxs);
4052 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4053 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4054 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4055 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4056 modelradius = modelyawradius + modelradius * modelradius;
4057 modelyawradius = sqrt(modelyawradius);
4058 modelradius = sqrt(modelradius);
4059 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4060 mod->yawmins[2] = mod->normalmins[2];
4061 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4062 mod->yawmaxs[2] = mod->normalmaxs[2];
4063 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4064 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4065 mod->radius = modelradius;
4066 mod->radius2 = modelradius * modelradius;
4068 // this gets altered below if sky or water is used
4069 mod->DrawSky = NULL;
4070 mod->DrawAddWaterPlanes = NULL;
4072 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4073 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4074 if (mod->nummodelsurfaces)
4076 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4077 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4079 if (j < mod->nummodelsurfaces)
4080 mod->DrawSky = R_Q1BSP_DrawSky;
4082 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4083 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4085 if (j < mod->nummodelsurfaces)
4086 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4088 // build lightstyle update chains
4089 // (used to rapidly mark lightmapupdateflags on many surfaces
4090 // when d_lightstylevalue changes)
4091 memset(stylecounts, 0, sizeof(stylecounts));
4092 for (k = 0;k < mod->nummodelsurfaces;k++)
4094 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4095 for (j = 0;j < MAXLIGHTMAPS;j++)
4096 stylecounts[surface->lightmapinfo->styles[j]]++;
4098 mod->brushq1.num_lightstyles = 0;
4099 for (k = 0;k < 255;k++)
4103 styleinfo[mod->brushq1.num_lightstyles].style = k;
4104 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4105 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4106 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4107 remapstyles[k] = mod->brushq1.num_lightstyles;
4108 mod->brushq1.num_lightstyles++;
4111 for (k = 0;k < mod->nummodelsurfaces;k++)
4113 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4114 for (j = 0;j < MAXLIGHTMAPS;j++)
4116 if (surface->lightmapinfo->styles[j] != 255)
4118 int r = remapstyles[surface->lightmapinfo->styles[j]];
4119 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4123 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4124 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4128 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4129 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4131 //mod->brushq1.num_visleafs = bm->visleafs;
4133 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4134 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4136 if (mod_q1bsp_polygoncollisions.integer)
4138 mod->collision_bih = mod->render_bih;
4139 // point traces and contents checks still use the bsp tree
4140 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4141 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4142 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4143 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4146 // generate VBOs and other shared data before cloning submodels
4150 Mod_Q1BSP_LoadMapBrushes();
4151 //Mod_Q1BSP_ProcessLightList();
4155 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);
4158 int Mod_Q2BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
4160 int supercontents = 0;
4161 if (nativecontents & CONTENTSQ2_SOLID)
4162 supercontents |= SUPERCONTENTS_SOLID;
4163 if (nativecontents & CONTENTSQ2_WATER)
4164 supercontents |= SUPERCONTENTS_WATER;
4165 if (nativecontents & CONTENTSQ2_SLIME)
4166 supercontents |= SUPERCONTENTS_SLIME;
4167 if (nativecontents & CONTENTSQ2_LAVA)
4168 supercontents |= SUPERCONTENTS_LAVA;
4169 if (nativecontents & CONTENTSQ2_MONSTER)
4170 supercontents |= SUPERCONTENTS_BODY;
4171 if (nativecontents & CONTENTSQ2_DEADMONSTER)
4172 supercontents |= SUPERCONTENTS_CORPSE;
4173 if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4174 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4175 if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4176 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4177 if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4178 supercontents |= SUPERCONTENTS_OPAQUE;
4179 return supercontents;
4182 int Mod_Q2BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
4184 int nativecontents = 0;
4185 if (supercontents & SUPERCONTENTS_SOLID)
4186 nativecontents |= CONTENTSQ2_SOLID;
4187 if (supercontents & SUPERCONTENTS_WATER)
4188 nativecontents |= CONTENTSQ2_WATER;
4189 if (supercontents & SUPERCONTENTS_SLIME)
4190 nativecontents |= CONTENTSQ2_SLIME;
4191 if (supercontents & SUPERCONTENTS_LAVA)
4192 nativecontents |= CONTENTSQ2_LAVA;
4193 if (supercontents & SUPERCONTENTS_BODY)
4194 nativecontents |= CONTENTSQ2_MONSTER;
4195 if (supercontents & SUPERCONTENTS_CORPSE)
4196 nativecontents |= CONTENTSQ2_DEADMONSTER;
4197 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4198 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4199 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4200 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4201 if (!(supercontents & SUPERCONTENTS_OPAQUE))
4202 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4203 return nativecontents;
4206 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4209 loadmodel->brushq1.num_compressedpvs = 0;
4210 loadmodel->brushq1.data_compressedpvs = NULL;
4211 loadmodel->brush.num_pvsclusters = 0;
4212 loadmodel->brush.num_pvsclusterbytes = 0;
4213 loadmodel->brush.data_pvsclusters = NULL;
4218 count = MSG_ReadLittleLong(sb);
4219 loadmodel->brush.num_pvsclusters = count;
4220 loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4221 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4222 for (i = 0;i < count;i++)
4224 int pvsofs = MSG_ReadLittleLong(sb);
4225 /*int phsofs = */MSG_ReadLittleLong(sb);
4226 // decompress the vis data for this cluster
4227 // (note this accesses the underlying data store of sb, which is kind of evil)
4228 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);
4230 // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4231 sb->readcount = sb->cursize;
4234 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4236 int i, j, count, p, child[2];
4238 int structsize = 28;
4240 if (sb->cursize % structsize)
4241 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4242 count = sb->cursize / structsize;
4244 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4245 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4247 loadmodel->brush.data_nodes = out;
4248 loadmodel->brush.num_nodes = count;
4250 for ( i=0 ; i<count ; i++, out++)
4252 p = MSG_ReadLittleLong(sb);
4253 out->plane = loadmodel->brush.data_planes + p;
4254 child[0] = MSG_ReadLittleLong(sb);
4255 child[1] = MSG_ReadLittleLong(sb);
4256 out->mins[0] = MSG_ReadLittleShort(sb);
4257 out->mins[1] = MSG_ReadLittleShort(sb);
4258 out->mins[2] = MSG_ReadLittleShort(sb);
4259 out->maxs[0] = MSG_ReadLittleShort(sb);
4260 out->maxs[1] = MSG_ReadLittleShort(sb);
4261 out->maxs[2] = MSG_ReadLittleShort(sb);
4262 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4263 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4264 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4266 Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4267 out->firstsurface = 0;
4268 out->numsurfaces = 0;
4270 for (j=0 ; j<2 ; j++)
4275 if (p < loadmodel->brush.num_nodes)
4276 out->children[j] = loadmodel->brush.data_nodes + p;
4279 Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4280 // map it to the solid leaf
4281 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4286 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4288 if (p < loadmodel->brush.num_leafs)
4289 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4292 Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4293 // map it to the solid leaf
4294 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4300 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
4303 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4307 int structsize = 76;
4308 int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4309 char filename[MAX_QPATH];
4311 if (sb->cursize % structsize)
4312 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4313 count = sb->cursize / structsize;
4314 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4315 loadmodel->brushq1.texinfo = out;
4316 loadmodel->brushq1.numtexinfo = count;
4317 loadmodel->num_texturesperskin = 0;
4318 loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4320 for (i = 0;i < count;i++, out++)
4323 for (k = 0;k < 2;k++)
4324 for (j = 0;j < 4;j++)
4325 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4327 out->q2flags = MSG_ReadLittleLong(sb);
4328 out->q2value = MSG_ReadLittleLong(sb);
4329 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4330 out->q2texture[31] = 0; // make absolutely sure it is terminated
4331 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4333 // find an existing match for the texture if possible
4334 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4335 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4336 if (!strcmp(filename, loadmodel->data_textures[j].name)
4337 && out->q2flags == loadmodel->data_textures[j].q2flags
4338 && out->q2value == loadmodel->data_textures[j].q2value)
4340 // if we don't find the texture, store the new texture
4341 if (j == loadmodel->num_texturesperskin)
4343 if (loadmodel->num_texturesperskin < maxtextures)
4345 texture_t *tx = loadmodel->data_textures + j;
4346 int q2flags = out->q2flags;
4347 unsigned char *walfile = NULL;
4348 fs_offset_t walfilesize = 0;
4349 Mod_LoadTextureFromQ3Shader(tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4350 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4351 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4355 LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4365 tx->q2flags = out->q2flags;
4366 tx->q2value = out->q2value;
4367 // also modify the texture to have the correct contents and such based on flags
4368 // note that we create multiple texture_t structures if q2flags differs
4369 if (q2flags & Q2SURF_LIGHT)
4371 // doesn't mean anything to us
4373 if (q2flags & Q2SURF_SLICK)
4375 // would be nice to support...
4377 if (q2flags & Q2SURF_SKY)
4379 // sky is a rather specific thing
4380 q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4381 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
4382 tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4383 tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4385 if (q2flags & Q2SURF_WARP)
4387 // we use a scroll instead of a warp
4388 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4389 // if it's also transparent, we can enable the WATERSHADER
4390 // but we do not set the WATERALPHA flag because we don't
4391 // want to honor r_wateralpha in q2bsp
4392 // (it would go against the artistic intent)
4393 if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4394 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4396 if (q2flags & Q2SURF_TRANS33)
4398 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4399 tx->basealpha = 1.0f / 3.0f;
4400 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4401 if (tx->q2contents & Q2CONTENTS_SOLID)
4402 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4404 if (q2flags & Q2SURF_TRANS66)
4406 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4407 tx->basealpha = 2.0f / 3.0f;
4408 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4409 if (tx->q2contents & Q2CONTENTS_SOLID)
4410 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4412 if (q2flags & Q2SURF_FLOWING)
4414 tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4415 if (q2flags & Q2SURF_WARP)
4416 tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
4418 tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
4419 tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
4421 if (q2flags & Q2SURF_ALPHATEST)
4423 // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4424 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4426 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4428 if (!mod_q2bsp_littransparentsurfaces.integer)
4429 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4431 if (q2flags & Q2SURF_NODRAW)
4433 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4435 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4436 tx->q2contents |= Q2CONTENTS_DETAIL;
4437 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4438 tx->q2contents |= Q2CONTENTS_SOLID;
4439 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4441 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(loadmodel, tx->q2contents);
4442 // set the current values to the base values
4443 tx->currentframe = tx;
4444 tx->currentskinframe = tx->materialshaderpass->skinframes[0];
4445 tx->currentmaterialflags = tx->basematerialflags;
4446 loadmodel->num_texturesperskin++;
4447 loadmodel->num_textures = loadmodel->num_texturesperskin;
4451 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4452 j = 0; // use first texture and give up
4455 // store the index we found for this texture
4456 out->textureindex = j;
4459 // realloc the textures array now that we know how many we actually need
4460 loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4462 // now assemble the texture chains
4463 // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier
4464 for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4467 texture_t *t = loadmodel->data_textures + out->textureindex;
4468 t->currentframe = t; // fix the reallocated pointer
4470 // if this is not animated, skip it
4471 // if this is already processed, skip it (part of an existing sequence)
4472 if (out->q2nexttexinfo == 0 || t->animated)
4475 // store the array of frames to use
4476 t->animated = 2; // q2bsp animation
4477 t->anim_total[0] = 0;
4478 t->anim_total[1] = 0;
4479 // gather up to 10 frames (we don't support more)
4480 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)
4482 // detect looping and stop there
4483 if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4485 t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4487 // we could look for the +a sequence here if this is the +0 sequence,
4488 // but it seems that quake2 did not implement that (even though the
4489 // files exist in the baseq2 content)
4491 // write the frame sequence to all the textures involved (just like
4492 // in the q1bsp loader)
4494 // note that this can overwrite the rest of the sequence - so if the
4495 // start of a sequence is found later than the other parts of the
4496 // sequence, it will go back and rewrite them correctly.
4497 for (k = 0;k < t->anim_total[0];k++)
4499 texture_t *txk = t->anim_frames[0][k];
4500 txk->animated = t->animated;
4501 txk->anim_total[0] = t->anim_total[0];
4502 for (l = 0;l < t->anim_total[0];l++)
4503 txk->anim_frames[0][l] = t->anim_frames[0][l];
4508 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4510 // LordHavoc: this fits exactly the same format that we use in .lit files
4511 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4512 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4515 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4518 int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4519 int structsize = 28;
4521 if (sb->cursize % structsize)
4522 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4523 count = sb->cursize / structsize;
4524 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4526 loadmodel->brush.data_leafs = out;
4527 loadmodel->brush.num_leafs = count;
4529 // FIXME: this function could really benefit from some error checking
4530 for ( i=0 ; i<count ; i++, out++)
4532 out->contents = MSG_ReadLittleLong(sb);
4533 out->clusterindex = MSG_ReadLittleShort(sb);
4534 out->areaindex = MSG_ReadLittleShort(sb);
4535 out->mins[0] = MSG_ReadLittleShort(sb);
4536 out->mins[1] = MSG_ReadLittleShort(sb);
4537 out->mins[2] = MSG_ReadLittleShort(sb);
4538 out->maxs[0] = MSG_ReadLittleShort(sb);
4539 out->maxs[1] = MSG_ReadLittleShort(sb);
4540 out->maxs[2] = MSG_ReadLittleShort(sb);
4542 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4543 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4544 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4545 nummarkbrushes = (unsigned short)MSG_ReadLittleShort(sb);
4547 for (j = 0;j < 4;j++)
4548 out->ambient_sound_level[j] = 0;
4550 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4552 Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4553 out->clusterindex = -1;
4556 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4558 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4559 out->numleafsurfaces = nummarksurfaces;
4563 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4564 out->firstleafsurface = NULL;
4565 out->numleafsurfaces = 0;
4568 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4570 out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4571 out->numleafbrushes = nummarkbrushes;
4575 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4576 out->firstleafbrush = NULL;
4577 out->numleafbrushes = 0;
4582 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4587 if (sb->cursize % structsize)
4588 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4589 loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4590 loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4592 for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4594 j = (unsigned short) MSG_ReadLittleShort(sb);
4595 if (j >= loadmodel->brush.num_brushes)
4596 Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4597 loadmodel->brush.data_leafbrushes[i] = j;
4601 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4603 q3mbrushside_t *out;
4607 if (sb->cursize % structsize)
4608 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4609 count = sb->cursize / structsize;
4610 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4612 loadmodel->brush.data_brushsides = out;
4613 loadmodel->brush.num_brushsides = count;
4615 for (i = 0;i < count;i++, out++)
4617 n = (unsigned short)MSG_ReadLittleShort(sb);
4618 if (n < 0 || n >= loadmodel->brush.num_planes)
4619 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4620 out->plane = loadmodel->brush.data_planes + n;
4621 n = MSG_ReadLittleShort(sb);
4624 if (n >= loadmodel->brushq1.numtexinfo)
4625 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4626 out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4630 //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4631 out->texture = &mod_q1bsp_texture_solid;
4636 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4639 int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4640 colplanef_t *planes;
4641 int structsize = 12;
4642 qboolean brushmissingtextures;
4643 int numbrushesmissingtextures = 0;
4644 int numcreatedtextures = 0;
4646 if (sb->cursize % structsize)
4647 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4648 count = sb->cursize / structsize;
4649 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4651 loadmodel->brush.data_brushes = out;
4652 loadmodel->brush.num_brushes = count;
4657 for (i = 0; i < count; i++, out++)
4659 firstside = MSG_ReadLittleLong(sb);
4660 numsides = MSG_ReadLittleLong(sb);
4661 contents = MSG_ReadLittleLong(sb);
4662 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4663 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4665 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4666 out->numbrushsides = numsides;
4667 // convert the contents to our values
4668 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(loadmodel, contents);
4670 // problem: q2bsp brushes have contents but not a texture
4671 // problem: q2bsp brushsides *may* have a texture or may not
4672 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4673 // solution: nasty hacks
4674 brushmissingtextures = false;
4675 out->texture = NULL;
4676 for (j = 0; j < out->numbrushsides; j++)
4678 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4679 brushmissingtextures = true;
4682 // if we can find a matching texture on a brush side we can use it instead of creating one
4683 if (out->firstbrushside[j].texture->supercontents == supercontents)
4684 out->texture = out->firstbrushside[j].texture;
4687 if (brushmissingtextures || out->texture == NULL)
4689 numbrushesmissingtextures++;
4690 // if we didn't find any appropriate texture (matching contents), we'll have to create one
4691 // we could search earlier ones for a matching one but that can be slow
4692 if (out->texture == NULL)
4694 texture_t *validtexture;
4695 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4696 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4697 validtexture->surfaceflags = 0;
4698 validtexture->supercontents = supercontents;
4699 numcreatedtextures++;
4700 out->texture = validtexture;
4702 // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4703 for (j = 0; j < out->numbrushsides; j++)
4704 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4705 out->firstbrushside[j].texture = out->texture;
4708 // make a colbrush from the brush
4710 // make a list of mplane_t structs to construct a colbrush from
4711 if (maxplanes < out->numbrushsides)
4713 maxplanes = out->numbrushsides;
4716 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4718 for (j = 0;j < out->numbrushsides;j++)
4720 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4721 planes[j].dist = out->firstbrushside[j].plane->dist;
4722 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4723 planes[j].texture = out->firstbrushside[j].texture;
4724 q3surfaceflags |= planes[j].q3surfaceflags;
4726 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4728 // this whole loop can take a while (e.g. on redstarrepublic4)
4729 CL_KeepaliveMessage(false);
4733 if (numcreatedtextures)
4734 Con_DPrintf("Mod_Q2BSP_LoadBrushes: %i brushes own sides that lack textures or have differing contents from the brush, %i textures have been created to describe these contents.\n", numbrushesmissingtextures, numcreatedtextures);
4737 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4739 // this is probably a "proof of purchase" lump of some sort, it seems to be 0 size in most bsp files (but not q2dm1.bsp for instance)
4740 sb->readcount = sb->cursize;
4743 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4745 // we currently don't use areas, they represent closable doors as vis blockers
4746 sb->readcount = sb->cursize;
4749 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4751 // we currently don't use areas, they represent closable doors as vis blockers
4752 sb->readcount = sb->cursize;
4755 static void Mod_Q2BSP_LoadSubmodels(sizebuf_t *sb)
4759 int structsize = 48;
4761 if (sb->cursize % structsize)
4762 Host_Error ("Mod_Q2BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
4764 count = sb->cursize / structsize;
4765 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
4767 loadmodel->brushq1.submodels = out;
4768 loadmodel->brush.numsubmodels = count;
4770 // this is identical to the q1 submodel structure except for having 1 hull
4771 for (i = 0; i < count; i++, out++)
4773 // spread out the mins / maxs by a pixel
4774 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
4775 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
4776 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
4777 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
4778 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
4779 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
4780 out->origin[0] = MSG_ReadLittleFloat(sb);
4781 out->origin[1] = MSG_ReadLittleFloat(sb);
4782 out->origin[2] = MSG_ReadLittleFloat(sb);
4783 out->headnode[0] = MSG_ReadLittleLong(sb);
4784 out->firstface = MSG_ReadLittleLong(sb);
4785 out->numfaces = MSG_ReadLittleLong(sb);
4789 static void Mod_Q2BSP_FindSubmodelBrushRange_r(dp_model_t *mod, mnode_t *node, int *first, int *last)
4795 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4796 node = node->children[1];
4798 leaf = (mleaf_t*)node;
4799 for (i = 0;i < leaf->numleafbrushes;i++)
4801 int brushnum = leaf->firstleafbrush[i];
4802 if (*first > brushnum)
4804 if (*last < brushnum)
4809 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4812 sizebuf_t lumpsb[Q2HEADER_LUMPS];
4814 float dist, modelyawradius, modelradius;
4815 msurface_t *surface;
4816 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4817 model_brush_lightstyleinfo_t styleinfo[256];
4818 unsigned char *datapointer;
4821 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4823 mod->type = mod_brushq2;
4825 mod->brush.ishlbsp = false;
4826 mod->brush.isbsp2rmqe = false;
4827 mod->brush.isbsp2 = false;
4828 mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4829 mod->brush.isq3bsp = false;
4830 mod->brush.skymasking = true;
4831 mod->modeldatatypestring = "Q2BSP";
4833 i = MSG_ReadLittleLong(&sb);
4834 if (i != Q2BSPMAGIC)
4835 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4837 i = MSG_ReadLittleLong(&sb);
4838 if (i != Q2BSPVERSION)
4839 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4842 for (i = 0; i < Q2HEADER_LUMPS; i++)
4844 int offset = MSG_ReadLittleLong(&sb);
4845 int size = MSG_ReadLittleLong(&sb);
4846 if (offset < 0 || offset + size > sb.cursize)
4847 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);
4848 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4851 mod->soundfromcenter = true;
4852 mod->TracePoint = Mod_CollisionBIH_TracePoint;
4853 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4854 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4855 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4856 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4857 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4858 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4859 mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4860 mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4861 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
4862 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
4863 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
4864 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
4865 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
4866 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
4867 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
4868 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
4869 mod->brush.AmbientSoundLevelsForPoint = NULL;
4870 mod->brush.RoundUpToHullSize = NULL;
4871 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
4872 mod->Draw = R_Q1BSP_Draw;
4873 mod->DrawDepth = R_Q1BSP_DrawDepth;
4874 mod->DrawDebug = R_Q1BSP_DrawDebug;
4875 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
4876 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
4877 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
4878 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
4879 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
4880 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
4881 mod->DrawLight = R_Q1BSP_DrawLight;
4885 mod->brush.qw_md4sum = 0;
4886 mod->brush.qw_md4sum2 = 0;
4887 for (i = 0;i < Q2HEADER_LUMPS;i++)
4890 if (i == Q2LUMP_ENTITIES)
4892 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4893 mod->brush.qw_md4sum ^= LittleLong(temp);
4894 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4896 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4899 // many of these functions are identical to Q1 loaders, so we use those where possible
4900 Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4901 Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4902 Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4903 Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4904 Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4905 Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4906 Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4907 Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4908 Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4909 Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4910 Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4911 Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4912 Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4913 Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4914 Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4915 Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4916 Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4917 Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4918 Mod_Q2BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS]);
4920 for (i = 0; i < Q2HEADER_LUMPS; i++)
4921 if (lumpsb[i].readcount != lumpsb[i].cursize)
4922 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4924 // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4925 // doesn't enable the cvar, just indicates that transparent water is OK
4926 loadmodel->brush.supportwateralpha = true;
4928 // we don't need the compressed pvs data anymore
4929 if (mod->brushq1.data_compressedpvs)
4930 Mem_Free(mod->brushq1.data_compressedpvs);
4931 mod->brushq1.data_compressedpvs = NULL;
4932 mod->brushq1.num_compressedpvs = 0;
4934 // the MakePortals code works fine on the q2bsp data as well
4935 if (mod_bsp_portalize.integer)
4936 Mod_Q1BSP_MakePortals();
4938 mod->numframes = 0; // q2bsp animations are kind of special, frame is unbounded...
4941 // make a single combined shadow mesh to allow optimized shadow volume creation
4942 Mod_Q1BSP_CreateShadowMesh(loadmodel);
4944 if (loadmodel->brush.numsubmodels)
4945 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
4947 totalstylesurfaces = 0;
4949 for (i = 0;i < mod->brush.numsubmodels;i++)
4951 memset(stylecounts, 0, sizeof(stylecounts));
4952 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4954 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4955 for (j = 0;j < MAXLIGHTMAPS;j++)
4956 stylecounts[surface->lightmapinfo->styles[j]]++;
4958 for (k = 0;k < 255;k++)
4962 totalstylesurfaces += stylecounts[k];
4965 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4966 // set up the world model, then on each submodel copy from the world model
4967 // and set up the submodel with the respective model info.
4969 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
4971 mnode_t *rootnode = NULL;
4972 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
4976 // duplicate the basic information
4977 dpsnprintf(name, sizeof(name), "*%i", i);
4978 mod = Mod_FindName(name, loadmodel->name);
4979 // copy the base model to this one
4981 // rename the clone back to its proper name
4982 strlcpy(mod->name, name, sizeof(mod->name));
4983 mod->brush.parentmodel = loadmodel;
4984 // textures and memory belong to the main model
4985 mod->texturepool = NULL;
4986 mod->mempool = NULL;
4987 mod->brush.GetPVS = NULL;
4988 mod->brush.FatPVS = NULL;
4989 mod->brush.BoxTouchingPVS = NULL;
4990 mod->brush.BoxTouchingLeafPVS = NULL;
4991 mod->brush.BoxTouchingVisibleLeafs = NULL;
4992 mod->brush.FindBoxClusters = NULL;
4993 mod->brush.LightPoint = NULL;
4994 mod->brush.AmbientSoundLevelsForPoint = NULL;
4996 mod->brush.submodel = i;
4997 if (loadmodel->brush.submodels)
4998 loadmodel->brush.submodels[i] = mod;
5000 bm = &mod->brushq1.submodels[i];
5002 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5003 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5005 mod->firstmodelsurface = bm->firstface;
5006 mod->nummodelsurfaces = bm->numfaces;
5008 // set node/leaf parents for this submodel
5009 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5010 // (this happens in base3.bsp)
5011 if (bm->headnode[0] >= 0)
5012 rootnode = mod->brush.data_nodes + bm->headnode[0];
5014 rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5015 Mod_Q1BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5017 // make the model surface list (used by shadowing/lighting)
5018 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
5019 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5020 if (firstbrush <= lastbrush)
5022 mod->firstmodelbrush = firstbrush;
5023 mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5027 mod->firstmodelbrush = 0;
5028 mod->nummodelbrushes = 0;
5030 Mod_MakeSortedSurfaces(mod);
5032 VectorCopy(bm->mins, mod->normalmins);
5033 VectorCopy(bm->maxs, mod->normalmaxs);
5034 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5035 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5036 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5037 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5038 modelradius = modelyawradius + modelradius * modelradius;
5039 modelyawradius = sqrt(modelyawradius);
5040 modelradius = sqrt(modelradius);
5041 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5042 mod->yawmins[2] = mod->normalmins[2];
5043 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
5044 mod->yawmaxs[2] = mod->normalmaxs[2];
5045 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5046 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5047 mod->radius = modelradius;
5048 mod->radius2 = modelradius * modelradius;
5050 // this gets altered below if sky or water is used
5051 mod->DrawSky = NULL;
5052 mod->DrawAddWaterPlanes = NULL;
5054 // scan surfaces for sky and water and flag the submodel as possessing these features or not
5055 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5056 if (mod->nummodelsurfaces)
5058 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5059 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
5061 if (j < mod->nummodelsurfaces)
5062 mod->DrawSky = R_Q1BSP_DrawSky;
5064 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5065 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
5067 if (j < mod->nummodelsurfaces)
5068 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
5070 // build lightstyle update chains
5071 // (used to rapidly mark lightmapupdateflags on many surfaces
5072 // when d_lightstylevalue changes)
5073 memset(stylecounts, 0, sizeof(stylecounts));
5074 for (k = 0;k < mod->nummodelsurfaces;k++)
5076 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5077 for (j = 0;j < MAXLIGHTMAPS;j++)
5078 stylecounts[surface->lightmapinfo->styles[j]]++;
5080 mod->brushq1.num_lightstyles = 0;
5081 for (k = 0;k < 255;k++)
5085 styleinfo[mod->brushq1.num_lightstyles].style = k;
5086 styleinfo[mod->brushq1.num_lightstyles].value = 0;
5087 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5088 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
5089 remapstyles[k] = mod->brushq1.num_lightstyles;
5090 mod->brushq1.num_lightstyles++;
5093 for (k = 0;k < mod->nummodelsurfaces;k++)
5095 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5096 for (j = 0;j < MAXLIGHTMAPS;j++)
5098 if (surface->lightmapinfo->styles[j] != 255)
5100 int r = remapstyles[surface->lightmapinfo->styles[j]];
5101 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
5105 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
5106 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5110 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5112 //mod->brushq1.num_visleafs = bm->visleafs;
5114 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5115 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5117 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5118 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5120 // generate VBOs and other shared data before cloning submodels
5126 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);
5129 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
5130 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
5132 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5135 char key[128], value[MAX_INPUTLINE];
5137 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5138 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5139 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5142 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5143 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5144 loadmodel->brush.entities[l->filelen] = 0;
5145 data = loadmodel->brush.entities;
5146 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5147 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5148 loadmodel->brushq3.deluxemapping = false;
5149 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5153 if (!COM_ParseToken_Simple(&data, false, false, true))
5155 if (com_token[0] == '}')
5156 break; // end of worldspawn
5157 if (com_token[0] == '_')
5158 strlcpy(key, com_token + 1, sizeof(key));
5160 strlcpy(key, com_token, sizeof(key));
5161 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5162 key[strlen(key)-1] = 0;
5163 if (!COM_ParseToken_Simple(&data, false, false, true))
5165 strlcpy(value, com_token, sizeof(value));
5166 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5168 #if _MSC_VER >= 1400
5169 #define sscanf sscanf_s
5172 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5173 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5175 VectorSet(v, 64, 64, 128);
5176 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5177 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]);
5178 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5179 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5182 else if (!strcmp("deluxeMaps", key))
5184 if (!strcmp(com_token, "1"))
5186 loadmodel->brushq3.deluxemapping = true;
5187 loadmodel->brushq3.deluxemapping_modelspace = true;
5189 else if (!strcmp(com_token, "2"))
5191 loadmodel->brushq3.deluxemapping = true;
5192 loadmodel->brushq3.deluxemapping_modelspace = false;
5199 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5205 in = (q3dtexture_t *)(mod_base + l->fileofs);
5206 if (l->filelen % sizeof(*in))
5207 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5208 count = l->filelen / sizeof(*in);
5209 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5211 loadmodel->data_textures = out;
5212 loadmodel->num_textures = count;
5213 loadmodel->num_texturesperskin = loadmodel->num_textures;
5215 for (i = 0;i < count;i++)
5217 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5218 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
5219 Mod_LoadTextureFromQ3Shader(out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
5220 // restore the surfaceflags and supercontents
5221 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5222 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
5226 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5232 in = (q3dplane_t *)(mod_base + l->fileofs);
5233 if (l->filelen % sizeof(*in))
5234 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5235 count = l->filelen / sizeof(*in);
5236 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5238 loadmodel->brush.data_planes = out;
5239 loadmodel->brush.num_planes = count;
5241 for (i = 0;i < count;i++, in++, out++)
5243 out->normal[0] = LittleFloat(in->normal[0]);
5244 out->normal[1] = LittleFloat(in->normal[1]);
5245 out->normal[2] = LittleFloat(in->normal[2]);
5246 out->dist = LittleFloat(in->dist);
5251 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5254 q3mbrushside_t *out;
5257 in = (q3dbrushside_t *)(mod_base + l->fileofs);
5258 if (l->filelen % sizeof(*in))
5259 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5260 count = l->filelen / sizeof(*in);
5261 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5263 loadmodel->brush.data_brushsides = out;
5264 loadmodel->brush.num_brushsides = count;
5266 for (i = 0;i < count;i++, in++, out++)
5268 n = LittleLong(in->planeindex);
5269 if (n < 0 || n >= loadmodel->brush.num_planes)
5270 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5271 out->plane = loadmodel->brush.data_planes + n;
5272 n = LittleLong(in->textureindex);
5273 if (n < 0 || n >= loadmodel->num_textures)
5274 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5275 out->texture = loadmodel->data_textures + n;
5279 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5281 q3dbrushside_ig_t *in;
5282 q3mbrushside_t *out;
5285 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5286 if (l->filelen % sizeof(*in))
5287 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5288 count = l->filelen / sizeof(*in);
5289 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5291 loadmodel->brush.data_brushsides = out;
5292 loadmodel->brush.num_brushsides = count;
5294 for (i = 0;i < count;i++, in++, out++)
5296 n = LittleLong(in->planeindex);
5297 if (n < 0 || n >= loadmodel->brush.num_planes)
5298 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5299 out->plane = loadmodel->brush.data_planes + n;
5300 n = LittleLong(in->textureindex);
5301 if (n < 0 || n >= loadmodel->num_textures)
5302 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5303 out->texture = loadmodel->data_textures + n;
5307 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5311 int i, j, n, c, count, maxplanes, q3surfaceflags;
5312 colplanef_t *planes;
5314 in = (q3dbrush_t *)(mod_base + l->fileofs);
5315 if (l->filelen % sizeof(*in))
5316 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5317 count = l->filelen / sizeof(*in);
5318 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5320 loadmodel->brush.data_brushes = out;
5321 loadmodel->brush.num_brushes = count;
5326 for (i = 0;i < count;i++, in++, out++)
5328 n = LittleLong(in->firstbrushside);
5329 c = LittleLong(in->numbrushsides);
5330 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5331 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5332 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5333 out->numbrushsides = c;
5334 n = LittleLong(in->textureindex);
5335 if (n < 0 || n >= loadmodel->num_textures)
5336 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5337 out->texture = loadmodel->data_textures + n;
5339 // make a list of mplane_t structs to construct a colbrush from
5340 if (maxplanes < out->numbrushsides)
5342 maxplanes = out->numbrushsides;
5345 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5348 for (j = 0;j < out->numbrushsides;j++)
5350 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5351 planes[j].dist = out->firstbrushside[j].plane->dist;
5352 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5353 planes[j].texture = out->firstbrushside[j].texture;
5354 q3surfaceflags |= planes[j].q3surfaceflags;
5356 // make the colbrush from the planes
5357 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5359 // this whole loop can take a while (e.g. on redstarrepublic4)
5360 CL_KeepaliveMessage(false);
5366 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5372 in = (q3deffect_t *)(mod_base + l->fileofs);
5373 if (l->filelen % sizeof(*in))
5374 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5375 count = l->filelen / sizeof(*in);
5376 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5378 loadmodel->brushq3.data_effects = out;
5379 loadmodel->brushq3.num_effects = count;
5381 for (i = 0;i < count;i++, in++, out++)
5383 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5384 n = LittleLong(in->brushindex);
5385 if (n >= loadmodel->brush.num_brushes)
5387 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5390 out->brushindex = n;
5391 out->unknown = LittleLong(in->unknown);
5395 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5400 in = (q3dvertex_t *)(mod_base + l->fileofs);
5401 if (l->filelen % sizeof(*in))
5402 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5403 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5404 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5405 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5406 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5407 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5408 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5410 for (i = 0;i < count;i++, in++)
5412 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5413 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5414 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5415 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5416 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5417 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5418 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5419 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5420 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5421 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5422 // svector/tvector are calculated later in face loading
5423 if(mod_q3bsp_sRGBlightmaps.integer)
5425 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5426 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5427 // working like this may be odd, but matches q3map2 -gamma 2.2
5428 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5430 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5431 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5432 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5433 // we fix the brightness consistently via lightmapscale
5437 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5438 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5439 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5444 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5446 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5447 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5448 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5452 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5453 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5454 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5457 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5458 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5459 loadmodel->lit = true;
5463 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5469 in = (int *)(mod_base + l->fileofs);
5470 if (l->filelen % sizeof(int[3]))
5471 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5472 count = l->filelen / sizeof(*in);
5474 if(!loadmodel->brushq3.num_vertices)
5477 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5478 loadmodel->brushq3.num_triangles = 0;
5482 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5483 loadmodel->brushq3.num_triangles = count / 3;
5484 loadmodel->brushq3.data_element3i = out;
5486 for (i = 0;i < count;i++, in++, out++)
5488 *out = LittleLong(*in);
5489 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5491 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5497 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5499 q3dlightmap_t *input_pointer;
5517 int mergedrowsxcolumns;
5522 unsigned char *mergedpixels;
5523 unsigned char *mergeddeluxepixels;
5524 unsigned char *mergebuf;
5525 char mapname[MAX_QPATH];
5527 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5530 // defaults for q3bsp
5537 loadmodel->brushq3.lightmapsize = 128;
5539 if (cls.state == ca_dedicated)
5542 if(mod_q3bsp_nolightmaps.integer)
5548 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5549 if (developer_loading.integer)
5550 Con_Printf("Using internal lightmaps\n");
5551 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5552 if (l->filelen % sizeof(*input_pointer))
5553 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5554 count = l->filelen / sizeof(*input_pointer);
5555 for(i = 0; i < count; ++i)
5556 inpixels[i] = input_pointer[i].rgb;
5560 // no internal lightmaps
5561 // try external lightmaps
5562 if (developer_loading.integer)
5563 Con_Printf("Using external lightmaps\n");
5564 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5565 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5569 // using EXTERNAL lightmaps instead
5570 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5572 Mem_Free(inpixels[0]);
5573 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5583 for(count = 1; ; ++count)
5585 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5586 if(!inpixels[count])
5587 break; // we got all of them
5588 if(image_width != size || image_height != size)
5590 Mem_Free(inpixels[count]);
5591 inpixels[count] = NULL;
5592 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);
5598 loadmodel->brushq3.lightmapsize = size;
5599 loadmodel->brushq3.num_originallightmaps = count;
5601 // now check the surfaces to see if any of them index an odd numbered
5602 // lightmap, if so this is not a deluxemapped bsp file
5604 // also check what lightmaps are actually used, because q3map2 sometimes
5605 // (always?) makes an unused one at the end, which
5606 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5607 // reason when only one lightmap is used, which can throw off the
5608 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5609 // to see if the second lightmap is blank, if so it is not deluxemapped.
5610 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5611 // in Mod_Q3BSP_LoadEntities was failed
5612 if (!loadmodel->brushq3.deluxemapping)
5614 loadmodel->brushq3.deluxemapping = !(count & 1);
5615 loadmodel->brushq3.deluxemapping_modelspace = true;
5617 if (loadmodel->brushq3.deluxemapping)
5619 int facecount = faceslump->filelen / sizeof(q3dface_t);
5620 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5621 for (i = 0;i < facecount;i++)
5623 j = LittleLong(faces[i].lightmapindex);
5626 endlightmap = max(endlightmap, j + 1);
5627 if ((j & 1) || j + 1 >= count)
5629 loadmodel->brushq3.deluxemapping = false;
5636 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5637 // reason when only one lightmap is used, which can throw off the
5638 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5639 // to see if the second lightmap is blank, if so it is not deluxemapped.
5641 // further research has shown q3map2 sometimes creates a deluxemap and two
5642 // blank lightmaps, which must be handled properly as well
5643 if (endlightmap == 1 && count > 1)
5646 for (i = 0;i < size*size;i++)
5648 if (c[bytesperpixel*i + rgbmap[0]])
5650 if (c[bytesperpixel*i + rgbmap[1]])
5652 if (c[bytesperpixel*i + rgbmap[2]])
5657 // all pixels in the unused lightmap were black...
5658 loadmodel->brushq3.deluxemapping = false;
5663 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5665 // figure out what the most reasonable merge power is within limits
5667 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5668 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5670 // figure out how big the merged texture has to be
5671 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5672 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5673 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5675 mergedwidth = mergegoal;
5676 mergedheight = mergegoal;
5677 // choose non-square size (2x1 aspect) if only half the space is used;
5678 // this really only happens when the entire set fits in one texture, if
5679 // there are multiple textures, we don't worry about shrinking the last
5680 // one to fit, because the driver prefers the same texture size on
5681 // consecutive draw calls...
5682 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5685 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5686 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5687 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5688 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5689 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5690 loadmodel->brushq3.num_lightmapmergedheightpower++;
5691 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5693 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5694 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5695 powerxy = powerx+powery;
5696 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5698 mergedcolumns = 1 << powerx;
5699 mergedrows = 1 << powery;
5700 mergedrowsxcolumns = 1 << powerxy;
5702 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5703 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5704 if (loadmodel->brushq3.deluxemapping)
5705 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5707 // allocate a texture pool if we need it
5708 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5709 loadmodel->texturepool = R_AllocTexturePool();
5711 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5712 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5713 for (i = 0;i < count;i++)
5715 // figure out which merged lightmap texture this fits into
5716 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5717 lightmapindex = i >> powerdxy;
5719 // choose the destination address
5720 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5721 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5722 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5723 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);
5725 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5726 for (j = 0;j < size;j++)
5727 for (k = 0;k < size;k++)
5729 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5730 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5731 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5732 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5735 // upload texture if this was the last tile being written to the texture
5736 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5738 if (loadmodel->brushq3.deluxemapping && (i & 1))
5739 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);
5742 if(mod_q3bsp_sRGBlightmaps.integer)
5745 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5747 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5748 // we fix the brightness consistently via lightmapscale
5751 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5752 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);
5756 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5757 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5758 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);
5764 if (mergeddeluxepixels)
5765 Mem_Free(mergeddeluxepixels);
5766 Mem_Free(mergedpixels);
5769 for(i = 0; i < count; ++i)
5770 Mem_Free(inpixels[i]);
5774 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5779 *collisionstride = stride;
5782 cnt = (num_triangles + stride - 1) / stride;
5783 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5784 for(j = 0; j < cnt; ++j)
5786 mins = &((*collisionbbox6f)[6 * j + 0]);
5787 maxs = &((*collisionbbox6f)[6 * j + 3]);
5788 for(k = 0; k < stride; ++k)
5790 tri = j * stride + k;
5791 if(tri >= num_triangles)
5793 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5794 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5795 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5796 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5797 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5798 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5799 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5800 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5801 if(vert[0] < mins[0]) mins[0] = vert[0];
5802 if(vert[1] < mins[1]) mins[1] = vert[1];
5803 if(vert[2] < mins[2]) mins[2] = vert[2];
5804 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5805 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5806 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5807 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5808 if(vert[0] < mins[0]) mins[0] = vert[0];
5809 if(vert[1] < mins[1]) mins[1] = vert[1];
5810 if(vert[2] < mins[2]) mins[2] = vert[2];
5811 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5812 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5813 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5818 *collisionbbox6f = NULL;
5821 typedef struct patchtess_s
5825 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5828 float *originalvertex3f;
5831 #define PATCHTESS_SAME_LODGROUP(a,b) \
5833 (a).lodgroup[0] == (b).lodgroup[0] && \
5834 (a).lodgroup[1] == (b).lodgroup[1] && \
5835 (a).lodgroup[2] == (b).lodgroup[2] && \
5836 (a).lodgroup[3] == (b).lodgroup[3] && \
5837 (a).lodgroup[4] == (b).lodgroup[4] && \
5838 (a).lodgroup[5] == (b).lodgroup[5] \
5841 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5843 q3dface_t *in, *oldin;
5844 msurface_t *out, *oldout;
5845 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;
5846 float lightmaptcbase[2], lightmaptcscale[2];
5847 //int *originalelement3i;
5848 //int *originalneighbor3i;
5849 float *originalvertex3f;
5850 //float *originalsvector3f;
5851 //float *originaltvector3f;
5852 float *originalnormal3f;
5853 float *originalcolor4f;
5854 float *originaltexcoordtexture2f;
5855 float *originaltexcoordlightmap2f;
5856 float *surfacecollisionvertex3f;
5857 int *surfacecollisionelement3i;
5859 patchtess_t *patchtess = NULL;
5860 int patchtesscount = 0;
5863 in = (q3dface_t *)(mod_base + l->fileofs);
5864 if (l->filelen % sizeof(*in))
5865 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5866 count = l->filelen / sizeof(*in);
5867 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5869 loadmodel->data_surfaces = out;
5870 loadmodel->num_surfaces = count;
5873 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5881 for (;i < count;i++, in++, out++)
5883 // check face type first
5884 type = LittleLong(in->type);
5885 if (type != Q3FACETYPE_FLAT
5886 && type != Q3FACETYPE_PATCH
5887 && type != Q3FACETYPE_MESH
5888 && type != Q3FACETYPE_FLARE)
5890 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5894 n = LittleLong(in->textureindex);
5895 if (n < 0 || n >= loadmodel->num_textures)
5897 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5900 out->texture = loadmodel->data_textures + n;
5901 n = LittleLong(in->effectindex);
5902 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5904 if (developer_extra.integer)
5905 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5911 out->effect = loadmodel->brushq3.data_effects + n;
5913 if (cls.state != ca_dedicated)
5915 out->lightmaptexture = NULL;
5916 out->deluxemaptexture = r_texture_blanknormalmap;
5917 n = LittleLong(in->lightmapindex);
5920 else if (n >= loadmodel->brushq3.num_originallightmaps)
5922 if(loadmodel->brushq3.num_originallightmaps != 0)
5923 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5928 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5929 if (loadmodel->brushq3.deluxemapping)
5930 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5931 loadmodel->lit = true;
5935 firstvertex = LittleLong(in->firstvertex);
5936 numvertices = LittleLong(in->numvertices);
5937 firstelement = LittleLong(in->firstelement);
5938 numtriangles = LittleLong(in->numelements) / 3;
5939 if (numtriangles * 3 != LittleLong(in->numelements))
5941 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));
5944 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5946 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);
5949 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5951 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);
5956 case Q3FACETYPE_FLAT:
5957 case Q3FACETYPE_MESH:
5958 // no processing necessary
5960 case Q3FACETYPE_PATCH:
5961 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5962 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5963 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))
5965 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5968 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5970 // convert patch to Q3FACETYPE_MESH
5971 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5972 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5973 // bound to user settings
5974 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5975 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5976 // bound to sanity settings
5977 xtess = bound(0, xtess, 1024);
5978 ytess = bound(0, ytess, 1024);
5980 // lower quality collision patches! Same procedure as before, but different cvars
5981 // convert patch to Q3FACETYPE_MESH
5982 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5983 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5984 // bound to user settings
5985 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5986 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5987 // bound to sanity settings
5988 cxtess = bound(0, cxtess, 1024);
5989 cytess = bound(0, cytess, 1024);
5991 // store it for the LOD grouping step
5992 patchtess[patchtesscount].info.xsize = patchsize[0];
5993 patchtess[patchtesscount].info.ysize = patchsize[1];
5994 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5995 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5996 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5997 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5999 patchtess[patchtesscount].surface_id = i;
6000 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
6001 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
6002 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
6003 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
6004 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
6005 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
6006 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
6009 case Q3FACETYPE_FLARE:
6010 if (developer_extra.integer)
6011 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
6015 out->num_vertices = numvertices;
6016 out->num_triangles = numtriangles;
6017 meshvertices += out->num_vertices;
6018 meshtriangles += out->num_triangles;
6021 // Fix patches tesselations so that they make no seams
6025 for(i = 0; i < patchtesscount; ++i)
6027 for(j = i+1; j < patchtesscount; ++j)
6029 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
6032 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
6039 // Calculate resulting number of triangles
6040 collisionvertices = 0;
6041 collisiontriangles = 0;
6042 for(i = 0; i < patchtesscount; ++i)
6044 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
6045 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
6046 numvertices = finalwidth * finalheight;
6047 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6049 oldout[patchtess[i].surface_id].num_vertices = numvertices;
6050 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
6051 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
6052 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
6054 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
6055 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
6056 numvertices = finalwidth * finalheight;
6057 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6059 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
6060 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
6061 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
6062 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
6068 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
6069 if (collisiontriangles)
6071 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6072 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6076 collisionvertices = 0;
6077 collisiontriangles = 0;
6078 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6080 if (out->num_vertices < 3 || out->num_triangles < 1)
6083 type = LittleLong(in->type);
6084 firstvertex = LittleLong(in->firstvertex);
6085 firstelement = LittleLong(in->firstelement);
6086 out->num_firstvertex = meshvertices;
6087 out->num_firsttriangle = meshtriangles;
6088 out->num_firstcollisiontriangle = collisiontriangles;
6091 case Q3FACETYPE_FLAT:
6092 case Q3FACETYPE_MESH:
6093 // no processing necessary, except for lightmap merging
6094 for (j = 0;j < out->num_vertices;j++)
6096 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6097 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6098 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6099 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6100 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6101 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6102 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6103 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6104 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6105 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6106 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6107 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6108 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6109 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6111 for (j = 0;j < out->num_triangles*3;j++)
6112 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6114 case Q3FACETYPE_PATCH:
6115 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6116 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6117 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6118 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6119 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6120 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6121 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6123 xtess = ytess = cxtess = cytess = -1;
6124 for(j = 0; j < patchtesscount; ++j)
6125 if(patchtess[j].surface_id == i)
6127 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6128 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6129 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6130 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6135 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
6136 xtess = ytess = cxtess = cytess = 0;
6139 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6140 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6141 finalvertices = finalwidth * finalheight;
6142 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6143 type = Q3FACETYPE_MESH;
6144 // generate geometry
6145 // (note: normals are skipped because they get recalculated)
6146 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6147 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6148 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6149 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6150 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6151 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6153 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);
6155 if (developer_extra.integer)
6157 if (out->num_triangles < finaltriangles)
6158 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);
6160 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);
6162 // q3map does not put in collision brushes for curves... ugh
6163 // build the lower quality collision geometry
6164 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6165 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6166 finalvertices = finalwidth * finalheight;
6167 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6169 // legacy collision geometry implementation
6170 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
6171 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
6172 out->num_collisionvertices = finalvertices;
6173 out->num_collisiontriangles = finaltriangles;
6174 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6175 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
6177 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
6178 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
6180 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
6182 // now optimize the collision mesh by finding triangle bboxes...
6183 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
6184 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);
6186 // store collision geometry for BIH collision tree
6187 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6188 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6189 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6190 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6191 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6193 // remove this once the legacy code is removed
6195 int nc = out->num_collisiontriangles;
6197 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6199 if(nc != out->num_collisiontriangles)
6201 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
6206 if (developer_extra.integer)
6207 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);
6209 collisionvertices += finalvertices;
6210 collisiontriangles += out->num_collisiontriangles;
6215 meshvertices += out->num_vertices;
6216 meshtriangles += out->num_triangles;
6217 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6218 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)
6220 if (invalidelements)
6222 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);
6223 for (j = 0;j < out->num_triangles * 3;j++)
6225 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6226 if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
6227 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6231 // calculate a bounding box
6232 VectorClear(out->mins);
6233 VectorClear(out->maxs);
6234 if (out->num_vertices)
6236 if (cls.state != ca_dedicated && out->lightmaptexture)
6238 // figure out which part of the merged lightmap this fits into
6239 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6240 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6241 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6242 lightmapindex &= mergewidth * mergeheight - 1;
6243 lightmaptcscale[0] = 1.0f / mergewidth;
6244 lightmaptcscale[1] = 1.0f / mergeheight;
6245 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6246 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6247 // modify the lightmap texcoords to match this region of the merged lightmap
6248 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6250 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6251 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6254 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6255 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6256 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6258 out->mins[0] = min(out->mins[0], v[0]);
6259 out->maxs[0] = max(out->maxs[0], v[0]);
6260 out->mins[1] = min(out->mins[1], v[1]);
6261 out->maxs[1] = max(out->maxs[1], v[1]);
6262 out->mins[2] = min(out->mins[2], v[2]);
6263 out->maxs[2] = max(out->maxs[2], v[2]);
6265 out->mins[0] -= 1.0f;
6266 out->mins[1] -= 1.0f;
6267 out->mins[2] -= 1.0f;
6268 out->maxs[0] += 1.0f;
6269 out->maxs[1] += 1.0f;
6270 out->maxs[2] += 1.0f;
6272 // set lightmap styles for consistency with q1bsp
6273 //out->lightmapinfo->styles[0] = 0;
6274 //out->lightmapinfo->styles[1] = 255;
6275 //out->lightmapinfo->styles[2] = 255;
6276 //out->lightmapinfo->styles[3] = 255;
6281 for (;i < count;i++, out++)
6283 if(out->num_vertices && out->num_triangles)
6285 if(out->num_vertices == 0)
6287 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6288 if(out->num_triangles == 0)
6289 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6291 else if(out->num_triangles == 0)
6292 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)",
6293 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6294 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6295 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6298 // for per pixel lighting
6299 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);
6301 // generate ushort elements array if possible
6302 if (loadmodel->surfmesh.data_element3s)
6303 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6304 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6306 // free the no longer needed vertex data
6307 loadmodel->brushq3.num_vertices = 0;
6308 if (loadmodel->brushq3.data_vertex3f)
6309 Mem_Free(loadmodel->brushq3.data_vertex3f);
6310 loadmodel->brushq3.data_vertex3f = NULL;
6311 loadmodel->brushq3.data_normal3f = NULL;
6312 loadmodel->brushq3.data_texcoordtexture2f = NULL;
6313 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6314 loadmodel->brushq3.data_color4f = NULL;
6315 // free the no longer needed triangle data
6316 loadmodel->brushq3.num_triangles = 0;
6317 if (loadmodel->brushq3.data_element3i)
6318 Mem_Free(loadmodel->brushq3.data_element3i);
6319 loadmodel->brushq3.data_element3i = NULL;
6322 Mem_Free(patchtess);
6325 static void Mod_Q3BSP_LoadModels(lump_t *l)
6329 int i, j, n, c, count;
6331 in = (q3dmodel_t *)(mod_base + l->fileofs);
6332 if (l->filelen % sizeof(*in))
6333 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6334 count = l->filelen / sizeof(*in);
6335 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6337 loadmodel->brushq3.data_models = out;
6338 loadmodel->brushq3.num_models = count;
6340 for (i = 0;i < count;i++, in++, out++)
6342 for (j = 0;j < 3;j++)
6344 out->mins[j] = LittleFloat(in->mins[j]);
6345 out->maxs[j] = LittleFloat(in->maxs[j]);
6347 n = LittleLong(in->firstface);
6348 c = LittleLong(in->numfaces);
6349 if (n < 0 || n + c > loadmodel->num_surfaces)
6350 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6353 n = LittleLong(in->firstbrush);
6354 c = LittleLong(in->numbrushes);
6355 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6356 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6357 out->firstbrush = n;
6358 out->numbrushes = c;
6362 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6368 in = (int *)(mod_base + l->fileofs);
6369 if (l->filelen % sizeof(*in))
6370 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6371 count = l->filelen / sizeof(*in);
6372 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6374 loadmodel->brush.data_leafbrushes = out;
6375 loadmodel->brush.num_leafbrushes = count;
6377 for (i = 0;i < count;i++, in++, out++)
6379 n = LittleLong(*in);
6380 if (n < 0 || n >= loadmodel->brush.num_brushes)
6381 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6386 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6392 in = (int *)(mod_base + l->fileofs);
6393 if (l->filelen % sizeof(*in))
6394 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6395 count = l->filelen / sizeof(*in);
6396 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6398 loadmodel->brush.data_leafsurfaces = out;
6399 loadmodel->brush.num_leafsurfaces = count;
6401 for (i = 0;i < count;i++, in++, out++)
6403 n = LittleLong(*in);
6404 if (n < 0 || n >= loadmodel->num_surfaces)
6405 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6410 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6414 int i, j, n, c, count;
6416 in = (q3dleaf_t *)(mod_base + l->fileofs);
6417 if (l->filelen % sizeof(*in))
6418 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6419 count = l->filelen / sizeof(*in);
6420 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6422 loadmodel->brush.data_leafs = out;
6423 loadmodel->brush.num_leafs = count;
6425 for (i = 0;i < count;i++, in++, out++)
6429 out->clusterindex = LittleLong(in->clusterindex);
6430 out->areaindex = LittleLong(in->areaindex);
6431 for (j = 0;j < 3;j++)
6433 // yes the mins/maxs are ints
6434 out->mins[j] = LittleLong(in->mins[j]) - 1;
6435 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6437 n = LittleLong(in->firstleafface);
6438 c = LittleLong(in->numleaffaces);
6439 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6440 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6441 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6442 out->numleafsurfaces = c;
6443 n = LittleLong(in->firstleafbrush);
6444 c = LittleLong(in->numleafbrushes);
6445 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6446 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6447 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6448 out->numleafbrushes = c;
6452 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6458 in = (q3dnode_t *)(mod_base + l->fileofs);
6459 if (l->filelen % sizeof(*in))
6460 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6461 count = l->filelen / sizeof(*in);
6463 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6464 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6466 loadmodel->brush.data_nodes = out;
6467 loadmodel->brush.num_nodes = count;
6469 for (i = 0;i < count;i++, in++, out++)
6472 n = LittleLong(in->planeindex);
6473 if (n < 0 || n >= loadmodel->brush.num_planes)
6474 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6475 out->plane = loadmodel->brush.data_planes + n;
6476 for (j = 0;j < 2;j++)
6478 n = LittleLong(in->childrenindex[j]);
6481 if (n >= loadmodel->brush.num_nodes)
6482 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6483 out->children[j] = loadmodel->brush.data_nodes + n;
6488 if (n >= loadmodel->brush.num_leafs)
6489 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6490 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6493 for (j = 0;j < 3;j++)
6495 // yes the mins/maxs are ints
6496 out->mins[j] = LittleLong(in->mins[j]) - 1;
6497 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6501 // set the parent pointers
6502 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6505 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6508 q3dlightgrid_t *out;
6512 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6513 if (l->filelen % sizeof(*in))
6514 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6515 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6516 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6517 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6518 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6519 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6520 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6521 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6522 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6523 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6524 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6525 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6526 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6527 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6528 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]);
6529 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]);
6531 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6534 if (l->filelen < count * (int)sizeof(*in))
6536 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]);
6537 return; // ignore the grid if we cannot understand it
6539 if (l->filelen != count * (int)sizeof(*in))
6540 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
6541 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6542 loadmodel->brushq3.data_lightgrid = out;
6543 loadmodel->brushq3.num_lightgrid = count;
6544 // no swapping or validation necessary
6545 memcpy(out, in, count * (int)sizeof(*out));
6547 if(mod_q3bsp_sRGBlightmaps.integer)
6549 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6551 // we fix the brightness consistently via lightmapscale
6555 for(i = 0; i < count; ++i)
6557 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6558 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6559 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6560 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6561 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6562 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6568 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6570 for(i = 0; i < count; ++i)
6572 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6573 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6574 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6575 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6576 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6577 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6588 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6593 if (l->filelen == 0)
6596 // unvised maps often have cluster indices even without pvs, so check
6597 // leafs to find real number of clusters
6598 loadmodel->brush.num_pvsclusters = 1;
6599 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6600 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6603 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6604 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6605 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6606 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6610 in = (q3dpvs_t *)(mod_base + l->fileofs);
6612 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6614 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6615 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6616 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6617 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6618 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6619 if (l->filelen < totalchains + (int)sizeof(*in))
6620 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);
6622 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6623 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6626 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6628 int i, j, k, index[3];
6629 float transformed[3], blend1, blend2, blend, stylescale = 1;
6630 q3dlightgrid_t *a, *s;
6632 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6633 switch(vid.renderpath)
6635 case RENDERPATH_GL20:
6636 case RENDERPATH_D3D9:
6637 case RENDERPATH_D3D10:
6638 case RENDERPATH_D3D11:
6639 case RENDERPATH_SOFT:
6640 case RENDERPATH_GLES2:
6641 // LordHavoc: FIXME: is this true?
6642 stylescale = 1; // added while render
6644 case RENDERPATH_GL11:
6645 case RENDERPATH_GL13:
6646 case RENDERPATH_GLES1:
6647 stylescale = r_refdef.scene.rtlightstylevalue[0];
6651 if (!model->brushq3.num_lightgrid)
6653 ambientcolor[0] = stylescale;
6654 ambientcolor[1] = stylescale;
6655 ambientcolor[2] = stylescale;
6659 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6660 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6661 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6662 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6663 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6664 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6665 index[0] = (int)floor(transformed[0]);
6666 index[1] = (int)floor(transformed[1]);
6667 index[2] = (int)floor(transformed[2]);
6668 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6670 // now lerp the values
6671 VectorClear(diffusenormal);
6672 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6673 for (k = 0;k < 2;k++)
6675 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6676 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6678 for (j = 0;j < 2;j++)
6680 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6681 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6683 for (i = 0;i < 2;i++)
6685 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6686 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6688 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6689 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6690 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6691 // this uses the mod_md3_sin table because the values are
6692 // already in the 0-255 range, the 64+ bias fetches a cosine
6693 // instead of a sine value
6694 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6695 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6696 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6697 //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)));
6702 // normalize the light direction before turning
6703 VectorNormalize(diffusenormal);
6704 //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]);
6707 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6710 double midf, mid[3];
6716 // find the point distances
6717 mplane_t *plane = node->plane;
6718 if (plane->type < 3)
6720 t1 = p1[plane->type] - plane->dist;
6721 t2 = p2[plane->type] - plane->dist;
6725 t1 = DotProduct (plane->normal, p1) - plane->dist;
6726 t2 = DotProduct (plane->normal, p2) - plane->dist;
6733 node = node->children[1];
6742 node = node->children[0];
6748 midf = t1 / (t1 - t2);
6749 VectorLerp(p1, midf, p2, mid);
6751 // recurse both sides, front side first
6752 // return 2 if empty is followed by solid (hit something)
6753 // do not return 2 if both are solid or both empty,
6754 // or if start is solid and end is empty
6755 // as these degenerate cases usually indicate the eye is in solid and
6756 // should see the target point anyway
6757 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6760 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6765 return ((mleaf_t *)node)->clusterindex < 0;
6768 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6770 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6773 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6774 return trace.fraction == 1;
6778 double tracestart[3], traceend[3];
6779 VectorCopy(start, tracestart);
6780 VectorCopy(end, traceend);
6781 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6785 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)
6788 const bih_leaf_t *leaf;
6789 const bih_node_t *node;
6790 const colbrushf_t *brush;
6793 int nodestackpos = 0;
6794 int nodestack[1024];
6796 memset(trace, 0, sizeof(*trace));
6797 trace->fraction = 1;
6798 trace->hitsupercontentsmask = hitsupercontentsmask;
6800 bih = &model->collision_bih;
6804 nodenum = bih->rootnode;
6805 nodestack[nodestackpos++] = nodenum;
6806 while (nodestackpos)
6808 nodenum = nodestack[--nodestackpos];
6809 node = bih->nodes + nodenum;
6811 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6814 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6816 axis = node->type - BIH_SPLITX;
6817 if (start[axis] >= node->frontmin)
6818 nodestack[nodestackpos++] = node->front;
6819 if (start[axis] <= node->backmax)
6820 nodestack[nodestackpos++] = node->back;
6822 else if (node->type == BIH_UNORDERED)
6824 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6826 leaf = bih->leafs + node->children[axis];
6828 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6834 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6835 Collision_TracePointBrushFloat(trace, start, brush);
6837 case BIH_COLLISIONTRIANGLE:
6838 // collision triangle - skipped because they have no volume
6840 case BIH_RENDERTRIANGLE:
6841 // render triangle - skipped because they have no volume
6849 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)
6851 const bih_leaf_t *leaf;
6852 const bih_node_t *node;
6853 const colbrushf_t *brush;
6855 const texture_t *texture;
6856 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6857 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6858 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6863 if (VectorCompare(start, end))
6865 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6869 nodenum = bih->rootnode;
6871 memset(trace, 0, sizeof(*trace));
6872 trace->fraction = 1;
6873 trace->hitsupercontentsmask = hitsupercontentsmask;
6876 nodestackline[nodestackpos][0] = start[0];
6877 nodestackline[nodestackpos][1] = start[1];
6878 nodestackline[nodestackpos][2] = start[2];
6879 nodestackline[nodestackpos][3] = end[0];
6880 nodestackline[nodestackpos][4] = end[1];
6881 nodestackline[nodestackpos][5] = end[2];
6882 nodestack[nodestackpos++] = nodenum;
6883 while (nodestackpos)
6885 nodenum = nodestack[--nodestackpos];
6886 node = bih->nodes + nodenum;
6887 VectorCopy(nodestackline[nodestackpos], nodestart);
6888 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6889 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6890 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6891 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6892 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6893 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6894 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6895 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6897 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6899 // recurse children of the split
6900 axis = node->type - BIH_SPLITX;
6901 d1 = node->backmax - nodestart[axis];
6902 d2 = node->backmax - nodeend[axis];
6903 d3 = nodestart[axis] - node->frontmin;
6904 d4 = nodeend[axis] - node->frontmin;
6905 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6907 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;
6908 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;
6909 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;
6910 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6911 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;
6912 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;
6913 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;
6914 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6915 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;
6916 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;
6917 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;
6918 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6919 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6920 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6921 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6922 case 15: /* <<<< */ break;
6925 else if (node->type == BIH_UNORDERED)
6927 // calculate sweep bounds for this node
6928 // copy node bounds into local variables
6929 VectorCopy(node->mins, nodebigmins);
6930 VectorCopy(node->maxs, nodebigmaxs);
6931 // clip line to this node bounds
6932 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); }
6933 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); }
6934 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); }
6935 // some of the line intersected the enlarged node box
6936 // calculate sweep bounds for this node
6937 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6938 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6939 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6940 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6941 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6942 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6943 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6945 leaf = bih->leafs + node->children[axis];
6946 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6951 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6952 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6954 case BIH_COLLISIONTRIANGLE:
6955 if (!mod_q3bsp_curves_collisions.integer)
6957 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6958 texture = model->data_textures + leaf->textureindex;
6959 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);
6961 case BIH_RENDERTRIANGLE:
6962 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6963 texture = model->data_textures + leaf->textureindex;
6964 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);
6972 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)
6974 if (VectorCompare(start, end))
6976 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6979 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6982 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)
6985 const bih_leaf_t *leaf;
6986 const bih_node_t *node;
6987 const colbrushf_t *brush;
6989 const texture_t *texture;
6990 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6991 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6992 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6993 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6995 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6997 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6998 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
7000 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
7004 bih = &model->collision_bih;
7007 nodenum = bih->rootnode;
7009 // box trace, performed as brush trace
7010 memset(trace, 0, sizeof(*trace));
7011 trace->fraction = 1;
7012 trace->hitsupercontentsmask = hitsupercontentsmask;
7014 // calculate tracebox-like parameters for efficient culling
7015 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
7016 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
7017 VectorSubtract(thisbrush_start->mins, start, startmins);
7018 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
7019 VectorSubtract(thisbrush_end->mins, end, endmins);
7020 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7021 mins[0] = min(startmins[0], endmins[0]);
7022 mins[1] = min(startmins[1], endmins[1]);
7023 mins[2] = min(startmins[2], endmins[2]);
7024 maxs[0] = max(startmaxs[0], endmaxs[0]);
7025 maxs[1] = max(startmaxs[1], endmaxs[1]);
7026 maxs[2] = max(startmaxs[2], endmaxs[2]);
7029 nodestackline[nodestackpos][0] = start[0];
7030 nodestackline[nodestackpos][1] = start[1];
7031 nodestackline[nodestackpos][2] = start[2];
7032 nodestackline[nodestackpos][3] = end[0];
7033 nodestackline[nodestackpos][4] = end[1];
7034 nodestackline[nodestackpos][5] = end[2];
7035 nodestack[nodestackpos++] = nodenum;
7036 while (nodestackpos)
7038 nodenum = nodestack[--nodestackpos];
7039 node = bih->nodes + nodenum;
7040 VectorCopy(nodestackline[nodestackpos], nodestart);
7041 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7042 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7043 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7044 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7045 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7046 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7047 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7048 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7050 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7052 // recurse children of the split
7053 axis = node->type - BIH_SPLITX;
7054 d1 = node->backmax - nodestart[axis] - mins[axis];
7055 d2 = node->backmax - nodeend[axis] - mins[axis];
7056 d3 = nodestart[axis] - node->frontmin + maxs[axis];
7057 d4 = nodeend[axis] - node->frontmin + maxs[axis];
7058 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7060 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;
7061 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;
7062 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;
7063 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7064 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;
7065 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;
7066 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;
7067 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7068 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;
7069 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;
7070 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;
7071 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7072 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7073 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7074 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7075 case 15: /* <<<< */ break;
7078 else if (node->type == BIH_UNORDERED)
7080 // calculate sweep bounds for this node
7081 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7082 VectorSubtract(node->mins, maxs, nodebigmins);
7083 VectorSubtract(node->maxs, mins, nodebigmaxs);
7084 // clip line to this node bounds
7085 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); }
7086 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); }
7087 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); }
7088 // some of the line intersected the enlarged node box
7089 // calculate sweep bounds for this node
7090 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7091 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7092 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7093 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7094 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7095 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7096 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7098 leaf = bih->leafs + node->children[axis];
7099 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7104 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7105 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7107 case BIH_COLLISIONTRIANGLE:
7108 if (!mod_q3bsp_curves_collisions.integer)
7110 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7111 texture = model->data_textures + leaf->textureindex;
7112 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);
7114 case BIH_RENDERTRIANGLE:
7115 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7116 texture = model->data_textures + leaf->textureindex;
7117 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);
7125 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)
7127 colboxbrushf_t thisbrush_start, thisbrush_end;
7128 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7130 // box trace, performed as brush trace
7131 VectorAdd(start, boxmins, boxstartmins);
7132 VectorAdd(start, boxmaxs, boxstartmaxs);
7133 VectorAdd(end, boxmins, boxendmins);
7134 VectorAdd(end, boxmaxs, boxendmaxs);
7135 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7136 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7137 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
7141 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7144 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
7145 return trace.startsupercontents;
7148 qboolean Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
7151 Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
7152 return trace.fraction == 1;
7155 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)
7158 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7160 int hitsupercontents;
7161 VectorSet(end, start[0], start[1], model->normalmins[2]);
7163 memset(trace, 0, sizeof(*trace));
7164 trace->fraction = 1;
7165 trace->hitsupercontentsmask = hitsupercontentsmask;
7167 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
7168 hitsupercontents = trace->hitsupercontents;
7169 memset(trace, 0, sizeof(*trace));
7170 trace->fraction = 1;
7171 trace->hitsupercontentsmask = hitsupercontentsmask;
7172 trace->startsupercontents = hitsupercontents;
7176 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7179 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7182 VectorSet(end, start[0], start[1], model->normalmins[2]);
7183 memset(&trace, 0, sizeof(trace));
7185 trace.hitsupercontentsmask = 0;
7186 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
7187 return trace.hitsupercontents;
7193 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
7198 // find which leaf the point is in
7200 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7201 // point trace the brushes
7202 leaf = (mleaf_t *)node;
7203 for (i = 0;i < leaf->numleafbrushes;i++)
7205 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7206 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
7208 brush->markframe = markframe;
7209 Collision_TracePointBrushFloat(trace, point, brush);
7212 // can't do point traces on curves (they have no thickness)
7215 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)
7217 int i, startside, endside;
7218 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
7220 msurface_t *surface;
7223 // walk the tree until we hit a leaf, recursing for any split cases
7227 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7229 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7230 node = node->children[1];
7232 // abort if this part of the bsp tree can not be hit by this trace
7233 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7235 plane = node->plane;
7236 // axial planes are much more common than non-axial, so an optimized
7237 // axial case pays off here
7238 if (plane->type < 3)
7240 dist1 = start[plane->type] - plane->dist;
7241 dist2 = end[plane->type] - plane->dist;
7245 dist1 = DotProduct(start, plane->normal) - plane->dist;
7246 dist2 = DotProduct(end, plane->normal) - plane->dist;
7248 startside = dist1 < 0;
7249 endside = dist2 < 0;
7250 if (startside == endside)
7252 // most of the time the line fragment is on one side of the plane
7253 node = node->children[startside];
7257 // line crosses node plane, split the line
7258 dist1 = PlaneDiff(linestart, plane);
7259 dist2 = PlaneDiff(lineend, plane);
7260 midfrac = dist1 / (dist1 - dist2);
7261 VectorLerp(linestart, midfrac, lineend, mid);
7262 // take the near side first
7263 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7264 // if we found an impact on the front side, don't waste time
7265 // exploring the far side
7266 if (midfrac <= trace->fraction)
7267 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7272 // abort if this part of the bsp tree can not be hit by this trace
7273 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7276 nodesegmentmins[0] = min(start[0], end[0]) - 1;
7277 nodesegmentmins[1] = min(start[1], end[1]) - 1;
7278 nodesegmentmins[2] = min(start[2], end[2]) - 1;
7279 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
7280 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
7281 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
7282 // line trace the brushes
7283 leaf = (mleaf_t *)node;
7285 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7288 for (i = 0;i < leaf->numleafbrushes;i++)
7290 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7291 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7293 brush->markframe = markframe;
7294 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
7297 // can't do point traces on curves (they have no thickness)
7298 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
7300 // line trace the curves
7301 for (i = 0;i < leaf->numleafsurfaces;i++)
7303 surface = model->data_surfaces + leaf->firstleafsurface[i];
7304 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7306 surface->deprecatedq3collisionmarkframe = markframe;
7307 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);
7313 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)
7319 msurface_t *surface;
7321 float nodesegmentmins[3], nodesegmentmaxs[3];
7322 // walk the tree until we hit a leaf, recursing for any split cases
7326 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7328 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7329 node = node->children[1];
7331 // abort if this part of the bsp tree can not be hit by this trace
7332 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7334 plane = node->plane;
7335 // axial planes are much more common than non-axial, so an optimized
7336 // axial case pays off here
7337 if (plane->type < 3)
7339 // this is an axial plane, compare bounding box directly to it and
7340 // recurse sides accordingly
7341 // recurse down node sides
7342 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
7343 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
7344 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
7345 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
7349 // this is a non-axial plane, so check if the start and end boxes
7350 // are both on one side of the plane to handle 'diagonal' cases
7351 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
7355 // segment crosses plane
7356 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7359 // if sides == 0 then the trace itself is bogus (Not A Number values),
7360 // in this case we simply pretend the trace hit nothing
7362 return; // ERROR: NAN bounding box!
7363 // take whichever side the segment box is on
7364 node = node->children[sides - 1];
7367 // abort if this part of the bsp tree can not be hit by this trace
7368 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7370 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
7371 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
7372 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
7373 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
7374 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
7375 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
7377 leaf = (mleaf_t *)node;
7379 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7382 for (i = 0;i < leaf->numleafbrushes;i++)
7384 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7385 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7387 brush->markframe = markframe;
7388 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7391 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
7393 for (i = 0;i < leaf->numleafsurfaces;i++)
7395 surface = model->data_surfaces + leaf->firstleafsurface[i];
7396 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7398 surface->deprecatedq3collisionmarkframe = markframe;
7399 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);
7406 static int markframe = 0;
7408 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)
7412 memset(trace, 0, sizeof(*trace));
7413 trace->fraction = 1;
7414 trace->hitsupercontentsmask = hitsupercontentsmask;
7415 if (mod_collision_bih.integer)
7416 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
7417 else if (model->brush.submodel)
7419 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7420 if (brush->colbrushf)
7421 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
7424 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
7427 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)
7430 float segmentmins[3], segmentmaxs[3];
7431 msurface_t *surface;
7434 if (VectorCompare(start, end))
7436 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
7440 memset(trace, 0, sizeof(*trace));
7441 trace->fraction = 1;
7442 trace->hitsupercontentsmask = hitsupercontentsmask;
7443 segmentmins[0] = min(start[0], end[0]) - 1;
7444 segmentmins[1] = min(start[1], end[1]) - 1;
7445 segmentmins[2] = min(start[2], end[2]) - 1;
7446 segmentmaxs[0] = max(start[0], end[0]) + 1;
7447 segmentmaxs[1] = max(start[1], end[1]) + 1;
7448 segmentmaxs[2] = max(start[2], end[2]) + 1;
7449 if (mod_collision_bih.integer)
7450 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
7451 else if (model->brush.submodel)
7453 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7454 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7455 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7456 if (mod_q3bsp_curves_collisions.integer)
7457 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7458 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7459 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);
7462 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
7465 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)
7467 float segmentmins[3], segmentmaxs[3];
7469 msurface_t *surface;
7472 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
7474 if (VectorCompare(start->mins, end->mins))
7475 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
7477 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
7481 // box trace, performed as brush trace
7482 memset(trace, 0, sizeof(*trace));
7483 trace->fraction = 1;
7484 trace->hitsupercontentsmask = hitsupercontentsmask;
7485 segmentmins[0] = min(start->mins[0], end->mins[0]) - 1;
7486 segmentmins[1] = min(start->mins[1], end->mins[1]) - 1;
7487 segmentmins[2] = min(start->mins[2], end->mins[2]) - 1;
7488 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]) + 1;
7489 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]) + 1;
7490 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]) + 1;
7491 if (mod_collision_bih.integer)
7492 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
7493 else if (model->brush.submodel)
7495 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7496 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7497 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7498 if (mod_q3bsp_curves_collisions.integer)
7499 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7500 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7501 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);
7504 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
7507 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)
7509 colboxbrushf_t thisbrush_start, thisbrush_end;
7510 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7512 // box trace, performed as brush trace
7513 VectorAdd(start, boxmins, boxstartmins);
7514 VectorAdd(start, boxmaxs, boxstartmaxs);
7515 VectorAdd(end, boxmins, boxendmins);
7516 VectorAdd(end, boxmaxs, boxendmaxs);
7517 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7518 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7519 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
7522 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7525 int supercontents = 0;
7527 if (mod_collision_bih.integer)
7529 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
7531 // test if the point is inside each brush
7532 else if (model->brush.submodel)
7534 // submodels are effectively one leaf
7535 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7536 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7537 supercontents |= brush->colbrushf->supercontents;
7541 mnode_t *node = model->brush.data_nodes;
7543 // find which leaf the point is in
7545 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7546 leaf = (mleaf_t *)node;
7547 // now check the brushes in the leaf
7548 for (i = 0;i < leaf->numleafbrushes;i++)
7550 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
7551 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7552 supercontents |= brush->colbrushf->supercontents;
7555 return supercontents;
7558 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)
7560 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
7564 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
7572 int nummodelbrushes = model->nummodelbrushes;
7573 int nummodelsurfaces = model->nummodelsurfaces;
7575 const int *collisionelement3i;
7576 const float *collisionvertex3f;
7577 const int *renderelement3i;
7578 const float *rendervertex3f;
7579 bih_leaf_t *bihleafs;
7580 bih_node_t *bihnodes;
7582 int *temp_leafsortscratch;
7583 const msurface_t *surface;
7584 const q3mbrush_t *brush;
7586 // find out how many BIH leaf nodes we need
7588 if (userendersurfaces)
7590 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7591 bihnumleafs += surface->num_triangles;
7595 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7596 if (brush->colbrushf)
7598 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7600 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7601 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7603 bihnumleafs += surface->num_collisiontriangles;
7610 // allocate the memory for the BIH leaf nodes
7611 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7613 // now populate the BIH leaf nodes
7616 // add render surfaces
7617 renderelement3i = model->surfmesh.data_element3i;
7618 rendervertex3f = model->surfmesh.data_vertex3f;
7619 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7621 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7623 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7625 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7626 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7627 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7628 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7629 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7630 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7631 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7632 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7633 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7634 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7639 if (!userendersurfaces)
7641 // add collision brushes
7642 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7644 if (!brush->colbrushf)
7646 bihleafs[bihleafindex].type = BIH_BRUSH;
7647 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7648 bihleafs[bihleafindex].surfaceindex = -1;
7649 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7650 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7651 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7655 // add collision surfaces
7656 collisionelement3i = model->brush.data_collisionelement3i;
7657 collisionvertex3f = model->brush.data_collisionvertex3f;
7658 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7660 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7662 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7663 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7664 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7665 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7666 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7667 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7668 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7669 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7670 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7671 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7677 // allocate buffers for the produced and temporary data
7678 bihmaxnodes = bihnumleafs + 1;
7679 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7680 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7681 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7684 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7686 // we're done with the temporary data
7687 Mem_Free(temp_leafsort);
7689 // resize the BIH nodes array if it over-allocated
7690 if (out->maxnodes > out->numnodes)
7692 out->maxnodes = out->numnodes;
7693 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7699 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7701 int supercontents = 0;
7702 if (nativecontents & CONTENTSQ3_SOLID)
7703 supercontents |= SUPERCONTENTS_SOLID;
7704 if (nativecontents & CONTENTSQ3_WATER)
7705 supercontents |= SUPERCONTENTS_WATER;
7706 if (nativecontents & CONTENTSQ3_SLIME)
7707 supercontents |= SUPERCONTENTS_SLIME;
7708 if (nativecontents & CONTENTSQ3_LAVA)
7709 supercontents |= SUPERCONTENTS_LAVA;
7710 if (nativecontents & CONTENTSQ3_BODY)
7711 supercontents |= SUPERCONTENTS_BODY;
7712 if (nativecontents & CONTENTSQ3_CORPSE)
7713 supercontents |= SUPERCONTENTS_CORPSE;
7714 if (nativecontents & CONTENTSQ3_NODROP)
7715 supercontents |= SUPERCONTENTS_NODROP;
7716 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7717 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7718 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7719 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7720 if (nativecontents & CONTENTSQ3_DONOTENTER)
7721 supercontents |= SUPERCONTENTS_DONOTENTER;
7722 if (nativecontents & CONTENTSQ3_BOTCLIP)
7723 supercontents |= SUPERCONTENTS_BOTCLIP;
7724 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7725 supercontents |= SUPERCONTENTS_OPAQUE;
7726 return supercontents;
7729 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7731 int nativecontents = 0;
7732 if (supercontents & SUPERCONTENTS_SOLID)
7733 nativecontents |= CONTENTSQ3_SOLID;
7734 if (supercontents & SUPERCONTENTS_WATER)
7735 nativecontents |= CONTENTSQ3_WATER;
7736 if (supercontents & SUPERCONTENTS_SLIME)
7737 nativecontents |= CONTENTSQ3_SLIME;
7738 if (supercontents & SUPERCONTENTS_LAVA)
7739 nativecontents |= CONTENTSQ3_LAVA;
7740 if (supercontents & SUPERCONTENTS_BODY)
7741 nativecontents |= CONTENTSQ3_BODY;
7742 if (supercontents & SUPERCONTENTS_CORPSE)
7743 nativecontents |= CONTENTSQ3_CORPSE;
7744 if (supercontents & SUPERCONTENTS_NODROP)
7745 nativecontents |= CONTENTSQ3_NODROP;
7746 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7747 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7748 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7749 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7750 if (supercontents & SUPERCONTENTS_DONOTENTER)
7751 nativecontents |= CONTENTSQ3_DONOTENTER;
7752 if (supercontents & SUPERCONTENTS_BOTCLIP)
7753 nativecontents |= CONTENTSQ3_BOTCLIP;
7754 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7755 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7756 return nativecontents;
7759 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7764 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7765 node = node->children[1];
7767 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7768 if (loadmodel->brush.num_leafs < numleafs)
7769 loadmodel->brush.num_leafs = numleafs;
7772 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7775 q3dheader_t *header;
7776 float corner[3], yawradius, modelradius;
7778 mod->modeldatatypestring = "Q3BSP";
7780 mod->type = mod_brushq3;
7781 mod->brush.ishlbsp = false;
7782 mod->brush.isbsp2rmqe = false;
7783 mod->brush.isbsp2 = false;
7784 mod->brush.isq2bsp = false;
7785 mod->brush.isq3bsp = true;
7786 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7789 header = (q3dheader_t *)buffer;
7790 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7791 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7793 i = LittleLong(header->version);
7794 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7795 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7797 mod->soundfromcenter = true;
7798 mod->TraceBox = Mod_Q3BSP_TraceBox;
7799 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7800 mod->TraceLine = Mod_Q3BSP_TraceLine;
7801 mod->TracePoint = Mod_Q3BSP_TracePoint;
7802 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7803 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7804 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7805 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7806 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7807 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7808 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7809 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7810 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7811 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7812 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7813 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7814 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7815 mod->brush.AmbientSoundLevelsForPoint = NULL;
7816 mod->brush.RoundUpToHullSize = NULL;
7817 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7818 mod->Draw = R_Q1BSP_Draw;
7819 mod->DrawDepth = R_Q1BSP_DrawDepth;
7820 mod->DrawDebug = R_Q1BSP_DrawDebug;
7821 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7822 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7823 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7824 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7825 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7826 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7827 mod->DrawLight = R_Q1BSP_DrawLight;
7829 mod_base = (unsigned char *)header;
7831 // swap all the lumps
7832 header->ident = LittleLong(header->ident);
7833 header->version = LittleLong(header->version);
7834 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7835 for (i = 0;i < lumps;i++)
7837 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7838 if((char *) bufferend < (char *) buffer + j)
7839 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7840 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7841 if((char *) bufferend < (char *) buffer + j)
7842 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7845 * NO, do NOT clear them!
7846 * they contain actual data referenced by other stuff.
7847 * Instead, before using the advertisements lump, check header->versio
7849 * Sorry, but otherwise it breaks memory of the first lump.
7850 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7852 header->lumps[i].fileofs = 0;
7853 header->lumps[i].filelen = 0;
7857 mod->brush.qw_md4sum = 0;
7858 mod->brush.qw_md4sum2 = 0;
7859 for (i = 0;i < lumps;i++)
7861 if (i == Q3LUMP_ENTITIES)
7863 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7864 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7866 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7868 // all this checksumming can take a while, so let's send keepalives here too
7869 CL_KeepaliveMessage(false);
7872 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7873 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7874 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7875 if (header->version == Q3BSPVERSION_IG)
7876 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7878 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7879 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7880 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7881 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7882 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7883 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7884 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7885 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7886 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7887 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7888 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7889 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7890 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7891 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7892 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7894 // the MakePortals code works fine on the q3bsp data as well
7895 if (mod_bsp_portalize.integer)
7896 Mod_Q1BSP_MakePortals();
7898 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7899 loadmodel->brush.supportwateralpha = true;
7901 // make a single combined shadow mesh to allow optimized shadow volume creation
7902 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7904 loadmodel->brush.num_leafs = 0;
7905 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7907 if (loadmodel->brush.numsubmodels)
7908 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7911 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7916 // duplicate the basic information
7917 dpsnprintf(name, sizeof(name), "*%i", i);
7918 mod = Mod_FindName(name, loadmodel->name);
7919 // copy the base model to this one
7921 // rename the clone back to its proper name
7922 strlcpy(mod->name, name, sizeof(mod->name));
7923 mod->brush.parentmodel = loadmodel;
7924 // textures and memory belong to the main model
7925 mod->texturepool = NULL;
7926 mod->mempool = NULL;
7927 mod->brush.GetPVS = NULL;
7928 mod->brush.FatPVS = NULL;
7929 mod->brush.BoxTouchingPVS = NULL;
7930 mod->brush.BoxTouchingLeafPVS = NULL;
7931 mod->brush.BoxTouchingVisibleLeafs = NULL;
7932 mod->brush.FindBoxClusters = NULL;
7933 mod->brush.LightPoint = NULL;
7934 mod->brush.AmbientSoundLevelsForPoint = NULL;
7936 mod->brush.submodel = i;
7937 if (loadmodel->brush.submodels)
7938 loadmodel->brush.submodels[i] = mod;
7940 // make the model surface list (used by shadowing/lighting)
7941 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7942 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7943 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7944 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7945 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7946 Mod_MakeSortedSurfaces(mod);
7948 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7949 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7950 // enlarge the bounding box to enclose all geometry of this model,
7951 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7952 // which can in turn mess up the farclip (as well as culling when
7953 // outside the level - an unimportant concern)
7955 //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]);
7956 for (j = 0;j < mod->nummodelsurfaces;j++)
7958 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7959 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7961 if (!surface->num_vertices)
7963 for (k = 0;k < surface->num_vertices;k++, v += 3)
7965 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7966 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7967 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7968 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7969 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7970 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7973 //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]);
7974 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7975 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7976 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7977 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7978 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7979 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7980 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7981 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7982 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7983 mod->yawmins[2] = mod->normalmins[2];
7984 mod->yawmaxs[2] = mod->normalmaxs[2];
7985 mod->radius = modelradius;
7986 mod->radius2 = modelradius * modelradius;
7988 // this gets altered below if sky or water is used
7989 mod->DrawSky = NULL;
7990 mod->DrawAddWaterPlanes = NULL;
7992 for (j = 0;j < mod->nummodelsurfaces;j++)
7993 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7995 if (j < mod->nummodelsurfaces)
7996 mod->DrawSky = R_Q1BSP_DrawSky;
7998 for (j = 0;j < mod->nummodelsurfaces;j++)
7999 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8001 if (j < mod->nummodelsurfaces)
8002 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8004 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
8005 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
8007 // generate VBOs and other shared data before cloning submodels
8012 if (mod_q3bsp_sRGBlightmaps.integer)
8014 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
8016 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
8017 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
8018 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
8019 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
8020 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
8022 else // if this is NOT set, regular rendering looks right by this requirement anyway
8025 // we want color 1 to do the same as without sRGB
8026 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
8027 loadmodel->lightmapscale *= 2.476923f; // fixes max level
8030 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
8031 // we need to undo that
8032 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
8036 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);
8039 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
8041 int i = LittleLong(((int *)buffer)[1]);
8042 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
8043 Mod_Q3BSP_Load(mod,buffer, bufferend);
8044 else if (i == Q2BSPVERSION)
8045 Mod_Q2BSP_Load(mod,buffer, bufferend);
8047 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
8050 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
8052 Host_Error("Mod_MAP_Load: not yet implemented");
8055 typedef struct objvertex_s
8066 static unsigned char nobsp_pvs[1] = {1};
8068 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
8070 const char *textbase = (char *)buffer, *text = textbase;
8074 char materialname[MAX_QPATH];
8075 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
8076 int index1, index2, index3;
8077 objvertex_t vfirst, vprev, vcurrent;
8080 int numtriangles = 0;
8081 int maxtriangles = 0;
8082 objvertex_t *vertices = NULL;
8084 int maxtextures = 0, numtextures = 0, textureindex = 0;
8085 int maxv = 0, numv = 1;
8086 int maxvt = 0, numvt = 1;
8087 int maxvn = 0, numvn = 1;
8088 char *texturenames = NULL;
8089 float dist, modelradius, modelyawradius, yawradius;
8090 float *obj_v = NULL;
8091 float *obj_vt = NULL;
8092 float *obj_vn = NULL;
8096 objvertex_t *thisvertex = NULL;
8097 int vertexhashindex;
8098 int *vertexhashtable = NULL;
8099 objvertex_t *vertexhashdata = NULL;
8100 objvertex_t *vdata = NULL;
8101 int vertexhashsize = 0;
8102 int vertexhashcount = 0;
8103 skinfile_t *skinfiles = NULL;
8104 unsigned char *data = NULL;
8105 int *submodelfirstsurface;
8106 msurface_t *tempsurface;
8107 msurface_t *tempsurfaces;
8109 memset(&vfirst, 0, sizeof(vfirst));
8110 memset(&vprev, 0, sizeof(vprev));
8111 memset(&vcurrent, 0, sizeof(vcurrent));
8113 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8115 loadmodel->modeldatatypestring = "OBJ";
8117 loadmodel->type = mod_obj;
8118 loadmodel->soundfromcenter = true;
8119 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
8120 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
8121 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
8122 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
8123 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8124 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
8125 loadmodel->brush.TraceLineOfSight = NULL;
8126 loadmodel->brush.SuperContentsFromNativeContents = NULL;
8127 loadmodel->brush.NativeContentsFromSuperContents = NULL;
8128 loadmodel->brush.GetPVS = NULL;
8129 loadmodel->brush.FatPVS = NULL;
8130 loadmodel->brush.BoxTouchingPVS = NULL;
8131 loadmodel->brush.BoxTouchingLeafPVS = NULL;
8132 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
8133 loadmodel->brush.FindBoxClusters = NULL;
8134 loadmodel->brush.LightPoint = NULL;
8135 loadmodel->brush.FindNonSolidLocation = NULL;
8136 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8137 loadmodel->brush.RoundUpToHullSize = NULL;
8138 loadmodel->brush.PointInLeaf = NULL;
8139 loadmodel->Draw = R_Q1BSP_Draw;
8140 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
8141 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
8142 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
8143 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
8144 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
8145 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
8146 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
8147 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
8148 loadmodel->DrawLight = R_Q1BSP_DrawLight;
8150 skinfiles = Mod_LoadSkinFiles();
8151 if (loadmodel->numskins < 1)
8152 loadmodel->numskins = 1;
8154 // make skinscenes for the skins (no groups)
8155 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8156 for (i = 0;i < loadmodel->numskins;i++)
8158 loadmodel->skinscenes[i].firstframe = i;
8159 loadmodel->skinscenes[i].framecount = 1;
8160 loadmodel->skinscenes[i].loop = true;
8161 loadmodel->skinscenes[i].framerate = 10;
8167 // we always have model 0, i.e. the first "submodel"
8168 loadmodel->brush.numsubmodels = 1;
8170 // parse the OBJ text now
8173 static char emptyarg[1] = "";
8178 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8179 line[linelen] = text[linelen];
8181 for (argc = 0;argc < 4;argc++)
8182 argv[argc] = emptyarg;
8185 while (*s == ' ' || *s == '\t')
8195 while (*s == ' ' || *s == '\t')
8205 if (argv[0][0] == '#')
8207 if (!strcmp(argv[0], "v"))
8211 maxv = max(maxv * 2, 1024);
8212 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
8214 if(mod_obj_orientation.integer)
8216 obj_v[numv*3+0] = atof(argv[1]);
8217 obj_v[numv*3+2] = atof(argv[2]);
8218 obj_v[numv*3+1] = atof(argv[3]);
8222 obj_v[numv*3+0] = atof(argv[1]);
8223 obj_v[numv*3+1] = atof(argv[2]);
8224 obj_v[numv*3+2] = atof(argv[3]);
8228 else if (!strcmp(argv[0], "vt"))
8232 maxvt = max(maxvt * 2, 1024);
8233 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
8235 obj_vt[numvt*2+0] = atof(argv[1]);
8236 obj_vt[numvt*2+1] = 1-atof(argv[2]);
8239 else if (!strcmp(argv[0], "vn"))
8243 maxvn = max(maxvn * 2, 1024);
8244 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
8246 if(mod_obj_orientation.integer)
8248 obj_vn[numvn*3+0] = atof(argv[1]);
8249 obj_vn[numvn*3+2] = atof(argv[2]);
8250 obj_vn[numvn*3+1] = atof(argv[3]);
8254 obj_vn[numvn*3+0] = atof(argv[1]);
8255 obj_vn[numvn*3+1] = atof(argv[2]);
8256 obj_vn[numvn*3+2] = atof(argv[3]);
8260 else if (!strcmp(argv[0], "f"))
8264 if (maxtextures <= numtextures)
8266 maxtextures = max(maxtextures * 2, 256);
8267 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8269 textureindex = numtextures++;
8270 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
8272 for (j = 1;j < argc;j++)
8274 index1 = atoi(argv[j]);
8275 while(argv[j][0] && argv[j][0] != '/')
8279 index2 = atoi(argv[j]);
8280 while(argv[j][0] && argv[j][0] != '/')
8284 index3 = atoi(argv[j]);
8285 // negative refers to a recent vertex
8286 // zero means not specified
8287 // positive means an absolute vertex index
8289 index1 = numv - index1;
8291 index2 = numvt - index2;
8293 index3 = numvn - index3;
8294 vcurrent.nextindex = -1;
8295 vcurrent.textureindex = textureindex;
8296 vcurrent.submodelindex = submodelindex;
8297 if (obj_v && index1 >= 0 && index1 < numv)
8298 VectorCopy(obj_v + 3*index1, vcurrent.v);
8299 if (obj_vt && index2 >= 0 && index2 < numvt)
8300 Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
8301 if (obj_vn && index3 >= 0 && index3 < numvn)
8302 VectorCopy(obj_vn + 3*index3, vcurrent.vn);
8303 if (numtriangles == 0)
8305 VectorCopy(vcurrent.v, mins);
8306 VectorCopy(vcurrent.v, maxs);
8310 mins[0] = min(mins[0], vcurrent.v[0]);
8311 mins[1] = min(mins[1], vcurrent.v[1]);
8312 mins[2] = min(mins[2], vcurrent.v[2]);
8313 maxs[0] = max(maxs[0], vcurrent.v[0]);
8314 maxs[1] = max(maxs[1], vcurrent.v[1]);
8315 maxs[2] = max(maxs[2], vcurrent.v[2]);
8321 if (maxtriangles <= numtriangles)
8323 maxtriangles = max(maxtriangles * 2, 32768);
8324 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8326 if(mod_obj_orientation.integer)
8328 vertices[numtriangles*3+0] = vfirst;
8329 vertices[numtriangles*3+1] = vprev;
8330 vertices[numtriangles*3+2] = vcurrent;
8334 vertices[numtriangles*3+0] = vfirst;
8335 vertices[numtriangles*3+2] = vprev;
8336 vertices[numtriangles*3+1] = vcurrent;
8343 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8345 submodelindex = atof(argv[1]);
8346 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8348 else if (!strcmp(argv[0], "usemtl"))
8350 for (i = 0;i < numtextures;i++)
8351 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8353 if (i < numtextures)
8357 if (maxtextures <= numtextures)
8359 maxtextures = max(maxtextures * 2, 256);
8360 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8362 textureindex = numtextures++;
8363 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8368 // now that we have the OBJ data loaded as-is, we can convert it
8370 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8371 VectorCopy(mins, loadmodel->normalmins);
8372 VectorCopy(maxs, loadmodel->normalmaxs);
8373 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8374 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8375 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8376 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8377 modelradius = modelyawradius + modelradius * modelradius;
8378 modelyawradius = sqrt(modelyawradius);
8379 modelradius = sqrt(modelradius);
8380 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8381 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8382 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8383 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8384 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8385 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8386 loadmodel->radius = modelradius;
8387 loadmodel->radius2 = modelradius * modelradius;
8389 // allocate storage for triangles
8390 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8391 // allocate vertex hash structures to build an optimal vertex subset
8392 vertexhashsize = numtriangles*2;
8393 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8394 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8395 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8396 vertexhashcount = 0;
8398 // gather surface stats for assigning vertex/triangle ranges
8402 loadmodel->num_surfaces = 0;
8403 // allocate storage for the worst case number of surfaces, later we resize
8404 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8405 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8406 tempsurface = tempsurfaces;
8407 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8409 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8410 for (textureindex = 0;textureindex < numtextures;textureindex++)
8412 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8414 thisvertex = vertices + vertexindex;
8415 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8418 // skip the surface creation if there are no triangles for it
8419 if (vertexindex == numtriangles*3)
8421 // create a surface for these vertices
8422 surfacevertices = 0;
8423 surfaceelements = 0;
8424 // we hack in a texture index in the surface to be fixed up later...
8425 tempsurface->texture = (texture_t *)((size_t)textureindex);
8426 // calculate bounds as we go
8427 VectorCopy(thisvertex->v, tempsurface->mins);
8428 VectorCopy(thisvertex->v, tempsurface->maxs);
8429 for (;vertexindex < numtriangles*3;vertexindex++)
8431 thisvertex = vertices + vertexindex;
8432 if (thisvertex->submodelindex != submodelindex)
8434 if (thisvertex->textureindex != textureindex)
8436 // add vertex to surface bounds
8437 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8438 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8439 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8440 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8441 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8442 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8443 // add the vertex if it is not found in the merged set, and
8444 // get its index (triangle element) for the surface
8445 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8446 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8448 vdata = vertexhashdata + i;
8449 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8454 i = vertexhashcount++;
8455 vdata = vertexhashdata + i;
8456 *vdata = *thisvertex;
8457 vdata->nextindex = vertexhashtable[vertexhashindex];
8458 vertexhashtable[vertexhashindex] = i;
8461 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8464 surfacetriangles = surfaceelements / 3;
8465 tempsurface->num_vertices = surfacevertices;
8466 tempsurface->num_triangles = surfacetriangles;
8467 tempsurface->num_firstvertex = firstvertex;
8468 tempsurface->num_firsttriangle = firsttriangle;
8469 firstvertex += tempsurface->num_vertices;
8470 firsttriangle += tempsurface->num_triangles;
8472 loadmodel->num_surfaces++;
8475 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8476 numvertices = firstvertex;
8477 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8478 tempsurfaces = NULL;
8480 // allocate storage for final mesh data
8481 loadmodel->num_textures = numtextures * loadmodel->numskins;
8482 loadmodel->num_texturesperskin = numtextures;
8483 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 *));
8484 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
8485 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8486 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8487 loadmodel->surfmesh.num_vertices = numvertices;
8488 loadmodel->surfmesh.num_triangles = numtriangles;
8489 if (r_enableshadowvolumes.integer)
8490 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
8491 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8492 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8493 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8494 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8495 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8496 if (loadmodel->surfmesh.num_vertices <= 65536)
8497 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8499 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8501 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8502 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8503 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8506 // load the textures
8507 for (textureindex = 0;textureindex < numtextures;textureindex++)
8508 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8509 Mod_FreeSkinFiles(skinfiles);
8511 // set the surface textures to their real values now that we loaded them...
8512 for (i = 0;i < loadmodel->num_surfaces;i++)
8513 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8517 Mem_Free(texturenames);
8521 Mem_Free(vertexhashtable);
8522 Mem_Free(vertexhashdata);
8524 // make a single combined shadow mesh to allow optimized shadow volume creation
8525 Mod_Q1BSP_CreateShadowMesh(loadmodel);
8527 // compute all the mesh information that was not loaded from the file
8528 if (loadmodel->surfmesh.data_element3s)
8529 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8530 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8531 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8532 // generate normals if the file did not have them
8533 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8534 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);
8535 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);
8536 if (loadmodel->surfmesh.data_neighbor3i)
8537 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8539 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8540 loadmodel->brush.num_visleafs = 1;
8541 loadmodel->brush.num_leafs = 1;
8542 loadmodel->brush.num_nodes = 0;
8543 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8544 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8545 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8546 loadmodel->brush.num_pvsclusters = 1;
8547 loadmodel->brush.num_pvsclusterbytes = 1;
8548 loadmodel->brush.data_pvsclusters = nobsp_pvs;
8549 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8550 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8551 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
8552 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8553 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8554 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8555 loadmodel->brush.data_leafs->clusterindex = 0;
8556 loadmodel->brush.data_leafs->areaindex = 0;
8557 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8558 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8559 loadmodel->brush.data_leafs->numleafbrushes = 0;
8560 loadmodel->brush.data_leafs->firstleafbrush = NULL;
8561 loadmodel->brush.supportwateralpha = true;
8563 if (loadmodel->brush.numsubmodels)
8564 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8567 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8572 // duplicate the basic information
8573 dpsnprintf(name, sizeof(name), "*%i", i);
8574 mod = Mod_FindName(name, loadmodel->name);
8575 // copy the base model to this one
8577 // rename the clone back to its proper name
8578 strlcpy(mod->name, name, sizeof(mod->name));
8579 mod->brush.parentmodel = loadmodel;
8580 // textures and memory belong to the main model
8581 mod->texturepool = NULL;
8582 mod->mempool = NULL;
8583 mod->brush.GetPVS = NULL;
8584 mod->brush.FatPVS = NULL;
8585 mod->brush.BoxTouchingPVS = NULL;
8586 mod->brush.BoxTouchingLeafPVS = NULL;
8587 mod->brush.BoxTouchingVisibleLeafs = NULL;
8588 mod->brush.FindBoxClusters = NULL;
8589 mod->brush.LightPoint = NULL;
8590 mod->brush.AmbientSoundLevelsForPoint = NULL;
8592 mod->brush.submodel = i;
8593 if (loadmodel->brush.submodels)
8594 loadmodel->brush.submodels[i] = mod;
8596 // make the model surface list (used by shadowing/lighting)
8597 mod->firstmodelsurface = submodelfirstsurface[i];
8598 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8599 mod->firstmodelbrush = 0;
8600 mod->nummodelbrushes = 0;
8601 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8602 Mod_MakeSortedSurfaces(mod);
8604 VectorClear(mod->normalmins);
8605 VectorClear(mod->normalmaxs);
8607 for (j = 0;j < mod->nummodelsurfaces;j++)
8609 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8610 const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8612 if (!surface->num_vertices)
8617 VectorCopy(v3f, mod->normalmins);
8618 VectorCopy(v3f, mod->normalmaxs);
8620 for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8622 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8623 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8624 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8625 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8626 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8627 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8630 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8631 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8632 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8633 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8634 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8635 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8636 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8637 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8638 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8639 mod->yawmins[2] = mod->normalmins[2];
8640 mod->yawmaxs[2] = mod->normalmaxs[2];
8641 mod->radius = modelradius;
8642 mod->radius2 = modelradius * modelradius;
8644 // this gets altered below if sky or water is used
8645 mod->DrawSky = NULL;
8646 mod->DrawAddWaterPlanes = NULL;
8648 for (j = 0;j < mod->nummodelsurfaces;j++)
8649 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8651 if (j < mod->nummodelsurfaces)
8652 mod->DrawSky = R_Q1BSP_DrawSky;
8654 for (j = 0;j < mod->nummodelsurfaces;j++)
8655 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8657 if (j < mod->nummodelsurfaces)
8658 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8660 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8661 mod->render_bih = mod->collision_bih;
8663 // generate VBOs and other shared data before cloning submodels
8668 Mem_Free(submodelfirstsurface);
8670 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);