2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
30 cvar_t mod_bsp_portalize = {0, "mod_bsp_portalize", "1", "enables portal generation from BSP tree (may take several seconds per map), used by r_drawportals, r_useportalculling, r_shadow_realtime_world_compileportalculling, sv_cullentities_portal"};
31 cvar_t r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
34 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
35 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
38 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
39 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
40 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t r_trippy = {0, "r_trippy", "0", "easter egg"};
42 cvar_t r_fxaa = {CVAR_SAVE, "r_fxaa", "0", "fast approximate anti aliasing"};
43 cvar_t mod_noshader_default_offsetmapping = {CVAR_SAVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
44 cvar_t mod_obj_orientation = {0, "mod_obj_orientation", "1", "fix orientation of OBJ models to the usual conventions (if zero, use coordinates as is)"};
45 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
46 cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
47 cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
48 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
49 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
50 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
51 cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
52 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
53 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
54 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
55 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
56 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
57 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
58 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
59 cvar_t mod_q3shader_force_addalpha = {0, "mod_q3shader_force_addalpha", "0", "treat GL_ONE GL_ONE (or add) blendfunc as GL_SRC_ALPHA GL_ONE for compatibility with older DarkPlaces releases"};
60 cvar_t mod_q3shader_force_terrain_alphaflag = {0, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
62 cvar_t mod_q1bsp_polygoncollisions = {0, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
63 cvar_t mod_collision_bih = {0, "mod_collision_bih", "1", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
64 cvar_t mod_recalculatenodeboxes = {0, "mod_recalculatenodeboxes", "1", "enables use of generated node bounding boxes based on BSP tree portal reconstruction, rather than the node boxes supplied by the map compiler"};
66 static texture_t mod_q1bsp_texture_solid;
67 static texture_t mod_q1bsp_texture_sky;
68 static texture_t mod_q1bsp_texture_lava;
69 static texture_t mod_q1bsp_texture_slime;
70 static texture_t mod_q1bsp_texture_water;
72 void Mod_BrushInit(void)
74 // Cvar_RegisterVariable(&r_subdivide_size);
75 Cvar_RegisterVariable(&mod_bsp_portalize);
76 Cvar_RegisterVariable(&r_novis);
77 Cvar_RegisterVariable(&r_nosurftextures);
78 Cvar_RegisterVariable(&r_subdivisions_tolerance);
79 Cvar_RegisterVariable(&r_subdivisions_mintess);
80 Cvar_RegisterVariable(&r_subdivisions_maxtess);
81 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
82 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
83 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
84 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
85 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
86 Cvar_RegisterVariable(&r_trippy);
87 Cvar_RegisterVariable(&r_fxaa);
88 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
89 Cvar_RegisterVariable(&mod_obj_orientation);
90 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
91 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
92 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
93 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
94 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
95 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
96 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
97 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
98 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
99 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
100 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
101 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
102 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
103 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
104 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
105 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
106 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
107 Cvar_RegisterVariable(&mod_collision_bih);
108 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
110 // these games were made for older DP engines and are no longer
111 // maintained; use this hack to show their textures properly
112 if(gamemode == GAME_NEXUIZ)
113 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
115 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
116 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
117 mod_q1bsp_texture_solid.surfaceflags = 0;
118 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
120 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
121 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
122 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
123 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
125 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
126 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
127 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
128 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
130 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
131 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
132 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
133 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
135 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
136 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
137 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
138 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
141 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
148 // LordHavoc: modified to start at first clip node,
149 // in other words: first node of the (sub)model
150 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
152 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
154 return (mleaf_t *)node;
157 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
161 leaf = Mod_Q1BSP_PointInLeaf(model, p);
164 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
167 memcpy(out, leaf->ambient_sound_level, i);
173 memset(out, 0, outsize);
176 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
179 int nodestackindex = 0;
180 mnode_t *node, *nodestack[1024];
181 if (!model->brush.num_pvsclusters)
183 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
189 // node - recurse down the BSP tree
190 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
194 return -1; // ERROR: NAN bounding box!
195 // box is on one side of plane, take that path
196 node = node->children[sides-1];
200 // box crosses plane, take one path and remember the other
201 if (nodestackindex < 1024)
202 nodestack[nodestackindex++] = node->children[0];
203 node = node->children[1];
209 // leaf - add clusterindex to list
210 if (numclusters < maxclusters)
211 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
215 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
219 if (nodestackindex < 1024)
220 nodestack[nodestackindex++] = node->children[0];
221 node = node->children[1];
226 // leaf - add clusterindex to list
227 if (numclusters < maxclusters)
228 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
233 // try another path we didn't take earlier
234 if (nodestackindex == 0)
236 node = nodestack[--nodestackindex];
238 // return number of clusters found (even if more than the maxclusters)
242 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
244 int nodestackindex = 0;
245 mnode_t *node, *nodestack[1024];
246 if (!model->brush.num_pvsclusters)
248 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
254 // node - recurse down the BSP tree
255 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
259 return -1; // ERROR: NAN bounding box!
260 // box is on one side of plane, take that path
261 node = node->children[sides-1];
265 // box crosses plane, take one path and remember the other
266 if (nodestackindex < 1024)
267 nodestack[nodestackindex++] = node->children[0];
268 node = node->children[1];
274 // leaf - check cluster bit
275 int clusterindex = ((mleaf_t *)node)->clusterindex;
276 if (CHECKPVSBIT(pvs, clusterindex))
278 // it is visible, return immediately with the news
283 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
287 if (nodestackindex < 1024)
288 nodestack[nodestackindex++] = node->children[0];
289 node = node->children[1];
294 // leaf - check cluster bit
295 int clusterindex = ((mleaf_t *)node)->clusterindex;
296 if (CHECKPVSBIT(pvs, clusterindex))
298 // it is visible, return immediately with the news
304 // nothing to see here, try another path we didn't take earlier
305 if (nodestackindex == 0)
307 node = nodestack[--nodestackindex];
313 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
315 int nodestackindex = 0;
316 mnode_t *node, *nodestack[1024];
317 if (!model->brush.num_leafs)
319 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
325 // node - recurse down the BSP tree
326 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
330 return -1; // ERROR: NAN bounding box!
331 // box is on one side of plane, take that path
332 node = node->children[sides-1];
336 // box crosses plane, take one path and remember the other
337 if (nodestackindex < 1024)
338 nodestack[nodestackindex++] = node->children[0];
339 node = node->children[1];
345 // leaf - check cluster bit
346 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
347 if (CHECKPVSBIT(pvs, clusterindex))
349 // it is visible, return immediately with the news
354 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
358 if (nodestackindex < 1024)
359 nodestack[nodestackindex++] = node->children[0];
360 node = node->children[1];
365 // leaf - check cluster bit
366 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
367 if (CHECKPVSBIT(pvs, clusterindex))
369 // it is visible, return immediately with the news
375 // nothing to see here, try another path we didn't take earlier
376 if (nodestackindex == 0)
378 node = nodestack[--nodestackindex];
384 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
386 int nodestackindex = 0;
387 mnode_t *node, *nodestack[1024];
388 if (!model->brush.num_leafs)
390 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
396 // node - recurse down the BSP tree
397 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
401 return -1; // ERROR: NAN bounding box!
402 // box is on one side of plane, take that path
403 node = node->children[sides-1];
407 // box crosses plane, take one path and remember the other
408 if (nodestackindex < 1024)
409 nodestack[nodestackindex++] = node->children[0];
410 node = node->children[1];
416 // leaf - check if it is visible
417 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
419 // it is visible, return immediately with the news
424 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
428 if (nodestackindex < 1024)
429 nodestack[nodestackindex++] = node->children[0];
430 node = node->children[1];
435 // leaf - check if it is visible
436 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
438 // it is visible, return immediately with the news
444 // nothing to see here, try another path we didn't take earlier
445 if (nodestackindex == 0)
447 node = nodestack[--nodestackindex];
453 typedef struct findnonsolidlocationinfo_s
456 vec3_t absmin, absmax;
462 findnonsolidlocationinfo_t;
464 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
467 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
469 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
470 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
471 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
472 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
473 VectorSubtract(vert[1], vert[0], edge[0]);
474 VectorSubtract(vert[2], vert[1], edge[1]);
475 CrossProduct(edge[1], edge[0], facenormal);
476 if (facenormal[0] || facenormal[1] || facenormal[2])
478 VectorNormalize(facenormal);
479 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
480 if (f <= info->bestdist && f >= -info->bestdist)
482 VectorSubtract(vert[0], vert[2], edge[2]);
483 VectorNormalize(edge[0]);
484 VectorNormalize(edge[1]);
485 VectorNormalize(edge[2]);
486 CrossProduct(facenormal, edge[0], edgenormal[0]);
487 CrossProduct(facenormal, edge[1], edgenormal[1]);
488 CrossProduct(facenormal, edge[2], edgenormal[2]);
490 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
491 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
492 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
494 // we got lucky, the center is within the face
495 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
499 if (info->bestdist > dist)
501 info->bestdist = dist;
502 VectorScale(facenormal, (info->radius - -dist), info->nudge);
507 if (info->bestdist > dist)
509 info->bestdist = dist;
510 VectorScale(facenormal, (info->radius - dist), info->nudge);
516 // check which edge or vertex the center is nearest
517 for (i = 0;i < 3;i++)
519 f = DotProduct(info->center, edge[i]);
520 if (f >= DotProduct(vert[0], edge[i])
521 && f <= DotProduct(vert[1], edge[i]))
524 VectorMA(info->center, -f, edge[i], point);
525 dist = sqrt(DotProduct(point, point));
526 if (info->bestdist > dist)
528 info->bestdist = dist;
529 VectorScale(point, (info->radius / dist), info->nudge);
531 // skip both vertex checks
532 // (both are further away than this edge)
537 // not on edge, check first vertex of edge
538 VectorSubtract(info->center, vert[i], point);
539 dist = sqrt(DotProduct(point, point));
540 if (info->bestdist > dist)
542 info->bestdist = dist;
543 VectorScale(point, (info->radius / dist), info->nudge);
552 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
554 int surfacenum, k, *mark;
556 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
558 surface = info->model->data_surfaces + *mark;
559 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
561 if(surface->deprecatedq3num_bboxstride > 0)
564 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
565 for(i = 0; i < cnt; ++i)
567 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
569 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
571 tri = i * surface->deprecatedq3num_bboxstride + k;
572 if(tri >= surface->num_triangles)
574 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
581 for (k = 0;k < surface->num_triangles;k++)
583 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
590 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
594 float f = PlaneDiff(info->center, node->plane);
595 if (f >= -info->bestdist)
596 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
597 if (f <= info->bestdist)
598 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
602 if (((mleaf_t *)node)->numleafsurfaces)
603 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
607 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
610 findnonsolidlocationinfo_t info;
616 VectorCopy(in, info.center);
617 info.radius = radius;
622 VectorClear(info.nudge);
623 info.bestdist = radius;
624 VectorCopy(info.center, info.absmin);
625 VectorCopy(info.center, info.absmax);
626 info.absmin[0] -= info.radius + 1;
627 info.absmin[1] -= info.radius + 1;
628 info.absmin[2] -= info.radius + 1;
629 info.absmax[0] += info.radius + 1;
630 info.absmax[1] += info.radius + 1;
631 info.absmax[2] += info.radius + 1;
632 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
633 VectorAdd(info.center, info.nudge, info.center);
635 while (info.bestdist < radius && ++i < 10);
636 VectorCopy(info.center, out);
639 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
641 switch(nativecontents)
646 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
648 return SUPERCONTENTS_WATER;
650 return SUPERCONTENTS_SLIME;
652 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
654 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
659 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
661 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
662 return CONTENTS_SOLID;
663 if (supercontents & SUPERCONTENTS_SKY)
665 if (supercontents & SUPERCONTENTS_LAVA)
666 return CONTENTS_LAVA;
667 if (supercontents & SUPERCONTENTS_SLIME)
668 return CONTENTS_SLIME;
669 if (supercontents & SUPERCONTENTS_WATER)
670 return CONTENTS_WATER;
671 return CONTENTS_EMPTY;
674 typedef struct RecursiveHullCheckTraceInfo_s
676 // the hull we're tracing through
679 // the trace structure to fill in
682 // start, end, and end - start (in model space)
687 RecursiveHullCheckTraceInfo_t;
689 // 1/32 epsilon to keep floating point happy
690 #define DIST_EPSILON (0.03125)
692 #define HULLCHECKSTATE_EMPTY 0
693 #define HULLCHECKSTATE_SOLID 1
694 #define HULLCHECKSTATE_DONE 2
696 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
698 // status variables, these don't need to be saved on the stack when
699 // recursing... but are because this should be thread-safe
700 // (note: tracing against a bbox is not thread-safe, yet)
705 // variables that need to be stored on the stack when recursing
710 // keep looping until we hit a leaf
713 // find the point distances
714 node = t->hull->clipnodes + num;
715 plane = t->hull->planes + node->planenum;
717 // axial planes can be calculated more quickly without the DotProduct
720 t1 = p1[plane->type] - plane->dist;
721 t2 = p2[plane->type] - plane->dist;
725 t1 = DotProduct (plane->normal, p1) - plane->dist;
726 t2 = DotProduct (plane->normal, p2) - plane->dist;
729 // negative plane distances indicate children[1] (behind plane)
733 // if the line starts and ends on the same side of the plane, recurse
734 // into that child instantly
735 if (p1side == p2side)
737 #if COLLISIONPARANOID >= 3
743 // loop back and process the start child
744 num = node->children[p1side];
748 // find the midpoint where the line crosses the plane, use the
749 // original line for best accuracy
750 #if COLLISIONPARANOID >= 3
755 t1 = t->start[plane->type] - plane->dist;
756 t2 = t->end[plane->type] - plane->dist;
760 t1 = DotProduct (plane->normal, t->start) - plane->dist;
761 t2 = DotProduct (plane->normal, t->end) - plane->dist;
763 midf = t1 / (t1 - t2);
764 midf = bound(p1f, midf, p2f);
765 VectorMA(t->start, midf, t->dist, mid);
767 // we now have a mid point, essentially splitting the line into
768 // the segments in the near child and the far child, we can now
769 // recurse those in order and get their results
771 // recurse both sides, front side first
772 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
773 // if this side is not empty, return what it is (solid or done)
774 if (ret != HULLCHECKSTATE_EMPTY)
777 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
778 // if other side is not solid, return what it is (empty or done)
779 if (ret != HULLCHECKSTATE_SOLID)
782 // front is air and back is solid, this is the impact point...
784 // copy the plane information, flipping it if needed
787 t->trace->plane.dist = -plane->dist;
788 VectorNegate (plane->normal, t->trace->plane.normal);
792 t->trace->plane.dist = plane->dist;
793 VectorCopy (plane->normal, t->trace->plane.normal);
796 // calculate the return fraction which is nudged off the surface a bit
797 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
798 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
799 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
800 t->trace->fraction = bound(0, midf, 1);
802 #if COLLISIONPARANOID >= 3
805 return HULLCHECKSTATE_DONE;
809 // we reached a leaf contents
812 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
813 if (!t->trace->startfound)
815 t->trace->startfound = true;
816 t->trace->startsupercontents |= num;
818 if (num & SUPERCONTENTS_LIQUIDSMASK)
819 t->trace->inwater = true;
821 t->trace->inopen = true;
822 if (num & SUPERCONTENTS_SOLID)
823 t->trace->hittexture = &mod_q1bsp_texture_solid;
824 else if (num & SUPERCONTENTS_SKY)
825 t->trace->hittexture = &mod_q1bsp_texture_sky;
826 else if (num & SUPERCONTENTS_LAVA)
827 t->trace->hittexture = &mod_q1bsp_texture_lava;
828 else if (num & SUPERCONTENTS_SLIME)
829 t->trace->hittexture = &mod_q1bsp_texture_slime;
831 t->trace->hittexture = &mod_q1bsp_texture_water;
832 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
833 t->trace->hitsupercontents = num;
834 if (num & t->trace->hitsupercontentsmask)
836 // if the first leaf is solid, set startsolid
837 if (t->trace->allsolid)
838 t->trace->startsolid = true;
839 #if COLLISIONPARANOID >= 3
842 return HULLCHECKSTATE_SOLID;
846 t->trace->allsolid = false;
847 #if COLLISIONPARANOID >= 3
850 return HULLCHECKSTATE_EMPTY;
854 //#if COLLISIONPARANOID < 2
855 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
858 mclipnode_t *nodes = t->hull->clipnodes;
859 mplane_t *planes = t->hull->planes;
861 VectorCopy(t->start, point);
864 plane = planes + nodes[num].planenum;
865 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
867 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
868 t->trace->startsupercontents |= num;
869 if (num & SUPERCONTENTS_LIQUIDSMASK)
870 t->trace->inwater = true;
872 t->trace->inopen = true;
873 if (num & t->trace->hitsupercontentsmask)
875 t->trace->allsolid = t->trace->startsolid = true;
876 return HULLCHECKSTATE_SOLID;
880 t->trace->allsolid = t->trace->startsolid = false;
881 return HULLCHECKSTATE_EMPTY;
886 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)
888 RecursiveHullCheckTraceInfo_t rhc;
890 memset(&rhc, 0, sizeof(rhc));
891 memset(trace, 0, sizeof(trace_t));
893 rhc.trace->fraction = 1;
894 rhc.trace->allsolid = true;
895 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
896 VectorCopy(start, rhc.start);
897 VectorCopy(start, rhc.end);
898 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
901 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);
903 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)
905 RecursiveHullCheckTraceInfo_t rhc;
907 if (VectorCompare(start, end))
909 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
913 // 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...
914 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
916 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
920 memset(&rhc, 0, sizeof(rhc));
921 memset(trace, 0, sizeof(trace_t));
923 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
924 rhc.trace->fraction = 1;
925 rhc.trace->allsolid = true;
926 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
927 VectorCopy(start, rhc.start);
928 VectorCopy(end, rhc.end);
929 VectorSubtract(rhc.end, rhc.start, rhc.dist);
930 #if COLLISIONPARANOID >= 2
931 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]);
932 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
937 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
938 memset(&testtrace, 0, sizeof(trace_t));
939 rhc.trace = &testtrace;
940 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
941 rhc.trace->fraction = 1;
942 rhc.trace->allsolid = true;
943 VectorCopy(test, rhc.start);
944 VectorCopy(test, rhc.end);
945 VectorClear(rhc.dist);
946 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
947 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
948 if (!trace->startsolid && testtrace.startsolid)
949 Con_Printf(" - ended in solid!\n");
953 if (VectorLength2(rhc.dist))
954 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
956 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
960 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)
962 // this function currently only supports same size start and end
964 RecursiveHullCheckTraceInfo_t rhc;
966 if (VectorCompare(boxmins, boxmaxs))
968 if (VectorCompare(start, end))
969 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
971 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
975 memset(&rhc, 0, sizeof(rhc));
976 memset(trace, 0, sizeof(trace_t));
978 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
979 rhc.trace->fraction = 1;
980 rhc.trace->allsolid = true;
981 VectorSubtract(boxmaxs, boxmins, boxsize);
983 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
984 else if (model->brush.ishlbsp)
986 // LordHavoc: this has to have a minor tolerance (the .1) because of
987 // minor float precision errors from the box being transformed around
988 if (boxsize[0] < 32.1)
990 if (boxsize[2] < 54) // pick the nearest of 36 or 72
991 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
993 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
996 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1000 // LordHavoc: this has to have a minor tolerance (the .1) because of
1001 // minor float precision errors from the box being transformed around
1002 if (boxsize[0] < 32.1)
1003 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1005 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1007 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1008 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1009 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1010 #if COLLISIONPARANOID >= 2
1011 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]);
1012 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1017 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1018 memset(&testtrace, 0, sizeof(trace_t));
1019 rhc.trace = &testtrace;
1020 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1021 rhc.trace->fraction = 1;
1022 rhc.trace->allsolid = true;
1023 VectorCopy(test, rhc.start);
1024 VectorCopy(test, rhc.end);
1025 VectorClear(rhc.dist);
1026 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1027 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1028 if (!trace->startsolid && testtrace.startsolid)
1029 Con_Printf(" - ended in solid!\n");
1033 if (VectorLength2(rhc.dist))
1034 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1036 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1040 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1042 int num = model->brushq1.hulls[0].firstclipnode;
1044 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1045 mplane_t *planes = model->brushq1.hulls[0].planes;
1048 plane = planes + nodes[num].planenum;
1049 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1051 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1054 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)
1058 colplanef_t cbox_planes[6];
1060 cbox.hasaabbplanes = true;
1061 cbox.supercontents = boxsupercontents;
1064 cbox.numtriangles = 0;
1065 cbox.planes = cbox_planes;
1067 cbox.elements = NULL;
1075 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];
1076 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];
1077 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];
1078 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];
1079 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];
1080 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];
1081 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1082 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1083 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1084 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1085 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1086 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1087 memset(trace, 0, sizeof(trace_t));
1088 trace->hitsupercontentsmask = hitsupercontentsmask;
1089 trace->fraction = 1;
1090 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1092 RecursiveHullCheckTraceInfo_t rhc;
1093 static hull_t box_hull;
1094 static mclipnode_t box_clipnodes[6];
1095 static mplane_t box_planes[6];
1096 // fill in a default trace
1097 memset(&rhc, 0, sizeof(rhc));
1098 memset(trace, 0, sizeof(trace_t));
1099 //To keep everything totally uniform, bounding boxes are turned into small
1100 //BSP trees instead of being compared directly.
1101 // create a temp hull from bounding box sizes
1102 box_planes[0].dist = cmaxs[0] - mins[0];
1103 box_planes[1].dist = cmins[0] - maxs[0];
1104 box_planes[2].dist = cmaxs[1] - mins[1];
1105 box_planes[3].dist = cmins[1] - maxs[1];
1106 box_planes[4].dist = cmaxs[2] - mins[2];
1107 box_planes[5].dist = cmins[2] - maxs[2];
1108 #if COLLISIONPARANOID >= 3
1109 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]);
1112 if (box_hull.clipnodes == NULL)
1116 //Set up the planes and clipnodes so that the six floats of a bounding box
1117 //can just be stored out and get a proper hull_t structure.
1119 box_hull.clipnodes = box_clipnodes;
1120 box_hull.planes = box_planes;
1121 box_hull.firstclipnode = 0;
1122 box_hull.lastclipnode = 5;
1124 for (i = 0;i < 6;i++)
1126 box_clipnodes[i].planenum = i;
1130 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1132 box_clipnodes[i].children[side^1] = i + 1;
1134 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1136 box_planes[i].type = i>>1;
1137 box_planes[i].normal[i>>1] = 1;
1141 // trace a line through the generated clipping hull
1142 //rhc.boxsupercontents = boxsupercontents;
1143 rhc.hull = &box_hull;
1145 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1146 rhc.trace->fraction = 1;
1147 rhc.trace->allsolid = true;
1148 VectorCopy(start, rhc.start);
1149 VectorCopy(end, rhc.end);
1150 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1151 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1152 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1153 if (rhc.trace->startsupercontents)
1154 rhc.trace->startsupercontents = boxsupercontents;
1158 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)
1160 memset(trace, 0, sizeof(trace_t));
1161 trace->fraction = 1;
1162 if (BoxesOverlap(start, start, cmins, cmaxs))
1164 trace->startsupercontents |= boxsupercontents;
1165 if (hitsupercontentsmask & boxsupercontents)
1167 trace->startsolid = true;
1168 trace->allsolid = true;
1173 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1176 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1177 return trace.fraction == 1;
1180 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)
1184 float mid, distz = endz - startz;
1188 switch (node->plane->type)
1191 node = node->children[x < node->plane->dist];
1192 continue; // loop back and process the new node
1194 node = node->children[y < node->plane->dist];
1195 continue; // loop back and process the new node
1197 side = startz < node->plane->dist;
1198 if ((endz < node->plane->dist) == side)
1200 node = node->children[side];
1201 continue; // loop back and process the new node
1203 // found an intersection
1204 mid = node->plane->dist;
1207 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1208 front += startz * node->plane->normal[2];
1209 back += endz * node->plane->normal[2];
1210 side = front < node->plane->dist;
1211 if ((back < node->plane->dist) == side)
1213 node = node->children[side];
1214 continue; // loop back and process the new node
1216 // found an intersection
1217 mid = startz + distz * (front - node->plane->dist) / (front - back);
1221 // go down front side
1222 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1223 return true; // hit something
1225 // check for impact on this node
1226 if (node->numsurfaces)
1229 int dsi, dti, lmwidth, lmheight;
1231 msurface_t *surface;
1232 unsigned char *lightmap;
1233 int maps, line3, size3;
1236 float scale, w, w00, w01, w10, w11;
1238 surface = model->data_surfaces + node->firstsurface;
1239 for (i = 0;i < node->numsurfaces;i++, surface++)
1241 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1242 continue; // no lightmaps
1244 // location we want to sample in the lightmap
1245 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;
1246 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;
1249 // thanks to jitspoe for pointing out that this int cast was
1250 // rounding toward zero, so we floor it
1251 dsi = (int)floor(ds);
1252 dti = (int)floor(dt);
1253 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1254 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1257 // we have to tolerate a position of lmwidth-1 for some rare
1258 // cases - in which case the sampling position still gets
1259 // clamped but the color gets interpolated to that edge.
1260 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1262 // in the rare cases where we're sampling slightly off
1263 // the polygon, clamp the sampling position (we can still
1264 // interpolate outside it, where it becomes extrapolation)
1269 if (dsi > lmwidth-2)
1271 if (dti > lmheight-2)
1274 // calculate bilinear interpolation factors
1275 // and also multiply by fixedpoint conversion factors to
1276 // compensate for lightmaps being 0-255 (as 0-2), we use
1277 // r_refdef.scene.rtlightstylevalue here which is already
1278 // 0.000-2.148 range
1279 // (if we used r_refdef.scene.lightstylevalue this
1280 // divisor would be 32768 rather than 128)
1283 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1284 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1285 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1286 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1288 // values for pointer math
1289 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1290 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1292 // look up the pixel
1293 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1295 // bilinear filter each lightmap style, and sum them
1296 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1298 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1299 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1300 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1301 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1302 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1306 return true; // success
1311 // go down back side
1312 node = node->children[side ^ 1];
1314 distz = endz - startz;
1315 // loop back and process the new node
1318 // did not hit anything
1322 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1324 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1325 VectorSet(diffusenormal, 0, 0, 1);
1327 if (!model->brushq1.lightdata)
1329 VectorSet(ambientcolor, 1, 1, 1);
1330 VectorSet(diffusecolor, 0, 0, 0);
1334 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);
1337 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1342 const msurface_t *surface;
1347 float edgenormal[3];
1354 surface = model->data_surfaces + node->firstsurface;
1355 for (i = 0;i < node->numsurfaces;i++, surface++)
1357 // skip surfaces whose bounding box does not include the point
1358 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1360 // skip faces with contents we don't care about
1361 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1363 // get the surface normal - since it is flat we know any vertex normal will suffice
1364 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1366 if (DotProduct(t->dist, normal) > 0)
1368 // iterate edges and see if the point is outside one of them
1369 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1371 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1372 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1373 VectorSubtract(v0, v1, edgedir);
1374 CrossProduct(edgedir, normal, edgenormal);
1375 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1378 // if the point is outside one of the edges, it is not within the surface
1379 if (j < surface->num_vertices)
1382 // we hit a surface, this is the impact point...
1383 VectorCopy(normal, t->trace->plane.normal);
1384 t->trace->plane.dist = DotProduct(normal, p);
1386 // calculate the return fraction which is nudged off the surface a bit
1387 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1388 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1389 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1390 t->trace->fraction = bound(0, midf, 1);
1392 t->trace->hittexture = surface->texture->currentframe;
1393 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1394 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1395 return surface->texture->currentframe;
1400 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])
1402 const mplane_t *plane;
1405 double midf, mid[3];
1406 const mleaf_t *leaf;
1410 plane = node->plane;
1411 if (plane->type < 3)
1413 t1 = p1[plane->type] - plane->dist;
1414 t2 = p2[plane->type] - plane->dist;
1418 t1 = DotProduct (plane->normal, p1) - plane->dist;
1419 t2 = DotProduct (plane->normal, p2) - plane->dist;
1425 node = node->children[1];
1434 node = node->children[0];
1440 // the line intersects, find intersection point
1441 // LordHavoc: this uses the original trace for maximum accuracy
1442 if (plane->type < 3)
1444 t1 = t->start[plane->type] - plane->dist;
1445 t2 = t->end[plane->type] - plane->dist;
1449 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1450 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1453 midf = t1 / (t1 - t2);
1454 VectorMA(t->start, midf, t->dist, mid);
1456 // recurse both sides, front side first, return if we hit a surface
1457 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1458 return HULLCHECKSTATE_DONE;
1460 // test each surface on the node
1461 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1462 if (t->trace->hittexture)
1463 return HULLCHECKSTATE_DONE;
1465 // recurse back side
1466 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1468 leaf = (const mleaf_t *)node;
1469 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1470 if (!t->trace->startfound)
1472 t->trace->startfound = true;
1473 t->trace->startsupercontents |= side;
1475 if (side & SUPERCONTENTS_LIQUIDSMASK)
1476 t->trace->inwater = true;
1478 t->trace->inopen = true;
1479 if (side & t->trace->hitsupercontentsmask)
1481 // if the first leaf is solid, set startsolid
1482 if (t->trace->allsolid)
1483 t->trace->startsolid = true;
1484 return HULLCHECKSTATE_SOLID;
1488 t->trace->allsolid = false;
1489 return HULLCHECKSTATE_EMPTY;
1493 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)
1495 RecursiveHullCheckTraceInfo_t rhc;
1497 memset(&rhc, 0, sizeof(rhc));
1498 memset(trace, 0, sizeof(trace_t));
1500 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1501 rhc.trace->fraction = 1;
1502 rhc.trace->allsolid = true;
1503 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1504 VectorCopy(start, rhc.start);
1505 VectorCopy(end, rhc.end);
1506 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1507 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1508 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1511 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1514 unsigned char *outstart = out;
1515 while (out < outend)
1519 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));
1529 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));
1532 for (c = *in++;c > 0;c--)
1536 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));
1547 R_Q1BSP_LoadSplitSky
1549 A sky texture is 256*128, with the right side being a masked overlay
1552 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1557 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1558 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1560 // allocate a texture pool if we need it
1561 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1562 loadmodel->texturepool = R_AllocTexturePool();
1564 if (bytesperpixel == 4)
1566 for (y = 0;y < h;y++)
1568 for (x = 0;x < w;x++)
1570 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1571 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1577 // make an average value for the back to avoid
1578 // a fringe on the top level
1587 for (y = 0;y < h;y++)
1589 for (x = 0;x < w;x++)
1591 p = src[x*width+y+w];
1592 r += palette_rgb[p][0];
1593 g += palette_rgb[p][1];
1594 b += palette_rgb[p][2];
1597 bgra.b[2] = r/(w*h);
1598 bgra.b[1] = g/(w*h);
1599 bgra.b[0] = b/(w*h);
1601 for (y = 0;y < h;y++)
1603 for (x = 0;x < w;x++)
1605 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1607 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1612 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1613 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1614 Mem_Free(solidpixels);
1615 Mem_Free(alphapixels);
1618 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1620 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1621 skinframe_t *skinframe;
1622 texture_t *tx, *tx2, *anims[10], *altanims[10];
1623 texture_t backuptex;
1624 unsigned char *data, *mtdata;
1626 char mapname[MAX_QPATH], name[MAX_QPATH];
1627 unsigned char zeroopaque[4], zerotrans[4];
1630 Vector4Set(zeroopaque, 0, 0, 0, 255);
1631 Vector4Set(zerotrans, 0, 0, 0, 128);
1633 loadmodel->data_textures = NULL;
1635 // add two slots for notexture walls and notexture liquids
1638 nummiptex = MSG_ReadLittleLong(sb);
1639 loadmodel->num_textures = nummiptex + 2;
1640 loadmodel->num_texturesperskin = loadmodel->num_textures;
1644 loadmodel->num_textures = 2;
1645 loadmodel->num_texturesperskin = loadmodel->num_textures;
1648 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1650 // fill out all slots with notexture
1651 if (cls.state != ca_dedicated)
1652 skinframe = R_SkinFrame_LoadMissing();
1655 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1657 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1660 if (cls.state != ca_dedicated)
1662 tx->numskinframes = 1;
1663 tx->skinframerate = 1;
1664 tx->skinframes[0] = skinframe;
1665 tx->currentskinframe = tx->skinframes[0];
1667 tx->basematerialflags = MATERIALFLAG_WALL;
1668 if (i == loadmodel->num_textures - 1)
1670 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1671 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1672 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1676 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1677 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1679 tx->currentframe = tx;
1681 // clear water settings
1684 tx->refractfactor = 1;
1685 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1686 tx->reflectfactor = 1;
1687 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1688 tx->r_water_wateralpha = 1;
1689 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1690 tx->offsetscale = 1;
1692 tx->specularscalemod = 1;
1693 tx->specularpowermod = 1;
1694 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1695 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1696 // JUST GREP FOR "specularscalemod = 1".
1701 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1705 s = loadmodel->name;
1706 if (!strncasecmp(s, "maps/", 5))
1708 FS_StripExtension(s, mapname, sizeof(mapname));
1710 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1711 // LordHavoc: mostly rewritten map texture loader
1712 for (i = 0;i < nummiptex;i++)
1714 doffset = MSG_ReadLittleLong(sb);
1715 if (r_nosurftextures.integer)
1719 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1723 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1725 // copy name, but only up to 16 characters
1726 // (the output buffer can hold more than this, but the input buffer is
1728 for (j = 0;j < 16;j++)
1729 name[j] = MSG_ReadByte(&miptexsb);
1731 // pretty up the buffer (replacing any trailing garbage with 0)
1732 for (j = (int)strlen(name);j < 16;j++)
1737 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1738 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1741 mtwidth = MSG_ReadLittleLong(&miptexsb);
1742 mtheight = MSG_ReadLittleLong(&miptexsb);
1744 j = MSG_ReadLittleLong(&miptexsb);
1748 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1750 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1753 mtdata = miptexsb.data + j;
1756 if ((mtwidth & 15) || (mtheight & 15))
1757 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1759 // LordHavoc: force all names to lowercase
1760 for (j = 0;name[j];j++)
1761 if (name[j] >= 'A' && name[j] <= 'Z')
1762 name[j] += 'a' - 'A';
1764 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1765 backuptex = loadmodel->data_textures[i];
1766 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1768 loadmodel->data_textures[i] = backuptex;
1770 tx = loadmodel->data_textures + i;
1771 strlcpy(tx->name, name, sizeof(tx->name));
1772 tx->width = mtwidth;
1773 tx->height = mtheight;
1775 if (tx->name[0] == '*')
1777 if (!strncmp(tx->name, "*lava", 5))
1779 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1780 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1782 else if (!strncmp(tx->name, "*slime", 6))
1784 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1785 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1789 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1790 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1793 else if (!strncmp(tx->name, "sky", 3))
1795 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1796 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1797 // for the surface traceline we need to hit this surface as a solid...
1798 tx->supercontents |= SUPERCONTENTS_SOLID;
1802 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1803 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1806 if (cls.state != ca_dedicated)
1808 // LordHavoc: HL sky textures are entirely different than quake
1809 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1811 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1813 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1814 if (data && image_width == image_height * 2)
1816 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1819 else if (mtdata != NULL)
1820 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1824 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);
1826 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);
1828 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1831 // did not find external texture, load it from the bsp or wad3
1832 if (loadmodel->brush.ishlbsp)
1834 // internal texture overrides wad
1835 unsigned char *pixels, *freepixels;
1836 pixels = freepixels = NULL;
1838 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1840 pixels = freepixels = W_GetTextureBGRA(tx->name);
1843 tx->width = image_width;
1844 tx->height = image_height;
1845 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1848 Mem_Free(freepixels);
1850 else if (mtdata) // texture included
1851 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1853 // if skinframe is still NULL the "missing" texture will be used
1855 tx->skinframes[0] = skinframe;
1857 // LordHavoc: some Tenebrae textures get replaced by black
1858 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1859 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1860 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1861 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1864 tx->basematerialflags = MATERIALFLAG_WALL;
1865 if (tx->name[0] == '*')
1867 // LordHavoc: some turbulent textures should not be affected by wateralpha
1868 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1869 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1870 else if (!strncmp(tx->name,"*lava",5)
1871 || !strncmp(tx->name,"*teleport",9)
1872 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1873 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1875 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1876 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1877 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1879 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1881 // replace the texture with black
1882 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1884 else if (!strncmp(tx->name, "sky", 3))
1885 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1886 else if (!strcmp(tx->name, "caulk"))
1887 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1888 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1889 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1891 // start out with no animation
1892 tx->currentframe = tx;
1893 tx->currentskinframe = tx->skinframes[0];
1894 tx->currentmaterialflags = tx->basematerialflags;
1897 // sequence the animations
1898 for (i = 0;i < nummiptex;i++)
1900 tx = loadmodel->data_textures + i;
1901 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1903 if (tx->anim_total[0] || tx->anim_total[1])
1904 continue; // already sequenced
1906 // find the number of frames in the animation
1907 memset(anims, 0, sizeof(anims));
1908 memset(altanims, 0, sizeof(altanims));
1910 for (j = i;j < nummiptex;j++)
1912 tx2 = loadmodel->data_textures + j;
1913 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1917 if (num >= '0' && num <= '9')
1918 anims[num - '0'] = tx2;
1919 else if (num >= 'a' && num <= 'j')
1920 altanims[num - 'a'] = tx2;
1922 Con_Printf("Bad animating texture %s\n", tx->name);
1926 for (j = 0;j < 10;j++)
1933 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1936 for (j = 0;j < max;j++)
1940 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1944 for (j = 0;j < altmax;j++)
1948 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1957 // if there is no alternate animation, duplicate the primary
1958 // animation into the alternate
1960 for (k = 0;k < 10;k++)
1961 altanims[k] = anims[k];
1964 // link together the primary animation
1965 for (j = 0;j < max;j++)
1968 tx2->animated = true;
1969 tx2->anim_total[0] = max;
1970 tx2->anim_total[1] = altmax;
1971 for (k = 0;k < 10;k++)
1973 tx2->anim_frames[0][k] = anims[k];
1974 tx2->anim_frames[1][k] = altanims[k];
1978 // if there really is an alternate anim...
1979 if (anims[0] != altanims[0])
1981 // link together the alternate animation
1982 for (j = 0;j < altmax;j++)
1985 tx2->animated = true;
1986 // the primary/alternate are reversed here
1987 tx2->anim_total[0] = altmax;
1988 tx2->anim_total[1] = max;
1989 for (k = 0;k < 10;k++)
1991 tx2->anim_frames[0][k] = altanims[k];
1992 tx2->anim_frames[1][k] = anims[k];
1999 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2002 unsigned char *in, *out, *data, d;
2003 char litfilename[MAX_QPATH];
2004 char dlitfilename[MAX_QPATH];
2005 fs_offset_t filesize;
2006 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2008 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2009 for (i = 0;i < sb->cursize;i++)
2010 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2012 else // LordHavoc: bsp version 29 (normal white lighting)
2014 // LordHavoc: hope is not lost yet, check for a .lit file to load
2015 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2016 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2017 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2018 strlcat (litfilename, ".lit", sizeof (litfilename));
2019 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2020 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2023 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2025 i = LittleLong(((int *)data)[1]);
2028 if (developer_loading.integer)
2029 Con_Printf("loaded %s\n", litfilename);
2030 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2031 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2033 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2036 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2038 i = LittleLong(((int *)data)[1]);
2041 if (developer_loading.integer)
2042 Con_Printf("loaded %s\n", dlitfilename);
2043 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2044 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2045 loadmodel->brushq3.deluxemapping_modelspace = false;
2046 loadmodel->brushq3.deluxemapping = true;
2055 Con_Printf("Unknown .lit file version (%d)\n", i);
2057 else if (filesize == 8)
2058 Con_Print("Empty .lit file, ignoring\n");
2060 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2067 // LordHavoc: oh well, expand the white lighting data
2070 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2072 out = loadmodel->brushq1.lightdata;
2073 for (i = 0;i < sb->cursize;i++)
2083 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2085 loadmodel->brushq1.num_compressedpvs = 0;
2086 loadmodel->brushq1.data_compressedpvs = NULL;
2089 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2090 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2091 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2094 // used only for HalfLife maps
2095 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2097 char key[128], value[4096];
2101 if (!COM_ParseToken_Simple(&data, false, false, true))
2103 if (com_token[0] != '{')
2107 if (!COM_ParseToken_Simple(&data, false, false, true))
2109 if (com_token[0] == '}')
2110 break; // end of worldspawn
2111 if (com_token[0] == '_')
2112 strlcpy(key, com_token + 1, sizeof(key));
2114 strlcpy(key, com_token, sizeof(key));
2115 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2116 key[strlen(key)-1] = 0;
2117 if (!COM_ParseToken_Simple(&data, false, false, true))
2119 dpsnprintf(value, sizeof(value), "%s", com_token);
2120 if (!strcmp("wad", key)) // for HalfLife maps
2122 if (loadmodel->brush.ishlbsp)
2125 for (i = 0;i < (int)sizeof(value);i++)
2126 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2130 for (;i < (int)sizeof(value);i++)
2132 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2133 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2135 else if (value[i] == ';' || value[i] == 0)
2139 W_LoadTextureWadFile(&value[j], false);
2151 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2153 loadmodel->brush.entities = NULL;
2156 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2157 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2158 loadmodel->brush.entities[sb->cursize] = 0;
2159 if (loadmodel->brush.ishlbsp)
2160 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2164 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2168 int structsize = 12;
2170 if (sb->cursize % structsize)
2171 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2172 count = sb->cursize / structsize;
2173 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2175 loadmodel->brushq1.vertexes = out;
2176 loadmodel->brushq1.numvertexes = count;
2178 for ( i=0 ; i<count ; i++, out++)
2180 out->position[0] = MSG_ReadLittleFloat(sb);
2181 out->position[1] = MSG_ReadLittleFloat(sb);
2182 out->position[2] = MSG_ReadLittleFloat(sb);
2186 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2190 int structsize = (48+4*hullinfo->filehulls);
2192 if (sb->cursize % structsize)
2193 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2195 count = sb->cursize / structsize;
2196 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2198 loadmodel->brushq1.submodels = out;
2199 loadmodel->brush.numsubmodels = count;
2201 for (i = 0; i < count; i++, out++)
2203 // spread out the mins / maxs by a pixel
2204 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2205 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2206 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2207 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2208 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2209 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2210 out->origin[0] = MSG_ReadLittleFloat(sb);
2211 out->origin[1] = MSG_ReadLittleFloat(sb);
2212 out->origin[2] = MSG_ReadLittleFloat(sb);
2213 for (j = 0; j < hullinfo->filehulls; j++)
2214 out->headnode[j] = MSG_ReadLittleLong(sb);
2215 out->visleafs = MSG_ReadLittleLong(sb);
2216 out->firstface = MSG_ReadLittleLong(sb);
2217 out->numfaces = MSG_ReadLittleLong(sb);
2221 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2225 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2227 if (sb->cursize % structsize)
2228 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2229 count = sb->cursize / structsize;
2230 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2232 loadmodel->brushq1.edges = out;
2233 loadmodel->brushq1.numedges = count;
2235 for ( i=0 ; i<count ; i++, out++)
2237 if (loadmodel->brush.isbsp2)
2239 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2240 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2244 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2245 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2247 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2249 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);
2250 if(!loadmodel->brushq1.numvertexes)
2251 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2259 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2262 int i, j, k, count, miptex;
2263 int structsize = 40;
2265 if (sb->cursize % structsize)
2266 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2267 count = sb->cursize / structsize;
2268 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2270 loadmodel->brushq1.texinfo = out;
2271 loadmodel->brushq1.numtexinfo = count;
2273 for (i = 0;i < count;i++, out++)
2275 for (k = 0;k < 2;k++)
2276 for (j = 0;j < 4;j++)
2277 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2279 miptex = MSG_ReadLittleLong(sb);
2280 out->flags = MSG_ReadLittleLong(sb);
2282 out->texture = NULL;
2283 if (loadmodel->data_textures)
2285 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2286 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2288 out->texture = loadmodel->data_textures + miptex;
2290 if (out->flags & TEX_SPECIAL)
2292 // if texture chosen is NULL or the shader needs a lightmap,
2293 // force to notexture water shader
2294 if (out->texture == NULL)
2295 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2299 // if texture chosen is NULL, force to notexture
2300 if (out->texture == NULL)
2301 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2307 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2312 mins[0] = mins[1] = mins[2] = 9999;
2313 maxs[0] = maxs[1] = maxs[2] = -9999;
2315 for (i = 0;i < numverts;i++)
2317 for (j = 0;j < 3;j++, v++)
2327 #define MAX_SUBDIVPOLYTRIANGLES 4096
2328 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2330 static int subdivpolyverts, subdivpolytriangles;
2331 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2332 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2334 static int subdivpolylookupvert(vec3_t v)
2337 for (i = 0;i < subdivpolyverts;i++)
2338 if (subdivpolyvert[i][0] == v[0]
2339 && subdivpolyvert[i][1] == v[1]
2340 && subdivpolyvert[i][2] == v[2])
2342 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2343 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2344 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2345 return subdivpolyverts++;
2348 static void SubdividePolygon(int numverts, float *verts)
2350 int i, i1, i2, i3, f, b, c, p;
2351 vec3_t mins, maxs, front[256], back[256];
2352 float m, *pv, *cv, dist[256], frac;
2355 Host_Error("SubdividePolygon: ran out of verts in buffer");
2357 BoundPoly(numverts, verts, mins, maxs);
2359 for (i = 0;i < 3;i++)
2361 m = (mins[i] + maxs[i]) * 0.5;
2362 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2363 if (maxs[i] - m < 8)
2365 if (m - mins[i] < 8)
2369 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2370 dist[c] = cv[i] - m;
2373 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2377 VectorCopy(pv, front[f]);
2382 VectorCopy(pv, back[b]);
2385 if (dist[p] == 0 || dist[c] == 0)
2387 if ((dist[p] > 0) != (dist[c] > 0) )
2390 frac = dist[p] / (dist[p] - dist[c]);
2391 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2392 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2393 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2399 SubdividePolygon(f, front[0]);
2400 SubdividePolygon(b, back[0]);
2404 i1 = subdivpolylookupvert(verts);
2405 i2 = subdivpolylookupvert(verts + 3);
2406 for (i = 2;i < numverts;i++)
2408 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2410 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2414 i3 = subdivpolylookupvert(verts + i * 3);
2415 subdivpolyindex[subdivpolytriangles][0] = i1;
2416 subdivpolyindex[subdivpolytriangles][1] = i2;
2417 subdivpolyindex[subdivpolytriangles][2] = i3;
2419 subdivpolytriangles++;
2423 //Breaks a polygon up along axial 64 unit
2424 //boundaries so that turbulent and sky warps
2425 //can be done reasonably.
2426 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2432 subdivpolytriangles = 0;
2433 subdivpolyverts = 0;
2434 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2435 if (subdivpolytriangles < 1)
2436 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2438 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2439 mesh->num_vertices = subdivpolyverts;
2440 mesh->num_triangles = subdivpolytriangles;
2441 mesh->vertex = (surfvertex_t *)(mesh + 1);
2442 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2443 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2445 for (i = 0;i < mesh->num_triangles;i++)
2446 for (j = 0;j < 3;j++)
2447 mesh->index[i*3+j] = subdivpolyindex[i][j];
2449 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2451 VectorCopy(subdivpolyvert[i], v->v);
2452 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2453 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2458 extern cvar_t gl_max_lightmapsize;
2459 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2461 msurface_t *surface;
2462 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2463 float texmins[2], texmaxs[2], val;
2464 rtexture_t *lightmaptexture, *deluxemaptexture;
2466 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2468 if (sb->cursize % structsize)
2469 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2470 count = sb->cursize / structsize;
2471 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2472 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2474 loadmodel->num_surfaces = count;
2476 loadmodel->brushq1.firstrender = true;
2477 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2481 for (surfacenum = 0;surfacenum < count;surfacenum++)
2483 if (loadmodel->brush.isbsp2)
2484 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2486 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2487 totalverts += numedges;
2488 totaltris += numedges - 2;
2491 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2493 lightmaptexture = NULL;
2494 deluxemaptexture = r_texture_blanknormalmap;
2496 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2497 totallightmapsamples = 0;
2501 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2503 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2504 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2505 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2506 firstedge = MSG_ReadLittleLong(sb);
2507 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2508 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2509 for (i = 0;i < MAXLIGHTMAPS;i++)
2510 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2511 lightmapoffset = MSG_ReadLittleLong(sb);
2513 // FIXME: validate edges, texinfo, etc?
2514 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)
2515 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2516 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2517 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2518 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2519 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2521 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2522 surface->texture = surface->lightmapinfo->texinfo->texture;
2524 //surface->flags = surface->texture->flags;
2525 //if (LittleShort(in->side))
2526 // surface->flags |= SURF_PLANEBACK;
2527 //surface->plane = loadmodel->brush.data_planes + planenum;
2529 surface->num_firstvertex = totalverts;
2530 surface->num_vertices = numedges;
2531 surface->num_firsttriangle = totaltris;
2532 surface->num_triangles = numedges - 2;
2533 totalverts += numedges;
2534 totaltris += numedges - 2;
2536 // convert edges back to a normal polygon
2537 for (i = 0;i < surface->num_vertices;i++)
2539 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2541 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2543 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2545 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2546 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2547 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2548 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2549 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2550 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2551 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2552 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2555 for (i = 0;i < surface->num_triangles;i++)
2557 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2558 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2559 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2562 // compile additional data about the surface geometry
2563 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);
2564 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);
2565 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2567 // generate surface extents information
2568 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2569 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2570 for (i = 1;i < surface->num_vertices;i++)
2572 for (j = 0;j < 2;j++)
2574 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2575 texmins[j] = min(texmins[j], val);
2576 texmaxs[j] = max(texmaxs[j], val);
2579 for (i = 0;i < 2;i++)
2581 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2582 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2585 smax = surface->lightmapinfo->extents[0] >> 4;
2586 tmax = surface->lightmapinfo->extents[1] >> 4;
2587 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2588 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2591 surface->lightmaptexture = NULL;
2592 surface->deluxemaptexture = r_texture_blanknormalmap;
2593 if (lightmapoffset == -1)
2595 surface->lightmapinfo->samples = NULL;
2597 // give non-lightmapped water a 1x white lightmap
2598 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2600 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2601 surface->lightmapinfo->styles[0] = 0;
2602 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2606 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2607 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2608 else // LordHavoc: white lighting (bsp version 29)
2610 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2611 if (loadmodel->brushq1.nmaplightdata)
2612 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2615 // check if we should apply a lightmap to this
2616 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2618 if (ssize > 256 || tsize > 256)
2619 Host_Error("Bad surface extents");
2621 if (lightmapsize < ssize)
2622 lightmapsize = ssize;
2623 if (lightmapsize < tsize)
2624 lightmapsize = tsize;
2626 totallightmapsamples += ssize*tsize;
2628 // force lightmap upload on first time seeing the surface
2630 // additionally this is used by the later code to see if a
2631 // lightmap is needed on this surface (rather than duplicating the
2633 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2634 loadmodel->lit = true;
2638 // small maps (such as ammo boxes especially) don't need big lightmap
2639 // textures, so this code tries to guess a good size based on
2640 // totallightmapsamples (size of the lightmaps lump basically), as well as
2641 // trying to max out the size if there is a lot of lightmap data to store
2642 // additionally, never choose a lightmapsize that is smaller than the
2643 // largest surface encountered (as it would fail)
2645 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2648 // now that we've decided the lightmap texture size, we can do the rest
2649 if (cls.state != ca_dedicated)
2651 int stainmapsize = 0;
2652 mod_alloclightmap_state_t allocState;
2654 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2655 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2657 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2658 float u, v, ubase, vbase, uscale, vscale;
2660 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2663 smax = surface->lightmapinfo->extents[0] >> 4;
2664 tmax = surface->lightmapinfo->extents[1] >> 4;
2665 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2666 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2667 stainmapsize += ssize * tsize * 3;
2669 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2671 // allocate a texture pool if we need it
2672 if (loadmodel->texturepool == NULL)
2673 loadmodel->texturepool = R_AllocTexturePool();
2674 // could not find room, make a new lightmap
2675 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2676 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2677 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2678 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);
2679 if (loadmodel->brushq1.nmaplightdata)
2680 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);
2682 Mod_AllocLightmap_Reset(&allocState);
2683 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2685 surface->lightmaptexture = lightmaptexture;
2686 surface->deluxemaptexture = deluxemaptexture;
2687 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2688 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2690 uscale = 1.0f / (float)lightmapsize;
2691 vscale = 1.0f / (float)lightmapsize;
2692 ubase = lightmapx * uscale;
2693 vbase = lightmapy * vscale;
2695 for (i = 0;i < surface->num_vertices;i++)
2697 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);
2698 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);
2699 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2700 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2701 // LordHavoc: calc lightmap data offset for vertex lighting to use
2704 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2708 if (cl_stainmaps.integer)
2710 // allocate stainmaps for permanent marks on walls and clear white
2711 unsigned char *stainsamples = NULL;
2712 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2713 memset(stainsamples, 255, stainmapsize);
2715 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2717 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2719 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2720 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2721 surface->lightmapinfo->stainsamples = stainsamples;
2722 stainsamples += ssize * tsize * 3;
2727 // generate ushort elements array if possible
2728 if (loadmodel->surfmesh.data_element3s)
2729 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2730 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2733 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2736 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2737 node->parent = parent;
2740 // this is a node, recurse to children
2741 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2742 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2743 // combine supercontents of children
2744 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2749 mleaf_t *leaf = (mleaf_t *)node;
2750 // if this is a leaf, calculate supercontents mask from all collidable
2751 // primitives in the leaf (brushes and collision surfaces)
2752 // also flag if the leaf contains any collision surfaces
2753 leaf->combinedsupercontents = 0;
2754 // combine the supercontents values of all brushes in this leaf
2755 for (j = 0;j < leaf->numleafbrushes;j++)
2756 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2757 // check if this leaf contains any collision surfaces (q3 patches)
2758 for (j = 0;j < leaf->numleafsurfaces;j++)
2760 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2761 if (surface->num_collisiontriangles)
2763 leaf->containscollisionsurfaces = true;
2764 leaf->combinedsupercontents |= surface->texture->supercontents;
2770 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2772 int i, j, count, p, child[2];
2774 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2776 if (sb->cursize % structsize)
2777 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2778 count = sb->cursize / structsize;
2780 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2781 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2783 loadmodel->brush.data_nodes = out;
2784 loadmodel->brush.num_nodes = count;
2786 for ( i=0 ; i<count ; i++, out++)
2788 p = MSG_ReadLittleLong(sb);
2789 out->plane = loadmodel->brush.data_planes + p;
2791 if (loadmodel->brush.isbsp2rmqe)
2793 child[0] = MSG_ReadLittleLong(sb);
2794 child[1] = MSG_ReadLittleLong(sb);
2795 out->mins[0] = MSG_ReadLittleShort(sb);
2796 out->mins[1] = MSG_ReadLittleShort(sb);
2797 out->mins[2] = MSG_ReadLittleShort(sb);
2798 out->maxs[0] = MSG_ReadLittleShort(sb);
2799 out->maxs[1] = MSG_ReadLittleShort(sb);
2800 out->maxs[2] = MSG_ReadLittleShort(sb);
2801 out->firstsurface = MSG_ReadLittleLong(sb);
2802 out->numsurfaces = MSG_ReadLittleLong(sb);
2804 else if (loadmodel->brush.isbsp2)
2806 child[0] = MSG_ReadLittleLong(sb);
2807 child[1] = MSG_ReadLittleLong(sb);
2808 out->mins[0] = MSG_ReadLittleFloat(sb);
2809 out->mins[1] = MSG_ReadLittleFloat(sb);
2810 out->mins[2] = MSG_ReadLittleFloat(sb);
2811 out->maxs[0] = MSG_ReadLittleFloat(sb);
2812 out->maxs[1] = MSG_ReadLittleFloat(sb);
2813 out->maxs[2] = MSG_ReadLittleFloat(sb);
2814 out->firstsurface = MSG_ReadLittleLong(sb);
2815 out->numsurfaces = MSG_ReadLittleLong(sb);
2819 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2820 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2821 if (child[0] >= count)
2823 if (child[1] >= count)
2826 out->mins[0] = MSG_ReadLittleShort(sb);
2827 out->mins[1] = MSG_ReadLittleShort(sb);
2828 out->mins[2] = MSG_ReadLittleShort(sb);
2829 out->maxs[0] = MSG_ReadLittleShort(sb);
2830 out->maxs[1] = MSG_ReadLittleShort(sb);
2831 out->maxs[2] = MSG_ReadLittleShort(sb);
2833 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2834 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2837 for (j=0 ; j<2 ; j++)
2839 // LordHavoc: this code supports broken bsp files produced by
2840 // arguire qbsp which can produce more than 32768 nodes, any value
2841 // below count is assumed to be a node number, any other value is
2842 // assumed to be a leaf number
2846 if (p < loadmodel->brush.num_nodes)
2847 out->children[j] = loadmodel->brush.data_nodes + p;
2850 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2851 // map it to the solid leaf
2852 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2857 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2859 if (p < loadmodel->brush.num_leafs)
2860 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2863 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2864 // map it to the solid leaf
2865 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2871 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2874 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2877 int i, j, count, p, firstmarksurface, nummarksurfaces;
2878 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2880 if (sb->cursize % structsize)
2881 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2882 count = sb->cursize / structsize;
2883 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2885 loadmodel->brush.data_leafs = out;
2886 loadmodel->brush.num_leafs = count;
2887 // get visleafs from the submodel data
2888 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2889 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2890 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2891 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2893 // FIXME: this function could really benefit from some error checking
2894 for ( i=0 ; i<count ; i++, out++)
2896 out->contents = MSG_ReadLittleLong(sb);
2898 out->clusterindex = i - 1;
2899 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2900 out->clusterindex = -1;
2902 p = MSG_ReadLittleLong(sb);
2903 // ignore visofs errors on leaf 0 (solid)
2904 if (p >= 0 && out->clusterindex >= 0)
2906 if (p >= loadmodel->brushq1.num_compressedpvs)
2907 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2909 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);
2912 if (loadmodel->brush.isbsp2rmqe)
2914 out->mins[0] = MSG_ReadLittleShort(sb);
2915 out->mins[1] = MSG_ReadLittleShort(sb);
2916 out->mins[2] = MSG_ReadLittleShort(sb);
2917 out->maxs[0] = MSG_ReadLittleShort(sb);
2918 out->maxs[1] = MSG_ReadLittleShort(sb);
2919 out->maxs[2] = MSG_ReadLittleShort(sb);
2921 firstmarksurface = MSG_ReadLittleLong(sb);
2922 nummarksurfaces = MSG_ReadLittleLong(sb);
2924 else if (loadmodel->brush.isbsp2)
2926 out->mins[0] = MSG_ReadLittleFloat(sb);
2927 out->mins[1] = MSG_ReadLittleFloat(sb);
2928 out->mins[2] = MSG_ReadLittleFloat(sb);
2929 out->maxs[0] = MSG_ReadLittleFloat(sb);
2930 out->maxs[1] = MSG_ReadLittleFloat(sb);
2931 out->maxs[2] = MSG_ReadLittleFloat(sb);
2933 firstmarksurface = MSG_ReadLittleLong(sb);
2934 nummarksurfaces = MSG_ReadLittleLong(sb);
2938 out->mins[0] = MSG_ReadLittleShort(sb);
2939 out->mins[1] = MSG_ReadLittleShort(sb);
2940 out->mins[2] = MSG_ReadLittleShort(sb);
2941 out->maxs[0] = MSG_ReadLittleShort(sb);
2942 out->maxs[1] = MSG_ReadLittleShort(sb);
2943 out->maxs[2] = MSG_ReadLittleShort(sb);
2945 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2946 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2949 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2951 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2952 out->numleafsurfaces = nummarksurfaces;
2956 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2957 out->firstleafsurface = NULL;
2958 out->numleafsurfaces = 0;
2961 for (j = 0;j < 4;j++)
2962 out->ambient_sound_level[j] = MSG_ReadByte(sb);
2966 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2970 const unsigned char *pvs;
2971 // if there's no vis data, assume supported (because everything is visible all the time)
2972 if (!loadmodel->brush.data_pvsclusters)
2974 // check all liquid leafs to see if they can see into empty leafs, if any
2975 // can we can assume this map supports r_wateralpha
2976 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2978 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2980 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2981 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2982 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2989 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
2994 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
2996 if (sb->cursize % structsize)
2997 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2998 count = sb->cursize / structsize;
2999 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3001 loadmodel->brushq1.clipnodes = out;
3002 loadmodel->brushq1.numclipnodes = count;
3004 for (i = 1; i < MAX_MAP_HULLS; i++)
3006 hull = &loadmodel->brushq1.hulls[i];
3007 hull->clipnodes = out;
3008 hull->firstclipnode = 0;
3009 hull->lastclipnode = count-1;
3010 hull->planes = loadmodel->brush.data_planes;
3011 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3012 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3013 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3014 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3015 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3016 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3017 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3020 for (i=0 ; i<count ; i++, out++)
3022 out->planenum = MSG_ReadLittleLong(sb);
3023 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3024 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3025 if (loadmodel->brush.isbsp2)
3027 out->children[0] = MSG_ReadLittleLong(sb);
3028 out->children[1] = MSG_ReadLittleLong(sb);
3029 if (out->children[0] >= count)
3030 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3031 if (out->children[1] >= count)
3032 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3036 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3037 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3038 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3039 if (out->children[0] >= count)
3040 out->children[0] -= 65536;
3041 if (out->children[1] >= count)
3042 out->children[1] -= 65536;
3047 //Duplicate the drawing hull structure as a clipping hull
3048 static void Mod_Q1BSP_MakeHull0(void)
3055 hull = &loadmodel->brushq1.hulls[0];
3057 in = loadmodel->brush.data_nodes;
3058 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3060 hull->clipnodes = out;
3061 hull->firstclipnode = 0;
3062 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3063 hull->planes = loadmodel->brush.data_planes;
3065 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3067 out->planenum = in->plane - loadmodel->brush.data_planes;
3068 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3069 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3073 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3076 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3078 if (sb->cursize % structsize)
3079 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3080 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3081 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3083 if (loadmodel->brush.isbsp2)
3085 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3087 j = MSG_ReadLittleLong(sb);
3088 if (j < 0 || j >= loadmodel->num_surfaces)
3089 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3090 loadmodel->brush.data_leafsurfaces[i] = j;
3095 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3097 j = (unsigned short) MSG_ReadLittleShort(sb);
3098 if (j >= loadmodel->num_surfaces)
3099 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3100 loadmodel->brush.data_leafsurfaces[i] = j;
3105 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3110 if (sb->cursize % structsize)
3111 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3112 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3113 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3115 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3116 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3120 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3124 int structsize = 20;
3126 if (sb->cursize % structsize)
3127 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3128 loadmodel->brush.num_planes = sb->cursize / structsize;
3129 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3131 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3133 out->normal[0] = MSG_ReadLittleFloat(sb);
3134 out->normal[1] = MSG_ReadLittleFloat(sb);
3135 out->normal[2] = MSG_ReadLittleFloat(sb);
3136 out->dist = MSG_ReadLittleFloat(sb);
3137 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3142 static void Mod_Q1BSP_LoadMapBrushes(void)
3146 int submodel, numbrushes;
3147 qboolean firstbrush;
3148 char *text, *maptext;
3149 char mapfilename[MAX_QPATH];
3150 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3151 strlcat (mapfilename, ".map", sizeof (mapfilename));
3152 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3156 if (!COM_ParseToken_Simple(&data, false, false, true))
3161 if (!COM_ParseToken_Simple(&data, false, false, true))
3163 if (com_token[0] != '{')
3169 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3172 if (!COM_ParseToken_Simple(&data, false, false, true))
3174 if (com_token[0] == '}')
3175 break; // end of entity
3176 if (com_token[0] == '{')
3183 if (submodel > loadmodel->brush.numsubmodels)
3185 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3189 model = loadmodel->brush.submodels[submodel];
3196 if (!COM_ParseToken_Simple(&data, false, false, true))
3198 if (com_token[0] == '}')
3199 break; // end of brush
3200 // each brush face should be this format:
3201 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3202 // FIXME: support hl .map format
3203 for (pointnum = 0;pointnum < 3;pointnum++)
3205 COM_ParseToken_Simple(&data, false, false, true);
3206 for (componentnum = 0;componentnum < 3;componentnum++)
3208 COM_ParseToken_Simple(&data, false, false, true);
3209 point[pointnum][componentnum] = atof(com_token);
3211 COM_ParseToken_Simple(&data, false, false, true);
3213 COM_ParseToken_Simple(&data, false, false, true);
3214 strlcpy(facetexture, com_token, sizeof(facetexture));
3215 COM_ParseToken_Simple(&data, false, false, true);
3216 //scroll_s = atof(com_token);
3217 COM_ParseToken_Simple(&data, false, false, true);
3218 //scroll_t = atof(com_token);
3219 COM_ParseToken_Simple(&data, false, false, true);
3220 //rotate = atof(com_token);
3221 COM_ParseToken_Simple(&data, false, false, true);
3222 //scale_s = atof(com_token);
3223 COM_ParseToken_Simple(&data, false, false, true);
3224 //scale_t = atof(com_token);
3225 TriangleNormal(point[0], point[1], point[2], planenormal);
3226 VectorNormalizeDouble(planenormal);
3227 planedist = DotProduct(point[0], planenormal);
3228 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3238 #define MAX_PORTALPOINTS 64
3240 typedef struct portal_s
3243 mnode_t *nodes[2]; // [0] = front side of plane
3244 struct portal_s *next[2];
3246 double points[3*MAX_PORTALPOINTS];
3247 struct portal_s *chain; // all portals are linked into a list
3251 static memexpandablearray_t portalarray;
3253 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3255 // process only nodes (leafs already had their box calculated)
3259 // calculate children first
3260 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3261 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3263 // make combined bounding box from children
3264 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3265 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3266 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3267 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3268 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3269 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3272 static void Mod_Q1BSP_FinalizePortals(void)
3274 int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3278 mleaf_t *leaf, *endleaf;
3280 // tally up portal and point counts and recalculate bounding boxes for all
3281 // leafs (because qbsp is very sloppy)
3282 leaf = loadmodel->brush.data_leafs;
3283 endleaf = leaf + loadmodel->brush.num_leafs;
3284 if (mod_recalculatenodeboxes.integer)
3286 for (;leaf < endleaf;leaf++)
3288 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3289 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3294 for (portalindex = 0;portalindex < portalrange;portalindex++)
3296 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3299 // note: this check must match the one below or it will usually corrupt memory
3300 // 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
3301 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3304 numpoints += p->numpoints * 2;
3307 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3308 loadmodel->brush.num_portals = numportals;
3309 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3310 loadmodel->brush.num_portalpoints = numpoints;
3311 // clear all leaf portal chains
3312 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3313 loadmodel->brush.data_leafs[i].portals = NULL;
3314 // process all portals in the global portal chain, while freeing them
3315 portal = loadmodel->brush.data_portals;
3316 point = loadmodel->brush.data_portalpoints;
3317 for (portalindex = 0;portalindex < portalrange;portalindex++)
3319 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3322 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3324 // note: this check must match the one above or it will usually corrupt memory
3325 // 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
3326 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3328 // first make the back to front portal(forward portal)
3329 portal->points = point;
3330 portal->numpoints = p->numpoints;
3331 portal->plane.dist = p->plane.dist;
3332 VectorCopy(p->plane.normal, portal->plane.normal);
3333 portal->here = (mleaf_t *)p->nodes[1];
3334 portal->past = (mleaf_t *)p->nodes[0];
3336 for (j = 0;j < portal->numpoints;j++)
3338 VectorCopy(p->points + j*3, point->position);
3341 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3342 PlaneClassify(&portal->plane);
3344 // link into leaf's portal chain
3345 portal->next = portal->here->portals;
3346 portal->here->portals = portal;
3348 // advance to next portal
3351 // then make the front to back portal(backward portal)
3352 portal->points = point;
3353 portal->numpoints = p->numpoints;
3354 portal->plane.dist = -p->plane.dist;
3355 VectorNegate(p->plane.normal, portal->plane.normal);
3356 portal->here = (mleaf_t *)p->nodes[0];
3357 portal->past = (mleaf_t *)p->nodes[1];
3359 for (j = portal->numpoints - 1;j >= 0;j--)
3361 VectorCopy(p->points + j*3, point->position);
3364 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3365 PlaneClassify(&portal->plane);
3367 // link into leaf's portal chain
3368 portal->next = portal->here->portals;
3369 portal->here->portals = portal;
3371 // advance to next portal
3374 // add the portal's polygon points to the leaf bounding boxes
3375 if (mod_recalculatenodeboxes.integer)
3377 for (i = 0;i < 2;i++)
3379 leaf = (mleaf_t *)p->nodes[i];
3380 for (j = 0;j < p->numpoints;j++)
3382 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3383 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3384 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3385 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3386 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3387 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3393 // now recalculate the node bounding boxes from the leafs
3394 if (mod_recalculatenodeboxes.integer)
3395 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3403 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3406 Host_Error("AddPortalToNodes: NULL front node");
3408 Host_Error("AddPortalToNodes: NULL back node");
3409 if (p->nodes[0] || p->nodes[1])
3410 Host_Error("AddPortalToNodes: already included");
3411 // 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
3413 p->nodes[0] = front;
3414 p->next[0] = (portal_t *)front->portals;
3415 front->portals = (mportal_t *)p;
3418 p->next[1] = (portal_t *)back->portals;
3419 back->portals = (mportal_t *)p;
3424 RemovePortalFromNode
3427 static void RemovePortalFromNodes(portal_t *portal)
3431 void **portalpointer;
3433 for (i = 0;i < 2;i++)
3435 node = portal->nodes[i];
3437 portalpointer = (void **) &node->portals;
3440 t = (portal_t *)*portalpointer;
3442 Host_Error("RemovePortalFromNodes: portal not in leaf");
3446 if (portal->nodes[0] == node)
3448 *portalpointer = portal->next[0];
3449 portal->nodes[0] = NULL;
3451 else if (portal->nodes[1] == node)
3453 *portalpointer = portal->next[1];
3454 portal->nodes[1] = NULL;
3457 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3461 if (t->nodes[0] == node)
3462 portalpointer = (void **) &t->next[0];
3463 else if (t->nodes[1] == node)
3464 portalpointer = (void **) &t->next[1];
3466 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3471 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3472 static double *portalpointsbuffer;
3473 static int portalpointsbufferoffset;
3474 static int portalpointsbuffersize;
3475 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3478 mnode_t *front, *back, *other_node;
3479 mplane_t clipplane, *plane;
3480 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3481 int numfrontpoints, numbackpoints;
3482 double *frontpoints, *backpoints;
3484 // if a leaf, we're done
3488 // get some space for our clipping operations to use
3489 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3491 portalpointsbuffersize = portalpointsbufferoffset * 2;
3492 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3494 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3495 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3496 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3497 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3499 plane = node->plane;
3501 front = node->children[0];
3502 back = node->children[1];
3504 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3506 // create the new portal by generating a polygon for the node plane,
3507 // and clipping it by all of the other portals(which came from nodes above this one)
3508 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3509 nodeportal->plane = *plane;
3511 // 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)
3512 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);
3513 nodeportal->numpoints = 4;
3514 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3515 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3517 clipplane = portal->plane;
3518 if (portal->nodes[0] == portal->nodes[1])
3519 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3520 if (portal->nodes[0] == node)
3522 else if (portal->nodes[1] == node)
3524 clipplane.dist = -clipplane.dist;
3525 VectorNegate(clipplane.normal, clipplane.normal);
3530 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3531 side = 0; // hush warning
3534 for (i = 0;i < nodeportal->numpoints*3;i++)
3535 frontpoints[i] = nodeportal->points[i];
3536 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);
3537 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3541 if (nodeportal->numpoints < 3)
3543 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3544 nodeportal->numpoints = 0;
3546 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3548 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3549 nodeportal->numpoints = 0;
3552 AddPortalToNodes(nodeportal, front, back);
3554 // split the portals of this node along this node's plane and assign them to the children of this node
3555 // (migrating the portals downward through the tree)
3556 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3558 if (portal->nodes[0] == portal->nodes[1])
3559 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3560 if (portal->nodes[0] == node)
3562 else if (portal->nodes[1] == node)
3566 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3567 side = 0; // hush warning
3569 nextportal = portal->next[side];
3570 if (!portal->numpoints)
3573 other_node = portal->nodes[!side];
3574 RemovePortalFromNodes(portal);
3576 // cut the portal into two portals, one on each side of the node plane
3577 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);
3579 if (!numfrontpoints)
3582 AddPortalToNodes(portal, back, other_node);
3584 AddPortalToNodes(portal, other_node, back);
3590 AddPortalToNodes(portal, front, other_node);
3592 AddPortalToNodes(portal, other_node, front);
3596 // the portal is split
3597 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3598 temp = splitportal->chain;
3599 *splitportal = *portal;
3600 splitportal->chain = temp;
3601 for (i = 0;i < numbackpoints*3;i++)
3602 splitportal->points[i] = backpoints[i];
3603 splitportal->numpoints = numbackpoints;
3604 for (i = 0;i < numfrontpoints*3;i++)
3605 portal->points[i] = frontpoints[i];
3606 portal->numpoints = numfrontpoints;
3610 AddPortalToNodes(portal, front, other_node);
3611 AddPortalToNodes(splitportal, back, other_node);
3615 AddPortalToNodes(portal, other_node, front);
3616 AddPortalToNodes(splitportal, other_node, back);
3620 Mod_Q1BSP_RecursiveNodePortals(front);
3621 Mod_Q1BSP_RecursiveNodePortals(back);
3623 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3626 static void Mod_Q1BSP_MakePortals(void)
3628 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3629 portalpointsbufferoffset = 0;
3630 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3631 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3632 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3633 Mem_Free(portalpointsbuffer);
3634 portalpointsbuffer = NULL;
3635 portalpointsbufferoffset = 0;
3636 portalpointsbuffersize = 0;
3637 Mod_Q1BSP_FinalizePortals();
3638 Mem_ExpandableArray_FreeArray(&portalarray);
3641 //Returns PVS data for a given point
3642 //(note: can return NULL)
3643 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3646 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3648 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3649 if (((mleaf_t *)node)->clusterindex >= 0)
3650 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3655 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)
3659 float d = PlaneDiff(org, node->plane);
3661 node = node->children[0];
3662 else if (d < -radius)
3663 node = node->children[1];
3666 // go down both sides
3667 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3668 node = node->children[1];
3671 // if this leaf is in a cluster, accumulate the pvs bits
3672 if (((mleaf_t *)node)->clusterindex >= 0)
3675 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3676 for (i = 0;i < pvsbytes;i++)
3677 pvsbuffer[i] |= pvs[i];
3681 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3682 //of the given point.
3683 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3685 int bytes = model->brush.num_pvsclusterbytes;
3686 bytes = min(bytes, pvsbufferlength);
3687 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3689 memset(pvsbuffer, 0xFF, bytes);
3693 memset(pvsbuffer, 0, bytes);
3694 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3698 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3703 VectorSubtract(inmaxs, inmins, size);
3704 if (cmodel->brush.ishlbsp)
3707 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3708 else if (size[0] <= 32)
3710 if (size[2] < 54) // pick the nearest of 36 or 72
3711 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3713 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3716 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3721 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3722 else if (size[0] <= 32)
3723 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3725 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3727 VectorCopy(inmins, outmins);
3728 VectorAdd(inmins, hull->clip_size, outmaxs);
3731 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3734 int numshadowmeshtriangles = 0;
3735 msurface_t *surface;
3736 if (cls.state == ca_dedicated)
3738 // make a single combined shadow mesh to allow optimized shadow volume creation
3740 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3742 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3743 numshadowmeshtriangles += surface->num_triangles;
3745 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3746 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3747 if (surface->num_triangles > 0)
3748 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));
3749 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3750 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3751 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3753 return numshadowmeshtriangles;
3756 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);
3758 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3761 sizebuf_t lumpsb[HEADER_LUMPS];
3763 float dist, modelyawradius, modelradius;
3764 msurface_t *surface;
3765 hullinfo_t hullinfo;
3766 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3767 model_brush_lightstyleinfo_t styleinfo[256];
3768 unsigned char *datapointer;
3771 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3773 mod->type = mod_brushq1;
3775 mod->brush.isbsp2 = false;
3776 mod->brush.ishlbsp = false;
3777 i = MSG_ReadLittleLong(&sb);
3781 mod->modeldatatypestring = "Q1BSP";
3784 mod->brush.ishlbsp = true;
3785 mod->modeldatatypestring = "HLBSP";
3787 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3788 mod->brush.isbsp2 = true;
3789 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3790 mod->modeldatatypestring = "Q1BSP2rmqe";
3792 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3793 mod->brush.isbsp2 = true;
3794 mod->modeldatatypestring = "Q1BSP2";
3797 mod->modeldatatypestring = "Unknown BSP";
3798 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);
3802 // fill in hull info
3803 VectorClear (hullinfo.hullsizes[0][0]);
3804 VectorClear (hullinfo.hullsizes[0][1]);
3805 if (mod->brush.ishlbsp)
3807 hullinfo.filehulls = 4;
3808 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3809 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3810 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3811 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3812 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3813 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3817 hullinfo.filehulls = 4;
3818 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3819 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3820 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3821 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3825 for (i = 0; i < HEADER_LUMPS; i++)
3827 int offset = MSG_ReadLittleLong(&sb);
3828 int size = MSG_ReadLittleLong(&sb);
3829 if (offset < 0 || offset + size > sb.cursize)
3830 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);
3831 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3834 mod->soundfromcenter = true;
3835 mod->TraceBox = Mod_Q1BSP_TraceBox;
3836 mod->TraceLine = Mod_Q1BSP_TraceLine;
3837 mod->TracePoint = Mod_Q1BSP_TracePoint;
3838 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3839 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3840 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3841 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3842 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3843 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3844 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3845 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3846 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3847 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3848 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3849 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3850 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3851 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3852 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3853 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3854 mod->Draw = R_Q1BSP_Draw;
3855 mod->DrawDepth = R_Q1BSP_DrawDepth;
3856 mod->DrawDebug = R_Q1BSP_DrawDebug;
3857 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3858 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3859 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3860 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3861 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3862 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3863 mod->DrawLight = R_Q1BSP_DrawLight;
3867 mod->brush.qw_md4sum = 0;
3868 mod->brush.qw_md4sum2 = 0;
3869 for (i = 0;i < HEADER_LUMPS;i++)
3872 if (i == LUMP_ENTITIES)
3874 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3875 mod->brush.qw_md4sum ^= LittleLong(temp);
3876 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3878 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3881 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3882 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3883 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3884 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3885 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3886 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3887 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3888 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3889 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3890 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3891 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3892 // load submodels before leafs because they contain the number of vis leafs
3893 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3894 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3895 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3896 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3898 for (i = 0; i < HEADER_LUMPS; i++)
3899 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3900 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3902 // check if the map supports transparent water rendering
3903 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3905 if (mod->brushq1.data_compressedpvs)
3906 Mem_Free(mod->brushq1.data_compressedpvs);
3907 mod->brushq1.data_compressedpvs = NULL;
3908 mod->brushq1.num_compressedpvs = 0;
3910 Mod_Q1BSP_MakeHull0();
3911 if (mod_bsp_portalize.integer)
3912 Mod_Q1BSP_MakePortals();
3914 mod->numframes = 2; // regular and alternate animation
3917 // make a single combined shadow mesh to allow optimized shadow volume creation
3918 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3920 if (loadmodel->brush.numsubmodels)
3921 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3923 // LordHavoc: to clear the fog around the original quake submodel code, I
3925 // first of all, some background info on the submodels:
3926 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3927 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3928 // now the weird for loop itself:
3929 // the loop functions in an odd way, on each iteration it sets up the
3930 // current 'mod' model (which despite the confusing code IS the model of
3931 // the number i), at the end of the loop it duplicates the model to become
3932 // the next submodel, and loops back to set up the new submodel.
3934 // LordHavoc: now the explanation of my sane way (which works identically):
3935 // set up the world model, then on each submodel copy from the world model
3936 // and set up the submodel with the respective model info.
3937 totalstylesurfaces = 0;
3939 for (i = 0;i < mod->brush.numsubmodels;i++)
3941 memset(stylecounts, 0, sizeof(stylecounts));
3942 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3944 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3945 for (j = 0;j < MAXLIGHTMAPS;j++)
3946 stylecounts[surface->lightmapinfo->styles[j]]++;
3948 for (k = 0;k < 255;k++)
3952 totalstylesurfaces += stylecounts[k];
3955 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3956 for (i = 0;i < mod->brush.numsubmodels;i++)
3958 // LordHavoc: this code was originally at the end of this loop, but
3959 // has been transformed to something more readable at the start here.
3964 // duplicate the basic information
3965 dpsnprintf(name, sizeof(name), "*%i", i);
3966 mod = Mod_FindName(name, loadmodel->name);
3967 // copy the base model to this one
3969 // rename the clone back to its proper name
3970 strlcpy(mod->name, name, sizeof(mod->name));
3971 mod->brush.parentmodel = loadmodel;
3972 // textures and memory belong to the main model
3973 mod->texturepool = NULL;
3974 mod->mempool = NULL;
3975 mod->brush.GetPVS = NULL;
3976 mod->brush.FatPVS = NULL;
3977 mod->brush.BoxTouchingPVS = NULL;
3978 mod->brush.BoxTouchingLeafPVS = NULL;
3979 mod->brush.BoxTouchingVisibleLeafs = NULL;
3980 mod->brush.FindBoxClusters = NULL;
3981 mod->brush.LightPoint = NULL;
3982 mod->brush.AmbientSoundLevelsForPoint = NULL;
3985 mod->brush.submodel = i;
3987 if (loadmodel->brush.submodels)
3988 loadmodel->brush.submodels[i] = mod;
3990 bm = &mod->brushq1.submodels[i];
3992 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3993 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3995 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3996 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3999 mod->firstmodelsurface = bm->firstface;
4000 mod->nummodelsurfaces = bm->numfaces;
4002 // set node/leaf parents for this submodel
4003 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4005 // make the model surface list (used by shadowing/lighting)
4006 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4007 Mod_MakeSortedSurfaces(mod);
4009 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4010 // (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)
4011 VectorCopy(bm->mins, mod->normalmins);
4012 VectorCopy(bm->maxs, mod->normalmaxs);
4013 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4014 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4015 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4016 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4017 modelradius = modelyawradius + modelradius * modelradius;
4018 modelyawradius = sqrt(modelyawradius);
4019 modelradius = sqrt(modelradius);
4020 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4021 mod->yawmins[2] = mod->normalmins[2];
4022 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4023 mod->yawmaxs[2] = mod->normalmaxs[2];
4024 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4025 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4026 mod->radius = modelradius;
4027 mod->radius2 = modelradius * modelradius;
4029 // this gets altered below if sky or water is used
4030 mod->DrawSky = NULL;
4031 mod->DrawAddWaterPlanes = NULL;
4033 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4034 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4035 if (mod->nummodelsurfaces)
4037 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4038 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4040 if (j < mod->nummodelsurfaces)
4041 mod->DrawSky = R_Q1BSP_DrawSky;
4043 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4044 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4046 if (j < mod->nummodelsurfaces)
4047 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4049 // build lightstyle update chains
4050 // (used to rapidly mark lightmapupdateflags on many surfaces
4051 // when d_lightstylevalue changes)
4052 memset(stylecounts, 0, sizeof(stylecounts));
4053 for (k = 0;k < mod->nummodelsurfaces;k++)
4055 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4056 for (j = 0;j < MAXLIGHTMAPS;j++)
4057 stylecounts[surface->lightmapinfo->styles[j]]++;
4059 mod->brushq1.num_lightstyles = 0;
4060 for (k = 0;k < 255;k++)
4064 styleinfo[mod->brushq1.num_lightstyles].style = k;
4065 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4066 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4067 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4068 remapstyles[k] = mod->brushq1.num_lightstyles;
4069 mod->brushq1.num_lightstyles++;
4072 for (k = 0;k < mod->nummodelsurfaces;k++)
4074 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4075 for (j = 0;j < MAXLIGHTMAPS;j++)
4077 if (surface->lightmapinfo->styles[j] != 255)
4079 int r = remapstyles[surface->lightmapinfo->styles[j]];
4080 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4084 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4085 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4089 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4090 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4092 //mod->brushq1.num_visleafs = bm->visleafs;
4094 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4095 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4097 if (mod_q1bsp_polygoncollisions.integer)
4099 mod->collision_bih = mod->render_bih;
4100 // point traces and contents checks still use the bsp tree
4101 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4102 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4103 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4104 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4107 // generate VBOs and other shared data before cloning submodels
4111 Mod_Q1BSP_LoadMapBrushes();
4112 //Mod_Q1BSP_ProcessLightList();
4116 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);
4119 static void Mod_Q2BSP_LoadEntities(lump_t *l)
4123 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
4130 in = (void *)(mod_base + l->fileofs);
4131 if (l->filelen % sizeof(*in))
4132 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4133 count = l->filelen / sizeof(*in);
4134 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4137 loadmodel->num = count;
4139 for (i = 0;i < count;i++, in++, out++)
4145 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4152 in = (void *)(mod_base + l->fileofs);
4153 if (l->filelen % sizeof(*in))
4154 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4155 count = l->filelen / sizeof(*in);
4156 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4159 loadmodel->num = count;
4161 for (i = 0;i < count;i++, in++, out++)
4167 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4174 in = (void *)(mod_base + l->fileofs);
4175 if (l->filelen % sizeof(*in))
4176 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4177 count = l->filelen / sizeof(*in);
4178 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4181 loadmodel->num = count;
4183 for (i = 0;i < count;i++, in++, out++)
4189 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4196 in = (void *)(mod_base + l->fileofs);
4197 if (l->filelen % sizeof(*in))
4198 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4199 count = l->filelen / sizeof(*in);
4200 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4203 loadmodel->num = count;
4205 for (i = 0;i < count;i++, in++, out++)
4211 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
4218 in = (void *)(mod_base + l->fileofs);
4219 if (l->filelen % sizeof(*in))
4220 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
4221 count = l->filelen / sizeof(*in);
4222 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4225 loadmodel->num = count;
4227 for (i = 0;i < count;i++, in++, out++)
4233 static void Mod_Q2BSP_LoadFaces(lump_t *l)
4240 in = (void *)(mod_base + l->fileofs);
4241 if (l->filelen % sizeof(*in))
4242 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4243 count = l->filelen / sizeof(*in);
4244 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4247 loadmodel->num = count;
4249 for (i = 0;i < count;i++, in++, out++)
4255 static void Mod_Q2BSP_LoadLighting(lump_t *l)
4262 in = (void *)(mod_base + l->fileofs);
4263 if (l->filelen % sizeof(*in))
4264 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
4265 count = l->filelen / sizeof(*in);
4266 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4269 loadmodel->num = count;
4271 for (i = 0;i < count;i++, in++, out++)
4277 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
4284 in = (void *)(mod_base + l->fileofs);
4285 if (l->filelen % sizeof(*in))
4286 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4287 count = l->filelen / sizeof(*in);
4288 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4291 loadmodel->num = count;
4293 for (i = 0;i < count;i++, in++, out++)
4299 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
4306 in = (void *)(mod_base + l->fileofs);
4307 if (l->filelen % sizeof(*in))
4308 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4309 count = l->filelen / sizeof(*in);
4310 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4313 loadmodel->num = count;
4315 for (i = 0;i < count;i++, in++, out++)
4321 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
4328 in = (void *)(mod_base + l->fileofs);
4329 if (l->filelen % sizeof(*in))
4330 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4331 count = l->filelen / sizeof(*in);
4332 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4335 loadmodel->num = count;
4337 for (i = 0;i < count;i++, in++, out++)
4343 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4350 in = (void *)(mod_base + l->fileofs);
4351 if (l->filelen % sizeof(*in))
4352 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4353 count = l->filelen / sizeof(*in);
4354 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4357 loadmodel->num = count;
4359 for (i = 0;i < count;i++, in++, out++)
4365 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4372 in = (void *)(mod_base + l->fileofs);
4373 if (l->filelen % sizeof(*in))
4374 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4375 count = l->filelen / sizeof(*in);
4376 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4379 loadmodel->num = count;
4381 for (i = 0;i < count;i++, in++, out++)
4387 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4394 in = (void *)(mod_base + l->fileofs);
4395 if (l->filelen % sizeof(*in))
4396 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4397 count = l->filelen / sizeof(*in);
4398 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4401 loadmodel->num = count;
4403 for (i = 0;i < count;i++, in++, out++)
4409 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4416 in = (void *)(mod_base + l->fileofs);
4417 if (l->filelen % sizeof(*in))
4418 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4419 count = l->filelen / sizeof(*in);
4420 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4423 loadmodel->num = count;
4425 for (i = 0;i < count;i++, in++, out++)
4431 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4438 in = (void *)(mod_base + l->fileofs);
4439 if (l->filelen % sizeof(*in))
4440 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4441 count = l->filelen / sizeof(*in);
4442 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4445 loadmodel->num = count;
4447 for (i = 0;i < count;i++, in++, out++)
4453 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4460 in = (void *)(mod_base + l->fileofs);
4461 if (l->filelen % sizeof(*in))
4462 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4463 count = l->filelen / sizeof(*in);
4464 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4467 loadmodel->num = count;
4469 for (i = 0;i < count;i++, in++, out++)
4475 static void Mod_Q2BSP_LoadModels(lump_t *l)
4482 in = (void *)(mod_base + l->fileofs);
4483 if (l->filelen % sizeof(*in))
4484 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4485 count = l->filelen / sizeof(*in);
4486 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4489 loadmodel->num = count;
4491 for (i = 0;i < count;i++, in++, out++)
4497 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4500 q2dheader_t *header;
4502 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4504 mod->modeldatatypestring = "Q2BSP";
4506 mod->type = mod_brushq2;
4508 header = (q2dheader_t *)buffer;
4510 i = LittleLong(header->version);
4511 if (i != Q2BSPVERSION)
4512 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4514 mod_base = (unsigned char *)header;
4516 // swap all the lumps
4517 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4518 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4520 mod->brush.qw_md4sum = 0;
4521 mod->brush.qw_md4sum2 = 0;
4522 for (i = 0;i < Q2HEADER_LUMPS;i++)
4524 if (i == Q2LUMP_ENTITIES)
4526 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4527 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4529 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4532 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4533 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4534 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4535 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4536 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4537 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4538 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4539 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4540 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4541 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4542 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4543 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4544 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4545 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4546 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4547 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4548 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4549 // LordHavoc: must go last because this makes the submodels
4550 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4553 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4554 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4556 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4559 char key[128], value[MAX_INPUTLINE];
4561 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4562 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4563 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4566 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4567 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4568 loadmodel->brush.entities[l->filelen] = 0;
4569 data = loadmodel->brush.entities;
4570 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4571 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4572 loadmodel->brushq3.deluxemapping = false;
4573 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
4577 if (!COM_ParseToken_Simple(&data, false, false, true))
4579 if (com_token[0] == '}')
4580 break; // end of worldspawn
4581 if (com_token[0] == '_')
4582 strlcpy(key, com_token + 1, sizeof(key));
4584 strlcpy(key, com_token, sizeof(key));
4585 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4586 key[strlen(key)-1] = 0;
4587 if (!COM_ParseToken_Simple(&data, false, false, true))
4589 strlcpy(value, com_token, sizeof(value));
4590 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4592 #if _MSC_VER >= 1400
4593 #define sscanf sscanf_s
4596 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4597 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4599 VectorSet(v, 64, 64, 128);
4600 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4601 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]);
4602 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4603 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4606 else if (!strcmp("deluxeMaps", key))
4608 if (!strcmp(com_token, "1"))
4610 loadmodel->brushq3.deluxemapping = true;
4611 loadmodel->brushq3.deluxemapping_modelspace = true;
4613 else if (!strcmp(com_token, "2"))
4615 loadmodel->brushq3.deluxemapping = true;
4616 loadmodel->brushq3.deluxemapping_modelspace = false;
4623 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4629 in = (q3dtexture_t *)(mod_base + l->fileofs);
4630 if (l->filelen % sizeof(*in))
4631 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4632 count = l->filelen / sizeof(*in);
4633 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4635 loadmodel->data_textures = out;
4636 loadmodel->num_textures = count;
4637 loadmodel->num_texturesperskin = loadmodel->num_textures;
4639 for (i = 0;i < count;i++)
4641 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4642 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4643 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4644 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4645 // restore the surfaceflags and supercontents
4646 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4647 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4651 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4657 in = (q3dplane_t *)(mod_base + l->fileofs);
4658 if (l->filelen % sizeof(*in))
4659 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4660 count = l->filelen / sizeof(*in);
4661 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4663 loadmodel->brush.data_planes = out;
4664 loadmodel->brush.num_planes = count;
4666 for (i = 0;i < count;i++, in++, out++)
4668 out->normal[0] = LittleFloat(in->normal[0]);
4669 out->normal[1] = LittleFloat(in->normal[1]);
4670 out->normal[2] = LittleFloat(in->normal[2]);
4671 out->dist = LittleFloat(in->dist);
4676 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4679 q3mbrushside_t *out;
4682 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4683 if (l->filelen % sizeof(*in))
4684 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4685 count = l->filelen / sizeof(*in);
4686 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4688 loadmodel->brush.data_brushsides = out;
4689 loadmodel->brush.num_brushsides = count;
4691 for (i = 0;i < count;i++, in++, out++)
4693 n = LittleLong(in->planeindex);
4694 if (n < 0 || n >= loadmodel->brush.num_planes)
4695 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4696 out->plane = loadmodel->brush.data_planes + n;
4697 n = LittleLong(in->textureindex);
4698 if (n < 0 || n >= loadmodel->num_textures)
4699 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4700 out->texture = loadmodel->data_textures + n;
4704 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4706 q3dbrushside_ig_t *in;
4707 q3mbrushside_t *out;
4710 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4711 if (l->filelen % sizeof(*in))
4712 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4713 count = l->filelen / sizeof(*in);
4714 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4716 loadmodel->brush.data_brushsides = out;
4717 loadmodel->brush.num_brushsides = count;
4719 for (i = 0;i < count;i++, in++, out++)
4721 n = LittleLong(in->planeindex);
4722 if (n < 0 || n >= loadmodel->brush.num_planes)
4723 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4724 out->plane = loadmodel->brush.data_planes + n;
4725 n = LittleLong(in->textureindex);
4726 if (n < 0 || n >= loadmodel->num_textures)
4727 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4728 out->texture = loadmodel->data_textures + n;
4732 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4736 int i, j, n, c, count, maxplanes, q3surfaceflags;
4737 colplanef_t *planes;
4739 in = (q3dbrush_t *)(mod_base + l->fileofs);
4740 if (l->filelen % sizeof(*in))
4741 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4742 count = l->filelen / sizeof(*in);
4743 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4745 loadmodel->brush.data_brushes = out;
4746 loadmodel->brush.num_brushes = count;
4751 for (i = 0;i < count;i++, in++, out++)
4753 n = LittleLong(in->firstbrushside);
4754 c = LittleLong(in->numbrushsides);
4755 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4756 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4757 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4758 out->numbrushsides = c;
4759 n = LittleLong(in->textureindex);
4760 if (n < 0 || n >= loadmodel->num_textures)
4761 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4762 out->texture = loadmodel->data_textures + n;
4764 // make a list of mplane_t structs to construct a colbrush from
4765 if (maxplanes < out->numbrushsides)
4767 maxplanes = out->numbrushsides;
4770 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4773 for (j = 0;j < out->numbrushsides;j++)
4775 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4776 planes[j].dist = out->firstbrushside[j].plane->dist;
4777 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4778 planes[j].texture = out->firstbrushside[j].texture;
4779 q3surfaceflags |= planes[j].q3surfaceflags;
4781 // make the colbrush from the planes
4782 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4784 // this whole loop can take a while (e.g. on redstarrepublic4)
4785 CL_KeepaliveMessage(false);
4791 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4797 in = (q3deffect_t *)(mod_base + l->fileofs);
4798 if (l->filelen % sizeof(*in))
4799 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4800 count = l->filelen / sizeof(*in);
4801 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4803 loadmodel->brushq3.data_effects = out;
4804 loadmodel->brushq3.num_effects = count;
4806 for (i = 0;i < count;i++, in++, out++)
4808 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4809 n = LittleLong(in->brushindex);
4810 if (n >= loadmodel->brush.num_brushes)
4812 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4815 out->brushindex = n;
4816 out->unknown = LittleLong(in->unknown);
4820 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4825 in = (q3dvertex_t *)(mod_base + l->fileofs);
4826 if (l->filelen % sizeof(*in))
4827 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4828 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4829 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4830 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4831 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4832 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4833 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4835 for (i = 0;i < count;i++, in++)
4837 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4838 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4839 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4840 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4841 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4842 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4843 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4844 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4845 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4846 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4847 // svector/tvector are calculated later in face loading
4848 if(mod_q3bsp_sRGBlightmaps.integer)
4850 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
4851 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
4852 // working like this may be odd, but matches q3map2 -gamma 2.2
4853 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4855 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4856 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4857 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4858 // we fix the brightness consistently via lightmapscale
4862 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
4863 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
4864 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
4869 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4871 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
4872 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
4873 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
4877 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4878 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4879 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4882 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4883 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4884 loadmodel->lit = true;
4888 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4894 in = (int *)(mod_base + l->fileofs);
4895 if (l->filelen % sizeof(int[3]))
4896 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4897 count = l->filelen / sizeof(*in);
4899 if(!loadmodel->brushq3.num_vertices)
4902 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4903 loadmodel->brushq3.num_triangles = 0;
4907 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4908 loadmodel->brushq3.num_triangles = count / 3;
4909 loadmodel->brushq3.data_element3i = out;
4911 for (i = 0;i < count;i++, in++, out++)
4913 *out = LittleLong(*in);
4914 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4916 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4922 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4924 q3dlightmap_t *input_pointer;
4942 int mergedrowsxcolumns;
4947 unsigned char *mergedpixels;
4948 unsigned char *mergeddeluxepixels;
4949 unsigned char *mergebuf;
4950 char mapname[MAX_QPATH];
4952 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4955 // defaults for q3bsp
4962 loadmodel->brushq3.lightmapsize = 128;
4964 if (cls.state == ca_dedicated)
4967 if(mod_q3bsp_nolightmaps.integer)
4973 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4974 if (developer_loading.integer)
4975 Con_Printf("Using internal lightmaps\n");
4976 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4977 if (l->filelen % sizeof(*input_pointer))
4978 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4979 count = l->filelen / sizeof(*input_pointer);
4980 for(i = 0; i < count; ++i)
4981 inpixels[i] = input_pointer[i].rgb;
4985 // no internal lightmaps
4986 // try external lightmaps
4987 if (developer_loading.integer)
4988 Con_Printf("Using external lightmaps\n");
4989 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4990 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
4994 // using EXTERNAL lightmaps instead
4995 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4997 Mem_Free(inpixels[0]);
4998 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5008 for(count = 1; ; ++count)
5010 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5011 if(!inpixels[count])
5012 break; // we got all of them
5013 if(image_width != size || image_height != size)
5015 Mem_Free(inpixels[count]);
5016 inpixels[count] = NULL;
5017 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);
5023 loadmodel->brushq3.lightmapsize = size;
5024 loadmodel->brushq3.num_originallightmaps = count;
5026 // now check the surfaces to see if any of them index an odd numbered
5027 // lightmap, if so this is not a deluxemapped bsp file
5029 // also check what lightmaps are actually used, because q3map2 sometimes
5030 // (always?) makes an unused one at the end, which
5031 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5032 // reason when only one lightmap is used, which can throw off the
5033 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5034 // to see if the second lightmap is blank, if so it is not deluxemapped.
5035 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5036 // in Mod_Q3BSP_LoadEntities was failed
5037 if (!loadmodel->brushq3.deluxemapping)
5039 loadmodel->brushq3.deluxemapping = !(count & 1);
5040 loadmodel->brushq3.deluxemapping_modelspace = true;
5042 if (loadmodel->brushq3.deluxemapping)
5044 int facecount = faceslump->filelen / sizeof(q3dface_t);
5045 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5046 for (i = 0;i < facecount;i++)
5048 j = LittleLong(faces[i].lightmapindex);
5051 endlightmap = max(endlightmap, j + 1);
5052 if ((j & 1) || j + 1 >= count)
5054 loadmodel->brushq3.deluxemapping = false;
5061 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5062 // reason when only one lightmap is used, which can throw off the
5063 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5064 // to see if the second lightmap is blank, if so it is not deluxemapped.
5066 // further research has shown q3map2 sometimes creates a deluxemap and two
5067 // blank lightmaps, which must be handled properly as well
5068 if (endlightmap == 1 && count > 1)
5071 for (i = 0;i < size*size;i++)
5073 if (c[bytesperpixel*i + rgbmap[0]])
5075 if (c[bytesperpixel*i + rgbmap[1]])
5077 if (c[bytesperpixel*i + rgbmap[2]])
5082 // all pixels in the unused lightmap were black...
5083 loadmodel->brushq3.deluxemapping = false;
5088 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5090 // figure out what the most reasonable merge power is within limits
5092 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5093 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5095 // figure out how big the merged texture has to be
5096 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5097 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5098 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5100 mergedwidth = mergegoal;
5101 mergedheight = mergegoal;
5102 // choose non-square size (2x1 aspect) if only half the space is used;
5103 // this really only happens when the entire set fits in one texture, if
5104 // there are multiple textures, we don't worry about shrinking the last
5105 // one to fit, because the driver prefers the same texture size on
5106 // consecutive draw calls...
5107 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5110 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5111 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5112 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5113 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5114 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5115 loadmodel->brushq3.num_lightmapmergedheightpower++;
5116 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5118 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5119 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5120 powerxy = powerx+powery;
5121 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5123 mergedcolumns = 1 << powerx;
5124 mergedrows = 1 << powery;
5125 mergedrowsxcolumns = 1 << powerxy;
5127 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5128 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5129 if (loadmodel->brushq3.deluxemapping)
5130 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5132 // allocate a texture pool if we need it
5133 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5134 loadmodel->texturepool = R_AllocTexturePool();
5136 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5137 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5138 for (i = 0;i < count;i++)
5140 // figure out which merged lightmap texture this fits into
5141 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5142 lightmapindex = i >> powerdxy;
5144 // choose the destination address
5145 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5146 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5147 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5148 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);
5150 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5151 for (j = 0;j < size;j++)
5152 for (k = 0;k < size;k++)
5154 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5155 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5156 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5157 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5160 // upload texture if this was the last tile being written to the texture
5161 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5163 if (loadmodel->brushq3.deluxemapping && (i & 1))
5164 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);
5167 if(mod_q3bsp_sRGBlightmaps.integer)
5170 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5172 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5173 // we fix the brightness consistently via lightmapscale
5176 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5177 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);
5181 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5182 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5183 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);
5189 if (mergeddeluxepixels)
5190 Mem_Free(mergeddeluxepixels);
5191 Mem_Free(mergedpixels);
5194 for(i = 0; i < count; ++i)
5195 Mem_Free(inpixels[i]);
5199 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5204 *collisionstride = stride;
5207 cnt = (num_triangles + stride - 1) / stride;
5208 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5209 for(j = 0; j < cnt; ++j)
5211 mins = &((*collisionbbox6f)[6 * j + 0]);
5212 maxs = &((*collisionbbox6f)[6 * j + 3]);
5213 for(k = 0; k < stride; ++k)
5215 tri = j * stride + k;
5216 if(tri >= num_triangles)
5218 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5219 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5220 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5221 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5222 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5223 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5224 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5225 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5226 if(vert[0] < mins[0]) mins[0] = vert[0];
5227 if(vert[1] < mins[1]) mins[1] = vert[1];
5228 if(vert[2] < mins[2]) mins[2] = vert[2];
5229 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5230 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5231 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5232 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5233 if(vert[0] < mins[0]) mins[0] = vert[0];
5234 if(vert[1] < mins[1]) mins[1] = vert[1];
5235 if(vert[2] < mins[2]) mins[2] = vert[2];
5236 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5237 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5238 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5243 *collisionbbox6f = NULL;
5246 typedef struct patchtess_s
5250 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5253 float *originalvertex3f;
5256 #define PATCHTESS_SAME_LODGROUP(a,b) \
5258 (a).lodgroup[0] == (b).lodgroup[0] && \
5259 (a).lodgroup[1] == (b).lodgroup[1] && \
5260 (a).lodgroup[2] == (b).lodgroup[2] && \
5261 (a).lodgroup[3] == (b).lodgroup[3] && \
5262 (a).lodgroup[4] == (b).lodgroup[4] && \
5263 (a).lodgroup[5] == (b).lodgroup[5] \
5266 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5268 q3dface_t *in, *oldin;
5269 msurface_t *out, *oldout;
5270 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;
5271 float lightmaptcbase[2], lightmaptcscale[2];
5272 //int *originalelement3i;
5273 //int *originalneighbor3i;
5274 float *originalvertex3f;
5275 //float *originalsvector3f;
5276 //float *originaltvector3f;
5277 float *originalnormal3f;
5278 float *originalcolor4f;
5279 float *originaltexcoordtexture2f;
5280 float *originaltexcoordlightmap2f;
5281 float *surfacecollisionvertex3f;
5282 int *surfacecollisionelement3i;
5284 patchtess_t *patchtess = NULL;
5285 int patchtesscount = 0;
5288 in = (q3dface_t *)(mod_base + l->fileofs);
5289 if (l->filelen % sizeof(*in))
5290 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5291 count = l->filelen / sizeof(*in);
5292 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5294 loadmodel->data_surfaces = out;
5295 loadmodel->num_surfaces = count;
5298 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5306 for (;i < count;i++, in++, out++)
5308 // check face type first
5309 type = LittleLong(in->type);
5310 if (type != Q3FACETYPE_FLAT
5311 && type != Q3FACETYPE_PATCH
5312 && type != Q3FACETYPE_MESH
5313 && type != Q3FACETYPE_FLARE)
5315 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5319 n = LittleLong(in->textureindex);
5320 if (n < 0 || n >= loadmodel->num_textures)
5322 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5325 out->texture = loadmodel->data_textures + n;
5326 n = LittleLong(in->effectindex);
5327 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5329 if (developer_extra.integer)
5330 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5336 out->effect = loadmodel->brushq3.data_effects + n;
5338 if (cls.state != ca_dedicated)
5340 out->lightmaptexture = NULL;
5341 out->deluxemaptexture = r_texture_blanknormalmap;
5342 n = LittleLong(in->lightmapindex);
5345 else if (n >= loadmodel->brushq3.num_originallightmaps)
5347 if(loadmodel->brushq3.num_originallightmaps != 0)
5348 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5353 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5354 if (loadmodel->brushq3.deluxemapping)
5355 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5356 loadmodel->lit = true;
5360 firstvertex = LittleLong(in->firstvertex);
5361 numvertices = LittleLong(in->numvertices);
5362 firstelement = LittleLong(in->firstelement);
5363 numtriangles = LittleLong(in->numelements) / 3;
5364 if (numtriangles * 3 != LittleLong(in->numelements))
5366 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));
5369 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5371 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);
5374 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5376 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);
5381 case Q3FACETYPE_FLAT:
5382 case Q3FACETYPE_MESH:
5383 // no processing necessary
5385 case Q3FACETYPE_PATCH:
5386 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5387 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5388 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))
5390 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5393 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5395 // convert patch to Q3FACETYPE_MESH
5396 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5397 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5398 // bound to user settings
5399 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5400 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5401 // bound to sanity settings
5402 xtess = bound(0, xtess, 1024);
5403 ytess = bound(0, ytess, 1024);
5405 // lower quality collision patches! Same procedure as before, but different cvars
5406 // convert patch to Q3FACETYPE_MESH
5407 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5408 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5409 // bound to user settings
5410 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5411 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5412 // bound to sanity settings
5413 cxtess = bound(0, cxtess, 1024);
5414 cytess = bound(0, cytess, 1024);
5416 // store it for the LOD grouping step
5417 patchtess[patchtesscount].info.xsize = patchsize[0];
5418 patchtess[patchtesscount].info.ysize = patchsize[1];
5419 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5420 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5421 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5422 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5424 patchtess[patchtesscount].surface_id = i;
5425 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5426 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5427 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5428 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5429 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5430 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5431 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5434 case Q3FACETYPE_FLARE:
5435 if (developer_extra.integer)
5436 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5440 out->num_vertices = numvertices;
5441 out->num_triangles = numtriangles;
5442 meshvertices += out->num_vertices;
5443 meshtriangles += out->num_triangles;
5446 // Fix patches tesselations so that they make no seams
5450 for(i = 0; i < patchtesscount; ++i)
5452 for(j = i+1; j < patchtesscount; ++j)
5454 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5457 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5464 // Calculate resulting number of triangles
5465 collisionvertices = 0;
5466 collisiontriangles = 0;
5467 for(i = 0; i < patchtesscount; ++i)
5469 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5470 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5471 numvertices = finalwidth * finalheight;
5472 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5474 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5475 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5476 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5477 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5479 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5480 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5481 numvertices = finalwidth * finalheight;
5482 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5484 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5485 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5486 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5487 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5493 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5494 if (collisiontriangles)
5496 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5497 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5501 collisionvertices = 0;
5502 collisiontriangles = 0;
5503 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5505 if (out->num_vertices < 3 || out->num_triangles < 1)
5508 type = LittleLong(in->type);
5509 firstvertex = LittleLong(in->firstvertex);
5510 firstelement = LittleLong(in->firstelement);
5511 out->num_firstvertex = meshvertices;
5512 out->num_firsttriangle = meshtriangles;
5513 out->num_firstcollisiontriangle = collisiontriangles;
5516 case Q3FACETYPE_FLAT:
5517 case Q3FACETYPE_MESH:
5518 // no processing necessary, except for lightmap merging
5519 for (j = 0;j < out->num_vertices;j++)
5521 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5522 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5523 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5524 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5525 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5526 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5527 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5528 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5529 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5530 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5531 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5532 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5533 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5534 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5536 for (j = 0;j < out->num_triangles*3;j++)
5537 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5539 case Q3FACETYPE_PATCH:
5540 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5541 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5542 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5543 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5544 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5545 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5546 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5548 xtess = ytess = cxtess = cytess = -1;
5549 for(j = 0; j < patchtesscount; ++j)
5550 if(patchtess[j].surface_id == i)
5552 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5553 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5554 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5555 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5560 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5561 xtess = ytess = cxtess = cytess = 0;
5564 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5565 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5566 finalvertices = finalwidth * finalheight;
5567 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5568 type = Q3FACETYPE_MESH;
5569 // generate geometry
5570 // (note: normals are skipped because they get recalculated)
5571 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5572 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5573 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5574 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5575 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5576 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5578 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);
5580 if (developer_extra.integer)
5582 if (out->num_triangles < finaltriangles)
5583 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);
5585 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);
5587 // q3map does not put in collision brushes for curves... ugh
5588 // build the lower quality collision geometry
5589 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5590 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5591 finalvertices = finalwidth * finalheight;
5592 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5594 // legacy collision geometry implementation
5595 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5596 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5597 out->num_collisionvertices = finalvertices;
5598 out->num_collisiontriangles = finaltriangles;
5599 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5600 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5602 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5603 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5605 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5607 // now optimize the collision mesh by finding triangle bboxes...
5608 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5609 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);
5611 // store collision geometry for BIH collision tree
5612 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5613 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5614 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5615 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5616 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5618 // remove this once the legacy code is removed
5620 int nc = out->num_collisiontriangles;
5622 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5624 if(nc != out->num_collisiontriangles)
5626 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5631 if (developer_extra.integer)
5632 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);
5634 collisionvertices += finalvertices;
5635 collisiontriangles += out->num_collisiontriangles;
5640 meshvertices += out->num_vertices;
5641 meshtriangles += out->num_triangles;
5642 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5643 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)
5645 if (invalidelements)
5647 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);
5648 for (j = 0;j < out->num_triangles * 3;j++)
5650 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5651 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)
5652 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5656 // calculate a bounding box
5657 VectorClear(out->mins);
5658 VectorClear(out->maxs);
5659 if (out->num_vertices)
5661 if (cls.state != ca_dedicated && out->lightmaptexture)
5663 // figure out which part of the merged lightmap this fits into
5664 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5665 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5666 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5667 lightmapindex &= mergewidth * mergeheight - 1;
5668 lightmaptcscale[0] = 1.0f / mergewidth;
5669 lightmaptcscale[1] = 1.0f / mergeheight;
5670 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5671 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5672 // modify the lightmap texcoords to match this region of the merged lightmap
5673 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5675 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5676 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5679 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5680 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5681 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5683 out->mins[0] = min(out->mins[0], v[0]);
5684 out->maxs[0] = max(out->maxs[0], v[0]);
5685 out->mins[1] = min(out->mins[1], v[1]);
5686 out->maxs[1] = max(out->maxs[1], v[1]);
5687 out->mins[2] = min(out->mins[2], v[2]);
5688 out->maxs[2] = max(out->maxs[2], v[2]);
5690 out->mins[0] -= 1.0f;
5691 out->mins[1] -= 1.0f;
5692 out->mins[2] -= 1.0f;
5693 out->maxs[0] += 1.0f;
5694 out->maxs[1] += 1.0f;
5695 out->maxs[2] += 1.0f;
5697 // set lightmap styles for consistency with q1bsp
5698 //out->lightmapinfo->styles[0] = 0;
5699 //out->lightmapinfo->styles[1] = 255;
5700 //out->lightmapinfo->styles[2] = 255;
5701 //out->lightmapinfo->styles[3] = 255;
5706 for (;i < count;i++, out++)
5708 if(out->num_vertices && out->num_triangles)
5710 if(out->num_vertices == 0)
5712 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5713 if(out->num_triangles == 0)
5714 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5716 else if(out->num_triangles == 0)
5717 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)",
5718 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5719 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5720 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5723 // for per pixel lighting
5724 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);
5726 // generate ushort elements array if possible
5727 if (loadmodel->surfmesh.data_element3s)
5728 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5729 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5731 // free the no longer needed vertex data
5732 loadmodel->brushq3.num_vertices = 0;
5733 if (loadmodel->brushq3.data_vertex3f)
5734 Mem_Free(loadmodel->brushq3.data_vertex3f);
5735 loadmodel->brushq3.data_vertex3f = NULL;
5736 loadmodel->brushq3.data_normal3f = NULL;
5737 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5738 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5739 loadmodel->brushq3.data_color4f = NULL;
5740 // free the no longer needed triangle data
5741 loadmodel->brushq3.num_triangles = 0;
5742 if (loadmodel->brushq3.data_element3i)
5743 Mem_Free(loadmodel->brushq3.data_element3i);
5744 loadmodel->brushq3.data_element3i = NULL;
5747 Mem_Free(patchtess);
5750 static void Mod_Q3BSP_LoadModels(lump_t *l)
5754 int i, j, n, c, count;
5756 in = (q3dmodel_t *)(mod_base + l->fileofs);
5757 if (l->filelen % sizeof(*in))
5758 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5759 count = l->filelen / sizeof(*in);
5760 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5762 loadmodel->brushq3.data_models = out;
5763 loadmodel->brushq3.num_models = count;
5765 for (i = 0;i < count;i++, in++, out++)
5767 for (j = 0;j < 3;j++)
5769 out->mins[j] = LittleFloat(in->mins[j]);
5770 out->maxs[j] = LittleFloat(in->maxs[j]);
5772 n = LittleLong(in->firstface);
5773 c = LittleLong(in->numfaces);
5774 if (n < 0 || n + c > loadmodel->num_surfaces)
5775 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5778 n = LittleLong(in->firstbrush);
5779 c = LittleLong(in->numbrushes);
5780 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5781 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5782 out->firstbrush = n;
5783 out->numbrushes = c;
5787 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5793 in = (int *)(mod_base + l->fileofs);
5794 if (l->filelen % sizeof(*in))
5795 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5796 count = l->filelen / sizeof(*in);
5797 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5799 loadmodel->brush.data_leafbrushes = out;
5800 loadmodel->brush.num_leafbrushes = count;
5802 for (i = 0;i < count;i++, in++, out++)
5804 n = LittleLong(*in);
5805 if (n < 0 || n >= loadmodel->brush.num_brushes)
5806 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5811 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5817 in = (int *)(mod_base + l->fileofs);
5818 if (l->filelen % sizeof(*in))
5819 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5820 count = l->filelen / sizeof(*in);
5821 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5823 loadmodel->brush.data_leafsurfaces = out;
5824 loadmodel->brush.num_leafsurfaces = count;
5826 for (i = 0;i < count;i++, in++, out++)
5828 n = LittleLong(*in);
5829 if (n < 0 || n >= loadmodel->num_surfaces)
5830 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5835 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5839 int i, j, n, c, count;
5841 in = (q3dleaf_t *)(mod_base + l->fileofs);
5842 if (l->filelen % sizeof(*in))
5843 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5844 count = l->filelen / sizeof(*in);
5845 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5847 loadmodel->brush.data_leafs = out;
5848 loadmodel->brush.num_leafs = count;
5850 for (i = 0;i < count;i++, in++, out++)
5854 out->clusterindex = LittleLong(in->clusterindex);
5855 out->areaindex = LittleLong(in->areaindex);
5856 for (j = 0;j < 3;j++)
5858 // yes the mins/maxs are ints
5859 out->mins[j] = LittleLong(in->mins[j]) - 1;
5860 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5862 n = LittleLong(in->firstleafface);
5863 c = LittleLong(in->numleaffaces);
5864 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5865 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5866 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5867 out->numleafsurfaces = c;
5868 n = LittleLong(in->firstleafbrush);
5869 c = LittleLong(in->numleafbrushes);
5870 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5871 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5872 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5873 out->numleafbrushes = c;
5877 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5883 in = (q3dnode_t *)(mod_base + l->fileofs);
5884 if (l->filelen % sizeof(*in))
5885 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5886 count = l->filelen / sizeof(*in);
5888 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5889 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5891 loadmodel->brush.data_nodes = out;
5892 loadmodel->brush.num_nodes = count;
5894 for (i = 0;i < count;i++, in++, out++)
5897 n = LittleLong(in->planeindex);
5898 if (n < 0 || n >= loadmodel->brush.num_planes)
5899 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5900 out->plane = loadmodel->brush.data_planes + n;
5901 for (j = 0;j < 2;j++)
5903 n = LittleLong(in->childrenindex[j]);
5906 if (n >= loadmodel->brush.num_nodes)
5907 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5908 out->children[j] = loadmodel->brush.data_nodes + n;
5913 if (n >= loadmodel->brush.num_leafs)
5914 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5915 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5918 for (j = 0;j < 3;j++)
5920 // yes the mins/maxs are ints
5921 out->mins[j] = LittleLong(in->mins[j]) - 1;
5922 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5926 // set the parent pointers
5927 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5930 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5933 q3dlightgrid_t *out;
5937 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5938 if (l->filelen % sizeof(*in))
5939 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5940 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5941 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5942 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5943 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5944 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5945 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5946 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5947 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5948 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5949 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5950 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5951 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5952 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5953 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]);
5954 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]);
5956 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5959 if (l->filelen < count * (int)sizeof(*in))
5961 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]);
5962 return; // ignore the grid if we cannot understand it
5964 if (l->filelen != count * (int)sizeof(*in))
5965 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5966 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5967 loadmodel->brushq3.data_lightgrid = out;
5968 loadmodel->brushq3.num_lightgrid = count;
5969 // no swapping or validation necessary
5970 memcpy(out, in, count * (int)sizeof(*out));
5972 if(mod_q3bsp_sRGBlightmaps.integer)
5974 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5976 // we fix the brightness consistently via lightmapscale
5980 for(i = 0; i < count; ++i)
5982 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5983 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5984 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5985 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
5986 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
5987 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
5993 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5995 for(i = 0; i < count; ++i)
5997 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5998 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5999 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6000 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6001 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6002 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6013 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6018 if (l->filelen == 0)
6021 // unvised maps often have cluster indices even without pvs, so check
6022 // leafs to find real number of clusters
6023 loadmodel->brush.num_pvsclusters = 1;
6024 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6025 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6028 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6029 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6030 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6031 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6035 in = (q3dpvs_t *)(mod_base + l->fileofs);
6037 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6039 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6040 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6041 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6042 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6043 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6044 if (l->filelen < totalchains + (int)sizeof(*in))
6045 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);
6047 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6048 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6051 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6053 int i, j, k, index[3];
6054 float transformed[3], blend1, blend2, blend, stylescale = 1;
6055 q3dlightgrid_t *a, *s;
6057 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6058 switch(vid.renderpath)
6060 case RENDERPATH_GL20:
6061 case RENDERPATH_D3D9:
6062 case RENDERPATH_D3D10:
6063 case RENDERPATH_D3D11:
6064 case RENDERPATH_SOFT:
6065 case RENDERPATH_GLES2:
6066 // LordHavoc: FIXME: is this true?
6067 stylescale = 1; // added while render
6069 case RENDERPATH_GL11:
6070 case RENDERPATH_GL13:
6071 case RENDERPATH_GLES1:
6072 stylescale = r_refdef.scene.rtlightstylevalue[0];
6076 if (!model->brushq3.num_lightgrid)
6078 ambientcolor[0] = stylescale;
6079 ambientcolor[1] = stylescale;
6080 ambientcolor[2] = stylescale;
6084 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6085 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6086 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6087 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6088 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6089 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6090 index[0] = (int)floor(transformed[0]);
6091 index[1] = (int)floor(transformed[1]);
6092 index[2] = (int)floor(transformed[2]);
6093 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6095 // now lerp the values
6096 VectorClear(diffusenormal);
6097 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6098 for (k = 0;k < 2;k++)
6100 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6101 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6103 for (j = 0;j < 2;j++)
6105 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6106 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6108 for (i = 0;i < 2;i++)
6110 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6111 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6113 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6114 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6115 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6116 // this uses the mod_md3_sin table because the values are
6117 // already in the 0-255 range, the 64+ bias fetches a cosine
6118 // instead of a sine value
6119 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6120 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6121 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6122 //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)));
6127 // normalize the light direction before turning
6128 VectorNormalize(diffusenormal);
6129 //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]);
6132 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6135 double midf, mid[3];
6141 // find the point distances
6142 mplane_t *plane = node->plane;
6143 if (plane->type < 3)
6145 t1 = p1[plane->type] - plane->dist;
6146 t2 = p2[plane->type] - plane->dist;
6150 t1 = DotProduct (plane->normal, p1) - plane->dist;
6151 t2 = DotProduct (plane->normal, p2) - plane->dist;
6158 node = node->children[1];
6167 node = node->children[0];
6173 midf = t1 / (t1 - t2);
6174 VectorLerp(p1, midf, p2, mid);
6176 // recurse both sides, front side first
6177 // return 2 if empty is followed by solid (hit something)
6178 // do not return 2 if both are solid or both empty,
6179 // or if start is solid and end is empty
6180 // as these degenerate cases usually indicate the eye is in solid and
6181 // should see the target point anyway
6182 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6185 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6190 return ((mleaf_t *)node)->clusterindex < 0;
6193 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6195 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6198 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6199 return trace.fraction == 1;
6203 double tracestart[3], traceend[3];
6204 VectorCopy(start, tracestart);
6205 VectorCopy(end, traceend);
6206 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6210 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)
6213 const bih_leaf_t *leaf;
6214 const bih_node_t *node;
6215 const colbrushf_t *brush;
6218 int nodestackpos = 0;
6219 int nodestack[1024];
6221 memset(trace, 0, sizeof(*trace));
6222 trace->fraction = 1;
6223 trace->hitsupercontentsmask = hitsupercontentsmask;
6225 bih = &model->collision_bih;
6229 nodenum = bih->rootnode;
6230 nodestack[nodestackpos++] = nodenum;
6231 while (nodestackpos)
6233 nodenum = nodestack[--nodestackpos];
6234 node = bih->nodes + nodenum;
6236 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6239 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6241 axis = node->type - BIH_SPLITX;
6242 if (start[axis] >= node->frontmin)
6243 nodestack[nodestackpos++] = node->front;
6244 if (start[axis] <= node->backmax)
6245 nodestack[nodestackpos++] = node->back;
6247 else if (node->type == BIH_UNORDERED)
6249 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6251 leaf = bih->leafs + node->children[axis];
6253 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6259 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6260 Collision_TracePointBrushFloat(trace, start, brush);
6262 case BIH_COLLISIONTRIANGLE:
6263 // collision triangle - skipped because they have no volume
6265 case BIH_RENDERTRIANGLE:
6266 // render triangle - skipped because they have no volume
6274 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)
6276 const bih_leaf_t *leaf;
6277 const bih_node_t *node;
6278 const colbrushf_t *brush;
6280 const texture_t *texture;
6281 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6282 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6283 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6288 if (VectorCompare(start, end))
6290 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6294 nodenum = bih->rootnode;
6296 memset(trace, 0, sizeof(*trace));
6297 trace->fraction = 1;
6298 trace->hitsupercontentsmask = hitsupercontentsmask;
6301 nodestackline[nodestackpos][0] = start[0];
6302 nodestackline[nodestackpos][1] = start[1];
6303 nodestackline[nodestackpos][2] = start[2];
6304 nodestackline[nodestackpos][3] = end[0];
6305 nodestackline[nodestackpos][4] = end[1];
6306 nodestackline[nodestackpos][5] = end[2];
6307 nodestack[nodestackpos++] = nodenum;
6308 while (nodestackpos)
6310 nodenum = nodestack[--nodestackpos];
6311 node = bih->nodes + nodenum;
6312 VectorCopy(nodestackline[nodestackpos], nodestart);
6313 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6314 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6315 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6316 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6317 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6318 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6319 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6320 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6322 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6324 // recurse children of the split
6325 axis = node->type - BIH_SPLITX;
6326 d1 = node->backmax - nodestart[axis];
6327 d2 = node->backmax - nodeend[axis];
6328 d3 = nodestart[axis] - node->frontmin;
6329 d4 = nodeend[axis] - node->frontmin;
6330 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6332 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;
6333 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;
6334 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;
6335 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6336 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;
6337 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;
6338 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;
6339 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6340 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;
6341 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;
6342 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;
6343 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6344 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6345 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6346 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6347 case 15: /* <<<< */ break;
6350 else if (node->type == BIH_UNORDERED)
6352 // calculate sweep bounds for this node
6353 // copy node bounds into local variables
6354 VectorCopy(node->mins, nodebigmins);
6355 VectorCopy(node->maxs, nodebigmaxs);
6356 // clip line to this node bounds
6357 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); }
6358 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); }
6359 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); }
6360 // some of the line intersected the enlarged node box
6361 // calculate sweep bounds for this node
6362 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6363 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6364 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6365 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6366 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6367 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6368 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6370 leaf = bih->leafs + node->children[axis];
6371 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6376 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6377 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6379 case BIH_COLLISIONTRIANGLE:
6380 if (!mod_q3bsp_curves_collisions.integer)
6382 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6383 texture = model->data_textures + leaf->textureindex;
6384 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);
6386 case BIH_RENDERTRIANGLE:
6387 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6388 texture = model->data_textures + leaf->textureindex;
6389 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);
6397 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)
6399 if (VectorCompare(start, end))
6401 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6404 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6407 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)
6410 const bih_leaf_t *leaf;
6411 const bih_node_t *node;
6412 const colbrushf_t *brush;
6414 const texture_t *texture;
6415 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6416 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6417 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6418 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6420 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6422 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6423 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6425 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6429 bih = &model->collision_bih;
6432 nodenum = bih->rootnode;
6434 // box trace, performed as brush trace
6435 memset(trace, 0, sizeof(*trace));
6436 trace->fraction = 1;
6437 trace->hitsupercontentsmask = hitsupercontentsmask;
6439 // calculate tracebox-like parameters for efficient culling
6440 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6441 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6442 VectorSubtract(thisbrush_start->mins, start, startmins);
6443 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6444 VectorSubtract(thisbrush_end->mins, end, endmins);
6445 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6446 mins[0] = min(startmins[0], endmins[0]);
6447 mins[1] = min(startmins[1], endmins[1]);
6448 mins[2] = min(startmins[2], endmins[2]);
6449 maxs[0] = max(startmaxs[0], endmaxs[0]);
6450 maxs[1] = max(startmaxs[1], endmaxs[1]);
6451 maxs[2] = max(startmaxs[2], endmaxs[2]);
6454 nodestackline[nodestackpos][0] = start[0];
6455 nodestackline[nodestackpos][1] = start[1];
6456 nodestackline[nodestackpos][2] = start[2];
6457 nodestackline[nodestackpos][3] = end[0];
6458 nodestackline[nodestackpos][4] = end[1];
6459 nodestackline[nodestackpos][5] = end[2];
6460 nodestack[nodestackpos++] = nodenum;
6461 while (nodestackpos)
6463 nodenum = nodestack[--nodestackpos];
6464 node = bih->nodes + nodenum;
6465 VectorCopy(nodestackline[nodestackpos], nodestart);
6466 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6467 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
6468 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
6469 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
6470 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
6471 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
6472 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
6473 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6475 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6477 // recurse children of the split
6478 axis = node->type - BIH_SPLITX;
6479 d1 = node->backmax - nodestart[axis] - mins[axis];
6480 d2 = node->backmax - nodeend[axis] - mins[axis];
6481 d3 = nodestart[axis] - node->frontmin + maxs[axis];
6482 d4 = nodeend[axis] - node->frontmin + maxs[axis];
6483 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6485 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;
6486 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;
6487 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;
6488 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6489 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;
6490 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;
6491 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;
6492 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6493 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;
6494 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;
6495 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;
6496 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6497 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6498 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6499 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6500 case 15: /* <<<< */ break;
6503 else if (node->type == BIH_UNORDERED)
6505 // calculate sweep bounds for this node
6506 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6507 VectorSubtract(node->mins, maxs, nodebigmins);
6508 VectorSubtract(node->maxs, mins, nodebigmaxs);
6509 // clip line to this node bounds
6510 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); }
6511 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); }
6512 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); }
6513 // some of the line intersected the enlarged node box
6514 // calculate sweep bounds for this node
6515 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
6516 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
6517 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
6518 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
6519 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
6520 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
6521 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6523 leaf = bih->leafs + node->children[axis];
6524 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6529 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6530 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6532 case BIH_COLLISIONTRIANGLE:
6533 if (!mod_q3bsp_curves_collisions.integer)
6535 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6536 texture = model->data_textures + leaf->textureindex;
6537 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);
6539 case BIH_RENDERTRIANGLE:
6540 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6541 texture = model->data_textures + leaf->textureindex;
6542 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);
6550 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)
6552 colboxbrushf_t thisbrush_start, thisbrush_end;
6553 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6555 // box trace, performed as brush trace
6556 VectorAdd(start, boxmins, boxstartmins);
6557 VectorAdd(start, boxmaxs, boxstartmaxs);
6558 VectorAdd(end, boxmins, boxendmins);
6559 VectorAdd(end, boxmaxs, boxendmaxs);
6560 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6561 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6562 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6566 static int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6569 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6570 return trace.startsupercontents;
6573 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)
6576 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6578 int hitsupercontents;
6579 VectorSet(end, start[0], start[1], model->normalmins[2]);
6581 memset(trace, 0, sizeof(*trace));
6582 trace->fraction = 1;
6583 trace->hitsupercontentsmask = hitsupercontentsmask;
6585 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6586 hitsupercontents = trace->hitsupercontents;
6587 memset(trace, 0, sizeof(*trace));
6588 trace->fraction = 1;
6589 trace->hitsupercontentsmask = hitsupercontentsmask;
6590 trace->startsupercontents = hitsupercontents;
6594 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6597 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6600 VectorSet(end, start[0], start[1], model->normalmins[2]);
6601 memset(&trace, 0, sizeof(trace));
6603 trace.hitsupercontentsmask = 0;
6604 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6605 return trace.hitsupercontents;
6611 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6616 // find which leaf the point is in
6618 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6619 // point trace the brushes
6620 leaf = (mleaf_t *)node;
6621 for (i = 0;i < leaf->numleafbrushes;i++)
6623 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6624 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6626 brush->markframe = markframe;
6627 Collision_TracePointBrushFloat(trace, point, brush);
6630 // can't do point traces on curves (they have no thickness)
6633 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)
6635 int i, startside, endside;
6636 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6638 msurface_t *surface;
6641 // walk the tree until we hit a leaf, recursing for any split cases
6645 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6647 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6648 node = node->children[1];
6650 // abort if this part of the bsp tree can not be hit by this trace
6651 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6653 plane = node->plane;
6654 // axial planes are much more common than non-axial, so an optimized
6655 // axial case pays off here
6656 if (plane->type < 3)
6658 dist1 = start[plane->type] - plane->dist;
6659 dist2 = end[plane->type] - plane->dist;
6663 dist1 = DotProduct(start, plane->normal) - plane->dist;
6664 dist2 = DotProduct(end, plane->normal) - plane->dist;
6666 startside = dist1 < 0;
6667 endside = dist2 < 0;
6668 if (startside == endside)
6670 // most of the time the line fragment is on one side of the plane
6671 node = node->children[startside];
6675 // line crosses node plane, split the line
6676 dist1 = PlaneDiff(linestart, plane);
6677 dist2 = PlaneDiff(lineend, plane);
6678 midfrac = dist1 / (dist1 - dist2);
6679 VectorLerp(linestart, midfrac, lineend, mid);
6680 // take the near side first
6681 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6682 // if we found an impact on the front side, don't waste time
6683 // exploring the far side
6684 if (midfrac <= trace->fraction)
6685 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6690 // abort if this part of the bsp tree can not be hit by this trace
6691 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6694 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6695 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6696 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6697 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6698 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6699 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6700 // line trace the brushes
6701 leaf = (mleaf_t *)node;
6703 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6706 for (i = 0;i < leaf->numleafbrushes;i++)
6708 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6709 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6711 brush->markframe = markframe;
6712 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6715 // can't do point traces on curves (they have no thickness)
6716 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6718 // line trace the curves
6719 for (i = 0;i < leaf->numleafsurfaces;i++)
6721 surface = model->data_surfaces + leaf->firstleafsurface[i];
6722 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6724 surface->deprecatedq3collisionmarkframe = markframe;
6725 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);
6731 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)
6737 msurface_t *surface;
6739 float nodesegmentmins[3], nodesegmentmaxs[3];
6740 // walk the tree until we hit a leaf, recursing for any split cases
6744 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6746 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6747 node = node->children[1];
6749 // abort if this part of the bsp tree can not be hit by this trace
6750 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6752 plane = node->plane;
6753 // axial planes are much more common than non-axial, so an optimized
6754 // axial case pays off here
6755 if (plane->type < 3)
6757 // this is an axial plane, compare bounding box directly to it and
6758 // recurse sides accordingly
6759 // recurse down node sides
6760 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6761 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6762 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6763 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6767 // this is a non-axial plane, so check if the start and end boxes
6768 // are both on one side of the plane to handle 'diagonal' cases
6769 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6773 // segment crosses plane
6774 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6777 // if sides == 0 then the trace itself is bogus (Not A Number values),
6778 // in this case we simply pretend the trace hit nothing
6780 return; // ERROR: NAN bounding box!
6781 // take whichever side the segment box is on
6782 node = node->children[sides - 1];
6785 // abort if this part of the bsp tree can not be hit by this trace
6786 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6788 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6789 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6790 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6791 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6792 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6793 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6795 leaf = (mleaf_t *)node;
6797 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6800 for (i = 0;i < leaf->numleafbrushes;i++)
6802 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6803 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6805 brush->markframe = markframe;
6806 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6809 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6811 for (i = 0;i < leaf->numleafsurfaces;i++)
6813 surface = model->data_surfaces + leaf->firstleafsurface[i];
6814 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6816 surface->deprecatedq3collisionmarkframe = markframe;
6817 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);
6824 static int markframe = 0;
6826 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)
6830 memset(trace, 0, sizeof(*trace));
6831 trace->fraction = 1;
6832 trace->hitsupercontentsmask = hitsupercontentsmask;
6833 if (mod_collision_bih.integer)
6834 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6835 else if (model->brush.submodel)
6837 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6838 if (brush->colbrushf)
6839 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6842 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6845 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)
6848 float segmentmins[3], segmentmaxs[3];
6849 msurface_t *surface;
6852 if (VectorCompare(start, end))
6854 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6858 memset(trace, 0, sizeof(*trace));
6859 trace->fraction = 1;
6860 trace->hitsupercontentsmask = hitsupercontentsmask;
6861 segmentmins[0] = min(start[0], end[0]) - 1;
6862 segmentmins[1] = min(start[1], end[1]) - 1;
6863 segmentmins[2] = min(start[2], end[2]) - 1;
6864 segmentmaxs[0] = max(start[0], end[0]) + 1;
6865 segmentmaxs[1] = max(start[1], end[1]) + 1;
6866 segmentmaxs[2] = max(start[2], end[2]) + 1;
6867 if (mod_collision_bih.integer)
6868 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6869 else if (model->brush.submodel)
6871 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6872 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6873 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6874 if (mod_q3bsp_curves_collisions.integer)
6875 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6876 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6877 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);
6880 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6883 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)
6885 float segmentmins[3], segmentmaxs[3];
6887 msurface_t *surface;
6890 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6892 if (VectorCompare(start->mins, end->mins))
6893 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6895 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6899 // box trace, performed as brush trace
6900 memset(trace, 0, sizeof(*trace));
6901 trace->fraction = 1;
6902 trace->hitsupercontentsmask = hitsupercontentsmask;
6903 segmentmins[0] = min(start->mins[0], end->mins[0]) - 1;
6904 segmentmins[1] = min(start->mins[1], end->mins[1]) - 1;
6905 segmentmins[2] = min(start->mins[2], end->mins[2]) - 1;
6906 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]) + 1;
6907 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]) + 1;
6908 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]) + 1;
6909 if (mod_collision_bih.integer)
6910 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6911 else if (model->brush.submodel)
6913 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6914 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6915 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6916 if (mod_q3bsp_curves_collisions.integer)
6917 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6918 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6919 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);
6922 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6925 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)
6927 colboxbrushf_t thisbrush_start, thisbrush_end;
6928 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6930 // box trace, performed as brush trace
6931 VectorAdd(start, boxmins, boxstartmins);
6932 VectorAdd(start, boxmaxs, boxstartmaxs);
6933 VectorAdd(end, boxmins, boxendmins);
6934 VectorAdd(end, boxmaxs, boxendmaxs);
6935 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6936 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6937 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6940 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6943 int supercontents = 0;
6945 if (mod_collision_bih.integer)
6947 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
6949 // test if the point is inside each brush
6950 else if (model->brush.submodel)
6952 // submodels are effectively one leaf
6953 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6954 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6955 supercontents |= brush->colbrushf->supercontents;
6959 mnode_t *node = model->brush.data_nodes;
6961 // find which leaf the point is in
6963 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6964 leaf = (mleaf_t *)node;
6965 // now check the brushes in the leaf
6966 for (i = 0;i < leaf->numleafbrushes;i++)
6968 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6969 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6970 supercontents |= brush->colbrushf->supercontents;
6973 return supercontents;
6976 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)
6978 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
6982 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6990 int nummodelbrushes = model->nummodelbrushes;
6991 int nummodelsurfaces = model->nummodelsurfaces;
6993 const int *collisionelement3i;
6994 const float *collisionvertex3f;
6995 const int *renderelement3i;
6996 const float *rendervertex3f;
6997 bih_leaf_t *bihleafs;
6998 bih_node_t *bihnodes;
7000 int *temp_leafsortscratch;
7001 const msurface_t *surface;
7002 const q3mbrush_t *brush;
7004 // find out how many BIH leaf nodes we need
7006 if (userendersurfaces)
7008 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7009 bihnumleafs += surface->num_triangles;
7013 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7014 if (brush->colbrushf)
7016 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7018 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7019 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7021 bihnumleafs += surface->num_collisiontriangles;
7028 // allocate the memory for the BIH leaf nodes
7029 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7031 // now populate the BIH leaf nodes
7034 // add render surfaces
7035 renderelement3i = model->surfmesh.data_element3i;
7036 rendervertex3f = model->surfmesh.data_vertex3f;
7037 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7039 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7041 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7043 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7044 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7045 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7046 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7047 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7048 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7049 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7050 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7051 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7052 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7057 if (!userendersurfaces)
7059 // add collision brushes
7060 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7062 if (!brush->colbrushf)
7064 bihleafs[bihleafindex].type = BIH_BRUSH;
7065 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7066 bihleafs[bihleafindex].surfaceindex = -1;
7067 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7068 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7069 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7073 // add collision surfaces
7074 collisionelement3i = model->brush.data_collisionelement3i;
7075 collisionvertex3f = model->brush.data_collisionvertex3f;
7076 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7078 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7080 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7081 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7082 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7083 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7084 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7085 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7086 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7087 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7088 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7089 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7095 // allocate buffers for the produced and temporary data
7096 bihmaxnodes = bihnumleafs + 1;
7097 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7098 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7099 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7102 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7104 // we're done with the temporary data
7105 Mem_Free(temp_leafsort);
7107 // resize the BIH nodes array if it over-allocated
7108 if (out->maxnodes > out->numnodes)
7110 out->maxnodes = out->numnodes;
7111 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7117 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7119 int supercontents = 0;
7120 if (nativecontents & CONTENTSQ3_SOLID)
7121 supercontents |= SUPERCONTENTS_SOLID;
7122 if (nativecontents & CONTENTSQ3_WATER)
7123 supercontents |= SUPERCONTENTS_WATER;
7124 if (nativecontents & CONTENTSQ3_SLIME)
7125 supercontents |= SUPERCONTENTS_SLIME;
7126 if (nativecontents & CONTENTSQ3_LAVA)
7127 supercontents |= SUPERCONTENTS_LAVA;
7128 if (nativecontents & CONTENTSQ3_BODY)
7129 supercontents |= SUPERCONTENTS_BODY;
7130 if (nativecontents & CONTENTSQ3_CORPSE)
7131 supercontents |= SUPERCONTENTS_CORPSE;
7132 if (nativecontents & CONTENTSQ3_NODROP)
7133 supercontents |= SUPERCONTENTS_NODROP;
7134 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7135 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7136 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7137 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7138 if (nativecontents & CONTENTSQ3_DONOTENTER)
7139 supercontents |= SUPERCONTENTS_DONOTENTER;
7140 if (nativecontents & CONTENTSQ3_BOTCLIP)
7141 supercontents |= SUPERCONTENTS_BOTCLIP;
7142 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7143 supercontents |= SUPERCONTENTS_OPAQUE;
7144 return supercontents;
7147 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7149 int nativecontents = 0;
7150 if (supercontents & SUPERCONTENTS_SOLID)
7151 nativecontents |= CONTENTSQ3_SOLID;
7152 if (supercontents & SUPERCONTENTS_WATER)
7153 nativecontents |= CONTENTSQ3_WATER;
7154 if (supercontents & SUPERCONTENTS_SLIME)
7155 nativecontents |= CONTENTSQ3_SLIME;
7156 if (supercontents & SUPERCONTENTS_LAVA)
7157 nativecontents |= CONTENTSQ3_LAVA;
7158 if (supercontents & SUPERCONTENTS_BODY)
7159 nativecontents |= CONTENTSQ3_BODY;
7160 if (supercontents & SUPERCONTENTS_CORPSE)
7161 nativecontents |= CONTENTSQ3_CORPSE;
7162 if (supercontents & SUPERCONTENTS_NODROP)
7163 nativecontents |= CONTENTSQ3_NODROP;
7164 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7165 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7166 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7167 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7168 if (supercontents & SUPERCONTENTS_DONOTENTER)
7169 nativecontents |= CONTENTSQ3_DONOTENTER;
7170 if (supercontents & SUPERCONTENTS_BOTCLIP)
7171 nativecontents |= CONTENTSQ3_BOTCLIP;
7172 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7173 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7174 return nativecontents;
7177 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7182 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7183 node = node->children[1];
7185 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7186 if (loadmodel->brush.num_leafs < numleafs)
7187 loadmodel->brush.num_leafs = numleafs;
7190 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7193 q3dheader_t *header;
7194 float corner[3], yawradius, modelradius;
7196 mod->modeldatatypestring = "Q3BSP";
7198 mod->type = mod_brushq3;
7199 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7202 header = (q3dheader_t *)buffer;
7203 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7204 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7206 i = LittleLong(header->version);
7207 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7208 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7210 mod->soundfromcenter = true;
7211 mod->TraceBox = Mod_Q3BSP_TraceBox;
7212 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7213 mod->TraceLine = Mod_Q3BSP_TraceLine;
7214 mod->TracePoint = Mod_Q3BSP_TracePoint;
7215 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7216 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7217 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7218 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7219 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7220 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7221 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7222 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7223 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7224 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7225 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7226 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7227 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7228 mod->brush.AmbientSoundLevelsForPoint = NULL;
7229 mod->brush.RoundUpToHullSize = NULL;
7230 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7231 mod->Draw = R_Q1BSP_Draw;
7232 mod->DrawDepth = R_Q1BSP_DrawDepth;
7233 mod->DrawDebug = R_Q1BSP_DrawDebug;
7234 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7235 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7236 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7237 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7238 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7239 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7240 mod->DrawLight = R_Q1BSP_DrawLight;
7242 mod_base = (unsigned char *)header;
7244 // swap all the lumps
7245 header->ident = LittleLong(header->ident);
7246 header->version = LittleLong(header->version);
7247 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7248 for (i = 0;i < lumps;i++)
7250 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7251 if((char *) bufferend < (char *) buffer + j)
7252 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7253 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7254 if((char *) bufferend < (char *) buffer + j)
7255 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7258 * NO, do NOT clear them!
7259 * they contain actual data referenced by other stuff.
7260 * Instead, before using the advertisements lump, check header->versio
7262 * Sorry, but otherwise it breaks memory of the first lump.
7263 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7265 header->lumps[i].fileofs = 0;
7266 header->lumps[i].filelen = 0;
7270 mod->brush.qw_md4sum = 0;
7271 mod->brush.qw_md4sum2 = 0;
7272 for (i = 0;i < lumps;i++)
7274 if (i == Q3LUMP_ENTITIES)
7276 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7277 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7279 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7281 // all this checksumming can take a while, so let's send keepalives here too
7282 CL_KeepaliveMessage(false);
7285 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7286 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7287 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7288 if (header->version == Q3BSPVERSION_IG)
7289 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7291 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7292 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7293 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7294 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7295 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7296 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7297 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7298 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7299 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7300 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7301 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7302 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7303 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7304 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7305 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7307 // the MakePortals code works fine on the q3bsp data as well
7308 if (mod_bsp_portalize.integer)
7309 Mod_Q1BSP_MakePortals();
7311 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7312 loadmodel->brush.supportwateralpha = true;
7314 // make a single combined shadow mesh to allow optimized shadow volume creation
7315 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7317 loadmodel->brush.num_leafs = 0;
7318 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7320 if (loadmodel->brush.numsubmodels)
7321 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7324 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7329 // duplicate the basic information
7330 dpsnprintf(name, sizeof(name), "*%i", i);
7331 mod = Mod_FindName(name, loadmodel->name);
7332 // copy the base model to this one
7334 // rename the clone back to its proper name
7335 strlcpy(mod->name, name, sizeof(mod->name));
7336 mod->brush.parentmodel = loadmodel;
7337 // textures and memory belong to the main model
7338 mod->texturepool = NULL;
7339 mod->mempool = NULL;
7340 mod->brush.GetPVS = NULL;
7341 mod->brush.FatPVS = NULL;
7342 mod->brush.BoxTouchingPVS = NULL;
7343 mod->brush.BoxTouchingLeafPVS = NULL;
7344 mod->brush.BoxTouchingVisibleLeafs = NULL;
7345 mod->brush.FindBoxClusters = NULL;
7346 mod->brush.LightPoint = NULL;
7347 mod->brush.AmbientSoundLevelsForPoint = NULL;
7349 mod->brush.submodel = i;
7350 if (loadmodel->brush.submodels)
7351 loadmodel->brush.submodels[i] = mod;
7353 // make the model surface list (used by shadowing/lighting)
7354 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7355 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7356 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7357 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7358 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7359 Mod_MakeSortedSurfaces(mod);
7361 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7362 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7363 // enlarge the bounding box to enclose all geometry of this model,
7364 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7365 // which can in turn mess up the farclip (as well as culling when
7366 // outside the level - an unimportant concern)
7368 //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]);
7369 for (j = 0;j < mod->nummodelsurfaces;j++)
7371 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7372 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7374 if (!surface->num_vertices)
7376 for (k = 0;k < surface->num_vertices;k++, v += 3)
7378 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7379 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7380 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7381 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7382 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7383 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7386 //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]);
7387 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7388 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7389 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7390 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7391 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7392 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7393 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7394 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7395 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7396 mod->yawmins[2] = mod->normalmins[2];
7397 mod->yawmaxs[2] = mod->normalmaxs[2];
7398 mod->radius = modelradius;
7399 mod->radius2 = modelradius * modelradius;
7401 // this gets altered below if sky or water is used
7402 mod->DrawSky = NULL;
7403 mod->DrawAddWaterPlanes = NULL;
7405 for (j = 0;j < mod->nummodelsurfaces;j++)
7406 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7408 if (j < mod->nummodelsurfaces)
7409 mod->DrawSky = R_Q1BSP_DrawSky;
7411 for (j = 0;j < mod->nummodelsurfaces;j++)
7412 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7414 if (j < mod->nummodelsurfaces)
7415 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7417 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7418 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7420 // generate VBOs and other shared data before cloning submodels
7425 if (mod_q3bsp_sRGBlightmaps.integer)
7427 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7429 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7430 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7431 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7432 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7433 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7435 else // if this is NOT set, regular rendering looks right by this requirement anyway
7438 // we want color 1 to do the same as without sRGB
7439 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7440 loadmodel->lightmapscale *= 2.476923f; // fixes max level
7443 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7444 // we need to undo that
7445 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7449 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);
7452 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7454 int i = LittleLong(((int *)buffer)[1]);
7455 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7456 Mod_Q3BSP_Load(mod,buffer, bufferend);
7457 else if (i == Q2BSPVERSION)
7458 Mod_Q2BSP_Load(mod,buffer, bufferend);
7460 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7463 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7465 Host_Error("Mod_MAP_Load: not yet implemented");
7468 typedef struct objvertex_s
7479 static unsigned char nobsp_pvs[1] = {1};
7481 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7483 const char *textbase = (char *)buffer, *text = textbase;
7487 char materialname[MAX_QPATH];
7488 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7489 int index1, index2, index3;
7490 objvertex_t vfirst, vprev, vcurrent;
7493 int numtriangles = 0;
7494 int maxtriangles = 0;
7495 objvertex_t *vertices = NULL;
7497 int maxtextures = 0, numtextures = 0, textureindex = 0;
7498 int maxv = 0, numv = 1;
7499 int maxvt = 0, numvt = 1;
7500 int maxvn = 0, numvn = 1;
7501 char *texturenames = NULL;
7502 float dist, modelradius, modelyawradius, yawradius;
7509 objvertex_t *thisvertex = NULL;
7510 int vertexhashindex;
7511 int *vertexhashtable = NULL;
7512 objvertex_t *vertexhashdata = NULL;
7513 objvertex_t *vdata = NULL;
7514 int vertexhashsize = 0;
7515 int vertexhashcount = 0;
7516 skinfile_t *skinfiles = NULL;
7517 unsigned char *data = NULL;
7518 int *submodelfirstsurface;
7519 msurface_t *surface;
7520 msurface_t *tempsurfaces;
7522 memset(&vfirst, 0, sizeof(vfirst));
7523 memset(&vprev, 0, sizeof(vprev));
7524 memset(&vcurrent, 0, sizeof(vcurrent));
7526 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7528 loadmodel->modeldatatypestring = "OBJ";
7530 loadmodel->type = mod_obj;
7531 loadmodel->soundfromcenter = true;
7532 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7533 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7534 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7535 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7536 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7537 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7538 loadmodel->brush.TraceLineOfSight = NULL;
7539 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7540 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7541 loadmodel->brush.GetPVS = NULL;
7542 loadmodel->brush.FatPVS = NULL;
7543 loadmodel->brush.BoxTouchingPVS = NULL;
7544 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7545 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7546 loadmodel->brush.FindBoxClusters = NULL;
7547 loadmodel->brush.LightPoint = NULL;
7548 loadmodel->brush.FindNonSolidLocation = NULL;
7549 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7550 loadmodel->brush.RoundUpToHullSize = NULL;
7551 loadmodel->brush.PointInLeaf = NULL;
7552 loadmodel->Draw = R_Q1BSP_Draw;
7553 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7554 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7555 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7556 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7557 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7558 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7559 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7560 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7561 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7563 skinfiles = Mod_LoadSkinFiles();
7564 if (loadmodel->numskins < 1)
7565 loadmodel->numskins = 1;
7567 // make skinscenes for the skins (no groups)
7568 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7569 for (i = 0;i < loadmodel->numskins;i++)
7571 loadmodel->skinscenes[i].firstframe = i;
7572 loadmodel->skinscenes[i].framecount = 1;
7573 loadmodel->skinscenes[i].loop = true;
7574 loadmodel->skinscenes[i].framerate = 10;
7580 // we always have model 0, i.e. the first "submodel"
7581 loadmodel->brush.numsubmodels = 1;
7583 // parse the OBJ text now
7586 static char emptyarg[1] = "";
7591 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7592 line[linelen] = text[linelen];
7594 for (argc = 0;argc < 4;argc++)
7595 argv[argc] = emptyarg;
7598 while (*s == ' ' || *s == '\t')
7608 while (*s == ' ' || *s == '\t')
7618 if (argv[0][0] == '#')
7620 if (!strcmp(argv[0], "v"))
7624 maxv = max(maxv * 2, 1024);
7625 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7627 if(mod_obj_orientation.integer)
7629 v[numv*3+0] = atof(argv[1]);
7630 v[numv*3+2] = atof(argv[2]);
7631 v[numv*3+1] = atof(argv[3]);
7635 v[numv*3+0] = atof(argv[1]);
7636 v[numv*3+1] = atof(argv[2]);
7637 v[numv*3+2] = atof(argv[3]);
7641 else if (!strcmp(argv[0], "vt"))
7645 maxvt = max(maxvt * 2, 1024);
7646 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7648 vt[numvt*2+0] = atof(argv[1]);
7649 vt[numvt*2+1] = 1-atof(argv[2]);
7652 else if (!strcmp(argv[0], "vn"))
7656 maxvn = max(maxvn * 2, 1024);
7657 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7659 if(mod_obj_orientation.integer)
7661 vn[numvn*3+0] = atof(argv[1]);
7662 vn[numvn*3+2] = atof(argv[2]);
7663 vn[numvn*3+1] = atof(argv[3]);
7667 vn[numvn*3+0] = atof(argv[1]);
7668 vn[numvn*3+1] = atof(argv[2]);
7669 vn[numvn*3+2] = atof(argv[3]);
7673 else if (!strcmp(argv[0], "f"))
7677 if (maxtextures <= numtextures)
7679 maxtextures = max(maxtextures * 2, 256);
7680 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7682 textureindex = numtextures++;
7683 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7685 for (j = 1;j < argc;j++)
7687 index1 = atoi(argv[j]);
7688 while(argv[j][0] && argv[j][0] != '/')
7692 index2 = atoi(argv[j]);
7693 while(argv[j][0] && argv[j][0] != '/')
7697 index3 = atoi(argv[j]);
7698 // negative refers to a recent vertex
7699 // zero means not specified
7700 // positive means an absolute vertex index
7702 index1 = numv - index1;
7704 index2 = numvt - index2;
7706 index3 = numvn - index3;
7707 vcurrent.nextindex = -1;
7708 vcurrent.textureindex = textureindex;
7709 vcurrent.submodelindex = submodelindex;
7710 if (v && index1 >= 0 && index1 < numv)
7711 VectorCopy(v + 3*index1, vcurrent.v);
7712 if (vt && index2 >= 0 && index2 < numvt)
7713 Vector2Copy(vt + 2*index2, vcurrent.vt);
7714 if (vn && index3 >= 0 && index3 < numvn)
7715 VectorCopy(vn + 3*index3, vcurrent.vn);
7716 if (numtriangles == 0)
7718 VectorCopy(vcurrent.v, mins);
7719 VectorCopy(vcurrent.v, maxs);
7723 mins[0] = min(mins[0], vcurrent.v[0]);
7724 mins[1] = min(mins[1], vcurrent.v[1]);
7725 mins[2] = min(mins[2], vcurrent.v[2]);
7726 maxs[0] = max(maxs[0], vcurrent.v[0]);
7727 maxs[1] = max(maxs[1], vcurrent.v[1]);
7728 maxs[2] = max(maxs[2], vcurrent.v[2]);
7734 if (maxtriangles <= numtriangles)
7736 maxtriangles = max(maxtriangles * 2, 32768);
7737 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7739 if(mod_obj_orientation.integer)
7741 vertices[numtriangles*3+0] = vfirst;
7742 vertices[numtriangles*3+1] = vprev;
7743 vertices[numtriangles*3+2] = vcurrent;
7747 vertices[numtriangles*3+0] = vfirst;
7748 vertices[numtriangles*3+2] = vprev;
7749 vertices[numtriangles*3+1] = vcurrent;
7756 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7758 submodelindex = atof(argv[1]);
7759 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7761 else if (!strcmp(argv[0], "usemtl"))
7763 for (i = 0;i < numtextures;i++)
7764 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7766 if (i < numtextures)
7770 if (maxtextures <= numtextures)
7772 maxtextures = max(maxtextures * 2, 256);
7773 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7775 textureindex = numtextures++;
7776 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7781 // now that we have the OBJ data loaded as-is, we can convert it
7783 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7784 VectorCopy(mins, loadmodel->normalmins);
7785 VectorCopy(maxs, loadmodel->normalmaxs);
7786 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7787 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7788 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7789 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7790 modelradius = modelyawradius + modelradius * modelradius;
7791 modelyawradius = sqrt(modelyawradius);
7792 modelradius = sqrt(modelradius);
7793 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7794 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7795 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7796 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7797 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7798 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7799 loadmodel->radius = modelradius;
7800 loadmodel->radius2 = modelradius * modelradius;
7802 // allocate storage for triangles
7803 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7804 // allocate vertex hash structures to build an optimal vertex subset
7805 vertexhashsize = numtriangles*2;
7806 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7807 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7808 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7809 vertexhashcount = 0;
7811 // gather surface stats for assigning vertex/triangle ranges
7815 loadmodel->num_surfaces = 0;
7816 // allocate storage for the worst case number of surfaces, later we resize
7817 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7818 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7819 surface = tempsurfaces;
7820 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7822 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7823 for (textureindex = 0;textureindex < numtextures;textureindex++)
7825 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7827 thisvertex = vertices + vertexindex;
7828 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7831 // skip the surface creation if there are no triangles for it
7832 if (vertexindex == numtriangles*3)
7834 // create a surface for these vertices
7835 surfacevertices = 0;
7836 surfaceelements = 0;
7837 // we hack in a texture index in the surface to be fixed up later...
7838 surface->texture = (texture_t *)((size_t)textureindex);
7839 // calculate bounds as we go
7840 VectorCopy(thisvertex->v, surface->mins);
7841 VectorCopy(thisvertex->v, surface->maxs);
7842 for (;vertexindex < numtriangles*3;vertexindex++)
7844 thisvertex = vertices + vertexindex;
7845 if (thisvertex->submodelindex != submodelindex)
7847 if (thisvertex->textureindex != textureindex)
7849 // add vertex to surface bounds
7850 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7851 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7852 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7853 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7854 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7855 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7856 // add the vertex if it is not found in the merged set, and
7857 // get its index (triangle element) for the surface
7858 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7859 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7861 vdata = vertexhashdata + i;
7862 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7867 i = vertexhashcount++;
7868 vdata = vertexhashdata + i;
7869 *vdata = *thisvertex;
7870 vdata->nextindex = vertexhashtable[vertexhashindex];
7871 vertexhashtable[vertexhashindex] = i;
7874 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7877 surfacetriangles = surfaceelements / 3;
7878 surface->num_vertices = surfacevertices;
7879 surface->num_triangles = surfacetriangles;
7880 surface->num_firstvertex = firstvertex;
7881 surface->num_firsttriangle = firsttriangle;
7882 firstvertex += surface->num_vertices;
7883 firsttriangle += surface->num_triangles;
7885 loadmodel->num_surfaces++;
7888 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7889 numvertices = firstvertex;
7890 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7891 tempsurfaces = NULL;
7893 // allocate storage for final mesh data
7894 loadmodel->num_textures = numtextures * loadmodel->numskins;
7895 loadmodel->num_texturesperskin = numtextures;
7896 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 *));
7897 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7898 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7899 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7900 loadmodel->surfmesh.num_vertices = numvertices;
7901 loadmodel->surfmesh.num_triangles = numtriangles;
7902 if (r_enableshadowvolumes.integer)
7903 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7904 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7905 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7906 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7907 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7908 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7909 if (loadmodel->surfmesh.num_vertices <= 65536)
7910 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7912 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7914 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7915 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7916 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7919 // load the textures
7920 for (textureindex = 0;textureindex < numtextures;textureindex++)
7921 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7922 Mod_FreeSkinFiles(skinfiles);
7924 // set the surface textures to their real values now that we loaded them...
7925 for (i = 0;i < loadmodel->num_surfaces;i++)
7926 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7930 Mem_Free(texturenames);
7934 Mem_Free(vertexhashtable);
7935 Mem_Free(vertexhashdata);
7937 // make a single combined shadow mesh to allow optimized shadow volume creation
7938 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7940 // compute all the mesh information that was not loaded from the file
7941 if (loadmodel->surfmesh.data_element3s)
7942 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7943 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7944 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7945 // generate normals if the file did not have them
7946 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7947 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);
7948 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);
7949 if (loadmodel->surfmesh.data_neighbor3i)
7950 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7952 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7953 loadmodel->brush.num_visleafs = 1;
7954 loadmodel->brush.num_leafs = 1;
7955 loadmodel->brush.num_nodes = 0;
7956 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7957 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7958 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7959 loadmodel->brush.num_pvsclusters = 1;
7960 loadmodel->brush.num_pvsclusterbytes = 1;
7961 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7962 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7963 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7964 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7965 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7966 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7967 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7968 loadmodel->brush.data_leafs->clusterindex = 0;
7969 loadmodel->brush.data_leafs->areaindex = 0;
7970 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7971 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7972 loadmodel->brush.data_leafs->numleafbrushes = 0;
7973 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7974 loadmodel->brush.supportwateralpha = true;
7976 if (loadmodel->brush.numsubmodels)
7977 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7980 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7985 // duplicate the basic information
7986 dpsnprintf(name, sizeof(name), "*%i", i);
7987 mod = Mod_FindName(name, loadmodel->name);
7988 // copy the base model to this one
7990 // rename the clone back to its proper name
7991 strlcpy(mod->name, name, sizeof(mod->name));
7992 mod->brush.parentmodel = loadmodel;
7993 // textures and memory belong to the main model
7994 mod->texturepool = NULL;
7995 mod->mempool = NULL;
7996 mod->brush.GetPVS = NULL;
7997 mod->brush.FatPVS = NULL;
7998 mod->brush.BoxTouchingPVS = NULL;
7999 mod->brush.BoxTouchingLeafPVS = NULL;
8000 mod->brush.BoxTouchingVisibleLeafs = NULL;
8001 mod->brush.FindBoxClusters = NULL;
8002 mod->brush.LightPoint = NULL;
8003 mod->brush.AmbientSoundLevelsForPoint = NULL;
8005 mod->brush.submodel = i;
8006 if (loadmodel->brush.submodels)
8007 loadmodel->brush.submodels[i] = mod;
8009 // make the model surface list (used by shadowing/lighting)
8010 mod->firstmodelsurface = submodelfirstsurface[i];
8011 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8012 mod->firstmodelbrush = 0;
8013 mod->nummodelbrushes = 0;
8014 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8015 Mod_MakeSortedSurfaces(mod);
8017 VectorClear(mod->normalmins);
8018 VectorClear(mod->normalmaxs);
8020 for (j = 0;j < mod->nummodelsurfaces;j++)
8022 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8023 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8025 if (!surface->num_vertices)
8030 VectorCopy(v, mod->normalmins);
8031 VectorCopy(v, mod->normalmaxs);
8033 for (k = 0;k < surface->num_vertices;k++, v += 3)
8035 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
8036 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
8037 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
8038 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
8039 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
8040 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
8043 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8044 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8045 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8046 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8047 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8048 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8049 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8050 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8051 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8052 mod->yawmins[2] = mod->normalmins[2];
8053 mod->yawmaxs[2] = mod->normalmaxs[2];
8054 mod->radius = modelradius;
8055 mod->radius2 = modelradius * modelradius;
8057 // this gets altered below if sky or water is used
8058 mod->DrawSky = NULL;
8059 mod->DrawAddWaterPlanes = NULL;
8061 for (j = 0;j < mod->nummodelsurfaces;j++)
8062 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8064 if (j < mod->nummodelsurfaces)
8065 mod->DrawSky = R_Q1BSP_DrawSky;
8067 for (j = 0;j < mod->nummodelsurfaces;j++)
8068 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8070 if (j < mod->nummodelsurfaces)
8071 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8073 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8074 mod->render_bih = mod->collision_bih;
8076 // generate VBOs and other shared data before cloning submodels
8081 Mem_Free(submodelfirstsurface);
8083 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);