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 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"};
43 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)"};
44 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
45 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)"};
46 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)"};
47 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
48 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
49 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, ..."};
50 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)"};
51 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
52 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
53 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"};
54 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
55 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
56 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
57 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
58 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"};
59 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"};
61 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)"};
62 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"};
63 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"};
65 static texture_t mod_q1bsp_texture_solid;
66 static texture_t mod_q1bsp_texture_sky;
67 static texture_t mod_q1bsp_texture_lava;
68 static texture_t mod_q1bsp_texture_slime;
69 static texture_t mod_q1bsp_texture_water;
71 void Mod_BrushInit(void)
73 // Cvar_RegisterVariable(&r_subdivide_size);
74 Cvar_RegisterVariable(&mod_bsp_portalize);
75 Cvar_RegisterVariable(&r_novis);
76 Cvar_RegisterVariable(&r_nosurftextures);
77 Cvar_RegisterVariable(&r_subdivisions_tolerance);
78 Cvar_RegisterVariable(&r_subdivisions_mintess);
79 Cvar_RegisterVariable(&r_subdivisions_maxtess);
80 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
81 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
82 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
83 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
84 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
85 Cvar_RegisterVariable(&r_trippy);
86 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
87 Cvar_RegisterVariable(&mod_obj_orientation);
88 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
89 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
90 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
91 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
92 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
93 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
94 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
95 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
96 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
97 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
98 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
99 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
100 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
101 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
102 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
103 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
104 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
105 Cvar_RegisterVariable(&mod_collision_bih);
106 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
108 // these games were made for older DP engines and are no longer
109 // maintained; use this hack to show their textures properly
110 if(gamemode == GAME_NEXUIZ)
111 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
113 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
114 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
115 mod_q1bsp_texture_solid.surfaceflags = 0;
116 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
118 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
119 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
120 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
121 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
123 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
124 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
125 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
126 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
128 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
129 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
130 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
131 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
133 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
134 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
135 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
136 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
139 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
146 // LordHavoc: modified to start at first clip node,
147 // in other words: first node of the (sub)model
148 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
150 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
152 return (mleaf_t *)node;
155 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
159 leaf = Mod_Q1BSP_PointInLeaf(model, p);
162 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
165 memcpy(out, leaf->ambient_sound_level, i);
171 memset(out, 0, outsize);
174 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
177 int nodestackindex = 0;
178 mnode_t *node, *nodestack[1024];
179 if (!model->brush.num_pvsclusters)
181 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
187 // node - recurse down the BSP tree
188 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
192 return -1; // ERROR: NAN bounding box!
193 // box is on one side of plane, take that path
194 node = node->children[sides-1];
198 // box crosses plane, take one path and remember the other
199 if (nodestackindex < 1024)
200 nodestack[nodestackindex++] = node->children[0];
201 node = node->children[1];
207 // leaf - add clusterindex to list
208 if (numclusters < maxclusters)
209 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
213 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
217 if (nodestackindex < 1024)
218 nodestack[nodestackindex++] = node->children[0];
219 node = node->children[1];
224 // leaf - add clusterindex to list
225 if (numclusters < maxclusters)
226 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
231 // try another path we didn't take earlier
232 if (nodestackindex == 0)
234 node = nodestack[--nodestackindex];
236 // return number of clusters found (even if more than the maxclusters)
240 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
242 int nodestackindex = 0;
243 mnode_t *node, *nodestack[1024];
244 if (!model->brush.num_pvsclusters)
246 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
252 // node - recurse down the BSP tree
253 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
257 return -1; // ERROR: NAN bounding box!
258 // box is on one side of plane, take that path
259 node = node->children[sides-1];
263 // box crosses plane, take one path and remember the other
264 if (nodestackindex < 1024)
265 nodestack[nodestackindex++] = node->children[0];
266 node = node->children[1];
272 // leaf - check cluster bit
273 int clusterindex = ((mleaf_t *)node)->clusterindex;
274 if (CHECKPVSBIT(pvs, clusterindex))
276 // it is visible, return immediately with the news
281 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
285 if (nodestackindex < 1024)
286 nodestack[nodestackindex++] = node->children[0];
287 node = node->children[1];
292 // leaf - check cluster bit
293 int clusterindex = ((mleaf_t *)node)->clusterindex;
294 if (CHECKPVSBIT(pvs, clusterindex))
296 // it is visible, return immediately with the news
302 // nothing to see here, try another path we didn't take earlier
303 if (nodestackindex == 0)
305 node = nodestack[--nodestackindex];
311 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
313 int nodestackindex = 0;
314 mnode_t *node, *nodestack[1024];
315 if (!model->brush.num_leafs)
317 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
323 // node - recurse down the BSP tree
324 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
328 return -1; // ERROR: NAN bounding box!
329 // box is on one side of plane, take that path
330 node = node->children[sides-1];
334 // box crosses plane, take one path and remember the other
335 if (nodestackindex < 1024)
336 nodestack[nodestackindex++] = node->children[0];
337 node = node->children[1];
343 // leaf - check cluster bit
344 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
345 if (CHECKPVSBIT(pvs, clusterindex))
347 // it is visible, return immediately with the news
352 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
356 if (nodestackindex < 1024)
357 nodestack[nodestackindex++] = node->children[0];
358 node = node->children[1];
363 // leaf - check cluster bit
364 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
365 if (CHECKPVSBIT(pvs, clusterindex))
367 // it is visible, return immediately with the news
373 // nothing to see here, try another path we didn't take earlier
374 if (nodestackindex == 0)
376 node = nodestack[--nodestackindex];
382 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
384 int nodestackindex = 0;
385 mnode_t *node, *nodestack[1024];
386 if (!model->brush.num_leafs)
388 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
394 // node - recurse down the BSP tree
395 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
399 return -1; // ERROR: NAN bounding box!
400 // box is on one side of plane, take that path
401 node = node->children[sides-1];
405 // box crosses plane, take one path and remember the other
406 if (nodestackindex < 1024)
407 nodestack[nodestackindex++] = node->children[0];
408 node = node->children[1];
414 // leaf - check if it is visible
415 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
417 // it is visible, return immediately with the news
422 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
426 if (nodestackindex < 1024)
427 nodestack[nodestackindex++] = node->children[0];
428 node = node->children[1];
433 // leaf - check if it is visible
434 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
436 // it is visible, return immediately with the news
442 // nothing to see here, try another path we didn't take earlier
443 if (nodestackindex == 0)
445 node = nodestack[--nodestackindex];
451 typedef struct findnonsolidlocationinfo_s
454 vec3_t absmin, absmax;
460 findnonsolidlocationinfo_t;
462 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
465 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
467 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
468 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
469 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
470 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
471 VectorSubtract(vert[1], vert[0], edge[0]);
472 VectorSubtract(vert[2], vert[1], edge[1]);
473 CrossProduct(edge[1], edge[0], facenormal);
474 if (facenormal[0] || facenormal[1] || facenormal[2])
476 VectorNormalize(facenormal);
477 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
478 if (f <= info->bestdist && f >= -info->bestdist)
480 VectorSubtract(vert[0], vert[2], edge[2]);
481 VectorNormalize(edge[0]);
482 VectorNormalize(edge[1]);
483 VectorNormalize(edge[2]);
484 CrossProduct(facenormal, edge[0], edgenormal[0]);
485 CrossProduct(facenormal, edge[1], edgenormal[1]);
486 CrossProduct(facenormal, edge[2], edgenormal[2]);
488 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
489 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
490 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
492 // we got lucky, the center is within the face
493 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
497 if (info->bestdist > dist)
499 info->bestdist = dist;
500 VectorScale(facenormal, (info->radius - -dist), info->nudge);
505 if (info->bestdist > dist)
507 info->bestdist = dist;
508 VectorScale(facenormal, (info->radius - dist), info->nudge);
514 // check which edge or vertex the center is nearest
515 for (i = 0;i < 3;i++)
517 f = DotProduct(info->center, edge[i]);
518 if (f >= DotProduct(vert[0], edge[i])
519 && f <= DotProduct(vert[1], edge[i]))
522 VectorMA(info->center, -f, edge[i], point);
523 dist = sqrt(DotProduct(point, point));
524 if (info->bestdist > dist)
526 info->bestdist = dist;
527 VectorScale(point, (info->radius / dist), info->nudge);
529 // skip both vertex checks
530 // (both are further away than this edge)
535 // not on edge, check first vertex of edge
536 VectorSubtract(info->center, vert[i], point);
537 dist = sqrt(DotProduct(point, point));
538 if (info->bestdist > dist)
540 info->bestdist = dist;
541 VectorScale(point, (info->radius / dist), info->nudge);
550 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
552 int surfacenum, k, *mark;
554 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
556 surface = info->model->data_surfaces + *mark;
557 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
559 if(surface->deprecatedq3num_bboxstride > 0)
562 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
563 for(i = 0; i < cnt; ++i)
565 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
567 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
569 tri = i * surface->deprecatedq3num_bboxstride + k;
570 if(tri >= surface->num_triangles)
572 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
579 for (k = 0;k < surface->num_triangles;k++)
581 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
588 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
592 float f = PlaneDiff(info->center, node->plane);
593 if (f >= -info->bestdist)
594 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
595 if (f <= info->bestdist)
596 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
600 if (((mleaf_t *)node)->numleafsurfaces)
601 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
605 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
608 findnonsolidlocationinfo_t info;
614 VectorCopy(in, info.center);
615 info.radius = radius;
620 VectorClear(info.nudge);
621 info.bestdist = radius;
622 VectorCopy(info.center, info.absmin);
623 VectorCopy(info.center, info.absmax);
624 info.absmin[0] -= info.radius + 1;
625 info.absmin[1] -= info.radius + 1;
626 info.absmin[2] -= info.radius + 1;
627 info.absmax[0] += info.radius + 1;
628 info.absmax[1] += info.radius + 1;
629 info.absmax[2] += info.radius + 1;
630 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
631 VectorAdd(info.center, info.nudge, info.center);
633 while (info.bestdist < radius && ++i < 10);
634 VectorCopy(info.center, out);
637 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
639 switch(nativecontents)
644 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
646 return SUPERCONTENTS_WATER;
648 return SUPERCONTENTS_SLIME;
650 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
652 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
657 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
659 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
660 return CONTENTS_SOLID;
661 if (supercontents & SUPERCONTENTS_SKY)
663 if (supercontents & SUPERCONTENTS_LAVA)
664 return CONTENTS_LAVA;
665 if (supercontents & SUPERCONTENTS_SLIME)
666 return CONTENTS_SLIME;
667 if (supercontents & SUPERCONTENTS_WATER)
668 return CONTENTS_WATER;
669 return CONTENTS_EMPTY;
672 typedef struct RecursiveHullCheckTraceInfo_s
674 // the hull we're tracing through
677 // the trace structure to fill in
680 // start, end, and end - start (in model space)
685 RecursiveHullCheckTraceInfo_t;
687 // 1/32 epsilon to keep floating point happy
688 #define DIST_EPSILON (0.03125)
690 #define HULLCHECKSTATE_EMPTY 0
691 #define HULLCHECKSTATE_SOLID 1
692 #define HULLCHECKSTATE_DONE 2
694 extern cvar_t collision_prefernudgedfraction;
695 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
697 // status variables, these don't need to be saved on the stack when
698 // recursing... but are because this should be thread-safe
699 // (note: tracing against a bbox is not thread-safe, yet)
704 // variables that need to be stored on the stack when recursing
709 // LordHavoc: a goto! everyone flee in terror... :)
714 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
715 if (!t->trace->startfound)
717 t->trace->startfound = true;
718 t->trace->startsupercontents |= num;
720 if (num & SUPERCONTENTS_LIQUIDSMASK)
721 t->trace->inwater = true;
723 t->trace->inopen = true;
724 if (num & SUPERCONTENTS_SOLID)
725 t->trace->hittexture = &mod_q1bsp_texture_solid;
726 else if (num & SUPERCONTENTS_SKY)
727 t->trace->hittexture = &mod_q1bsp_texture_sky;
728 else if (num & SUPERCONTENTS_LAVA)
729 t->trace->hittexture = &mod_q1bsp_texture_lava;
730 else if (num & SUPERCONTENTS_SLIME)
731 t->trace->hittexture = &mod_q1bsp_texture_slime;
733 t->trace->hittexture = &mod_q1bsp_texture_water;
734 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
735 t->trace->hitsupercontents = num;
736 if (num & t->trace->hitsupercontentsmask)
738 // if the first leaf is solid, set startsolid
739 if (t->trace->allsolid)
740 t->trace->startsolid = true;
741 #if COLLISIONPARANOID >= 3
744 return HULLCHECKSTATE_SOLID;
748 t->trace->allsolid = false;
749 #if COLLISIONPARANOID >= 3
752 return HULLCHECKSTATE_EMPTY;
756 // find the point distances
757 node = t->hull->clipnodes + num;
759 plane = t->hull->planes + node->planenum;
762 t1 = p1[plane->type] - plane->dist;
763 t2 = p2[plane->type] - plane->dist;
767 t1 = DotProduct (plane->normal, p1) - plane->dist;
768 t2 = DotProduct (plane->normal, p2) - plane->dist;
775 #if COLLISIONPARANOID >= 3
778 num = node->children[1];
787 #if COLLISIONPARANOID >= 3
790 num = node->children[0];
796 // the line intersects, find intersection point
797 // LordHavoc: this uses the original trace for maximum accuracy
798 #if COLLISIONPARANOID >= 3
803 t1 = t->start[plane->type] - plane->dist;
804 t2 = t->end[plane->type] - plane->dist;
808 t1 = DotProduct (plane->normal, t->start) - plane->dist;
809 t2 = DotProduct (plane->normal, t->end) - plane->dist;
812 midf = t1 / (t1 - t2);
813 midf = bound(p1f, midf, p2f);
814 VectorMA(t->start, midf, t->dist, mid);
816 // recurse both sides, front side first
817 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
818 // if this side is not empty, return what it is (solid or done)
819 if (ret != HULLCHECKSTATE_EMPTY)
822 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
823 // if other side is not solid, return what it is (empty or done)
824 if (ret != HULLCHECKSTATE_SOLID)
827 // front is air and back is solid, this is the impact point...
830 t->trace->plane.dist = -plane->dist;
831 VectorNegate (plane->normal, t->trace->plane.normal);
835 t->trace->plane.dist = plane->dist;
836 VectorCopy (plane->normal, t->trace->plane.normal);
839 // calculate the true fraction
840 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
841 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
842 midf = t1 / (t1 - t2);
843 t->trace->realfraction = bound(0, midf, 1);
845 // calculate the return fraction which is nudged off the surface a bit
846 midf = (t1 - DIST_EPSILON) / (t1 - t2);
847 t->trace->fraction = bound(0, midf, 1);
849 if (collision_prefernudgedfraction.integer)
850 t->trace->realfraction = t->trace->fraction;
852 #if COLLISIONPARANOID >= 3
855 return HULLCHECKSTATE_DONE;
858 //#if COLLISIONPARANOID < 2
859 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
862 mclipnode_t *nodes = t->hull->clipnodes;
863 mplane_t *planes = t->hull->planes;
865 VectorCopy(t->start, point);
868 plane = planes + nodes[num].planenum;
869 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
871 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
872 t->trace->startsupercontents |= num;
873 if (num & SUPERCONTENTS_LIQUIDSMASK)
874 t->trace->inwater = true;
876 t->trace->inopen = true;
877 if (num & t->trace->hitsupercontentsmask)
879 t->trace->allsolid = t->trace->startsolid = true;
880 return HULLCHECKSTATE_SOLID;
884 t->trace->allsolid = t->trace->startsolid = false;
885 return HULLCHECKSTATE_EMPTY;
890 static void Mod_Q1BSP_TracePoint(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
892 RecursiveHullCheckTraceInfo_t rhc;
894 memset(&rhc, 0, sizeof(rhc));
895 memset(trace, 0, sizeof(trace_t));
897 rhc.trace->fraction = 1;
898 rhc.trace->realfraction = 1;
899 rhc.trace->allsolid = true;
900 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
901 VectorCopy(start, rhc.start);
902 VectorCopy(start, rhc.end);
903 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
906 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)
908 RecursiveHullCheckTraceInfo_t rhc;
910 if (VectorCompare(start, end))
912 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
916 memset(&rhc, 0, sizeof(rhc));
917 memset(trace, 0, sizeof(trace_t));
919 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
920 rhc.trace->fraction = 1;
921 rhc.trace->realfraction = 1;
922 rhc.trace->allsolid = true;
923 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
924 VectorCopy(start, rhc.start);
925 VectorCopy(end, rhc.end);
926 VectorSubtract(rhc.end, rhc.start, rhc.dist);
927 #if COLLISIONPARANOID >= 2
928 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]);
929 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
934 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
935 memset(&testtrace, 0, sizeof(trace_t));
936 rhc.trace = &testtrace;
937 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
938 rhc.trace->fraction = 1;
939 rhc.trace->realfraction = 1;
940 rhc.trace->allsolid = true;
941 VectorCopy(test, rhc.start);
942 VectorCopy(test, rhc.end);
943 VectorClear(rhc.dist);
944 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
945 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
946 if (!trace->startsolid && testtrace.startsolid)
947 Con_Printf(" - ended in solid!\n");
951 if (VectorLength2(rhc.dist))
952 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
954 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
958 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)
960 // this function currently only supports same size start and end
962 RecursiveHullCheckTraceInfo_t rhc;
964 if (VectorCompare(boxmins, boxmaxs))
966 if (VectorCompare(start, end))
967 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
969 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
973 memset(&rhc, 0, sizeof(rhc));
974 memset(trace, 0, sizeof(trace_t));
976 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
977 rhc.trace->fraction = 1;
978 rhc.trace->realfraction = 1;
979 rhc.trace->allsolid = true;
980 VectorSubtract(boxmaxs, boxmins, boxsize);
982 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
983 else if (model->brush.ishlbsp)
985 // LordHavoc: this has to have a minor tolerance (the .1) because of
986 // minor float precision errors from the box being transformed around
987 if (boxsize[0] < 32.1)
989 if (boxsize[2] < 54) // pick the nearest of 36 or 72
990 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
992 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
995 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
999 // LordHavoc: this has to have a minor tolerance (the .1) because of
1000 // minor float precision errors from the box being transformed around
1001 if (boxsize[0] < 32.1)
1002 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1004 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1006 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1007 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1008 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1009 #if COLLISIONPARANOID >= 2
1010 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]);
1011 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1016 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1017 memset(&testtrace, 0, sizeof(trace_t));
1018 rhc.trace = &testtrace;
1019 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1020 rhc.trace->fraction = 1;
1021 rhc.trace->realfraction = 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 trace->realfraction = 1;
1091 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1093 RecursiveHullCheckTraceInfo_t rhc;
1094 static hull_t box_hull;
1095 static mclipnode_t box_clipnodes[6];
1096 static mplane_t box_planes[6];
1097 // fill in a default trace
1098 memset(&rhc, 0, sizeof(rhc));
1099 memset(trace, 0, sizeof(trace_t));
1100 //To keep everything totally uniform, bounding boxes are turned into small
1101 //BSP trees instead of being compared directly.
1102 // create a temp hull from bounding box sizes
1103 box_planes[0].dist = cmaxs[0] - mins[0];
1104 box_planes[1].dist = cmins[0] - maxs[0];
1105 box_planes[2].dist = cmaxs[1] - mins[1];
1106 box_planes[3].dist = cmins[1] - maxs[1];
1107 box_planes[4].dist = cmaxs[2] - mins[2];
1108 box_planes[5].dist = cmins[2] - maxs[2];
1109 #if COLLISIONPARANOID >= 3
1110 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]);
1113 if (box_hull.clipnodes == NULL)
1117 //Set up the planes and clipnodes so that the six floats of a bounding box
1118 //can just be stored out and get a proper hull_t structure.
1120 box_hull.clipnodes = box_clipnodes;
1121 box_hull.planes = box_planes;
1122 box_hull.firstclipnode = 0;
1123 box_hull.lastclipnode = 5;
1125 for (i = 0;i < 6;i++)
1127 box_clipnodes[i].planenum = i;
1131 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1133 box_clipnodes[i].children[side^1] = i + 1;
1135 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1137 box_planes[i].type = i>>1;
1138 box_planes[i].normal[i>>1] = 1;
1142 // trace a line through the generated clipping hull
1143 //rhc.boxsupercontents = boxsupercontents;
1144 rhc.hull = &box_hull;
1146 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1147 rhc.trace->fraction = 1;
1148 rhc.trace->realfraction = 1;
1149 rhc.trace->allsolid = true;
1150 VectorCopy(start, rhc.start);
1151 VectorCopy(end, rhc.end);
1152 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1153 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1154 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1155 if (rhc.trace->startsupercontents)
1156 rhc.trace->startsupercontents = boxsupercontents;
1160 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1162 memset(trace, 0, sizeof(trace_t));
1163 trace->fraction = 1;
1164 trace->realfraction = 1;
1165 if (BoxesOverlap(start, start, cmins, cmaxs))
1167 trace->startsupercontents |= boxsupercontents;
1168 if (hitsupercontentsmask & boxsupercontents)
1170 trace->startsolid = true;
1171 trace->allsolid = true;
1176 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1179 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1180 return trace.fraction == 1;
1183 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)
1187 float mid, distz = endz - startz;
1191 return false; // didn't hit anything
1193 switch (node->plane->type)
1196 node = node->children[x < node->plane->dist];
1199 node = node->children[y < node->plane->dist];
1202 side = startz < node->plane->dist;
1203 if ((endz < node->plane->dist) == side)
1205 node = node->children[side];
1208 // found an intersection
1209 mid = node->plane->dist;
1212 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1213 front += startz * node->plane->normal[2];
1214 back += endz * node->plane->normal[2];
1215 side = front < node->plane->dist;
1216 if ((back < node->plane->dist) == side)
1218 node = node->children[side];
1221 // found an intersection
1222 mid = startz + distz * (front - node->plane->dist) / (front - back);
1226 // go down front side
1227 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1228 return true; // hit something
1231 // check for impact on this node
1232 if (node->numsurfaces)
1235 int dsi, dti, lmwidth, lmheight;
1237 msurface_t *surface;
1238 unsigned char *lightmap;
1239 int maps, line3, size3;
1242 float scale, w, w00, w01, w10, w11;
1244 surface = model->data_surfaces + node->firstsurface;
1245 for (i = 0;i < node->numsurfaces;i++, surface++)
1247 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1248 continue; // no lightmaps
1250 // location we want to sample in the lightmap
1251 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;
1252 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;
1257 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1258 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1261 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1263 // calculate bilinear interpolation factors
1264 // and also multiply by fixedpoint conversion factors
1267 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1268 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1269 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1270 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1272 // values for pointer math
1273 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1274 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1276 // look up the pixel
1277 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1279 // bilinear filter each lightmap style, and sum them
1280 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1282 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1283 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1284 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1285 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1286 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1290 return true; // success
1295 // go down back side
1296 node = node->children[side ^ 1];
1298 distz = endz - startz;
1303 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1305 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1306 VectorSet(diffusenormal, 0, 0, 1);
1308 if (!model->brushq1.lightdata)
1310 VectorSet(ambientcolor, 1, 1, 1);
1311 VectorSet(diffusecolor, 0, 0, 0);
1315 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);
1318 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1323 const msurface_t *surface;
1328 float edgenormal[3];
1335 surface = model->data_surfaces + node->firstsurface;
1336 for (i = 0;i < node->numsurfaces;i++, surface++)
1338 // skip surfaces whose bounding box does not include the point
1339 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1341 // skip faces with contents we don't care about
1342 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1344 // get the surface normal - since it is flat we know any vertex normal will suffice
1345 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1347 if (DotProduct(t->dist, normal) > 0)
1349 // iterate edges and see if the point is outside one of them
1350 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1352 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1353 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1354 VectorSubtract(v0, v1, edgedir);
1355 CrossProduct(edgedir, normal, edgenormal);
1356 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1359 // if the point is outside one of the edges, it is not within the surface
1360 if (j < surface->num_vertices)
1363 // we hit a surface, this is the impact point...
1364 VectorCopy(normal, t->trace->plane.normal);
1365 t->trace->plane.dist = DotProduct(normal, p);
1367 // calculate the true fraction
1368 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1369 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1370 midf = t1 / (t1 - t2);
1371 t->trace->realfraction = midf;
1373 // calculate the return fraction which is nudged off the surface a bit
1374 midf = (t1 - DIST_EPSILON) / (t1 - t2);
1375 t->trace->fraction = bound(0, midf, 1);
1377 if (collision_prefernudgedfraction.integer)
1378 t->trace->realfraction = t->trace->fraction;
1380 t->trace->hittexture = surface->texture->currentframe;
1381 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1382 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1383 return surface->texture->currentframe;
1388 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])
1390 const mplane_t *plane;
1393 double midf, mid[3];
1394 const mleaf_t *leaf;
1398 plane = node->plane;
1399 if (plane->type < 3)
1401 t1 = p1[plane->type] - plane->dist;
1402 t2 = p2[plane->type] - plane->dist;
1406 t1 = DotProduct (plane->normal, p1) - plane->dist;
1407 t2 = DotProduct (plane->normal, p2) - plane->dist;
1413 node = node->children[1];
1422 node = node->children[0];
1428 // the line intersects, find intersection point
1429 // LordHavoc: this uses the original trace for maximum accuracy
1430 if (plane->type < 3)
1432 t1 = t->start[plane->type] - plane->dist;
1433 t2 = t->end[plane->type] - plane->dist;
1437 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1438 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1441 midf = t1 / (t1 - t2);
1442 VectorMA(t->start, midf, t->dist, mid);
1444 // recurse both sides, front side first, return if we hit a surface
1445 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1446 return HULLCHECKSTATE_DONE;
1448 // test each surface on the node
1449 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1450 if (t->trace->hittexture)
1451 return HULLCHECKSTATE_DONE;
1453 // recurse back side
1454 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1456 leaf = (const mleaf_t *)node;
1457 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1458 if (!t->trace->startfound)
1460 t->trace->startfound = true;
1461 t->trace->startsupercontents |= side;
1463 if (side & SUPERCONTENTS_LIQUIDSMASK)
1464 t->trace->inwater = true;
1466 t->trace->inopen = true;
1467 if (side & t->trace->hitsupercontentsmask)
1469 // if the first leaf is solid, set startsolid
1470 if (t->trace->allsolid)
1471 t->trace->startsolid = true;
1472 return HULLCHECKSTATE_SOLID;
1476 t->trace->allsolid = false;
1477 return HULLCHECKSTATE_EMPTY;
1481 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)
1483 RecursiveHullCheckTraceInfo_t rhc;
1485 memset(&rhc, 0, sizeof(rhc));
1486 memset(trace, 0, sizeof(trace_t));
1488 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1489 rhc.trace->fraction = 1;
1490 rhc.trace->realfraction = 1;
1491 rhc.trace->allsolid = true;
1492 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1493 VectorCopy(start, rhc.start);
1494 VectorCopy(end, rhc.end);
1495 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1496 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1497 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1500 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1503 unsigned char *outstart = out;
1504 while (out < outend)
1508 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));
1518 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));
1521 for (c = *in++;c > 0;c--)
1525 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));
1536 R_Q1BSP_LoadSplitSky
1538 A sky texture is 256*128, with the right side being a masked overlay
1541 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1546 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1547 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1549 // allocate a texture pool if we need it
1550 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1551 loadmodel->texturepool = R_AllocTexturePool();
1553 if (bytesperpixel == 4)
1555 for (y = 0;y < h;y++)
1557 for (x = 0;x < w;x++)
1559 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1560 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1566 // make an average value for the back to avoid
1567 // a fringe on the top level
1576 for (y = 0;y < h;y++)
1578 for (x = 0;x < w;x++)
1580 p = src[x*width+y+w];
1581 r += palette_rgb[p][0];
1582 g += palette_rgb[p][1];
1583 b += palette_rgb[p][2];
1586 bgra.b[2] = r/(w*h);
1587 bgra.b[1] = g/(w*h);
1588 bgra.b[0] = b/(w*h);
1590 for (y = 0;y < h;y++)
1592 for (x = 0;x < w;x++)
1594 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1596 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1601 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1602 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1603 Mem_Free(solidpixels);
1604 Mem_Free(alphapixels);
1607 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1609 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1610 skinframe_t *skinframe;
1611 texture_t *tx, *tx2, *anims[10], *altanims[10];
1612 texture_t backuptex;
1613 unsigned char *data, *mtdata;
1615 char mapname[MAX_QPATH], name[MAX_QPATH];
1616 unsigned char zeroopaque[4], zerotrans[4];
1619 Vector4Set(zeroopaque, 0, 0, 0, 255);
1620 Vector4Set(zerotrans, 0, 0, 0, 128);
1622 loadmodel->data_textures = NULL;
1624 // add two slots for notexture walls and notexture liquids
1627 nummiptex = MSG_ReadLittleLong(sb);
1628 loadmodel->num_textures = nummiptex + 2;
1629 loadmodel->num_texturesperskin = loadmodel->num_textures;
1633 loadmodel->num_textures = 2;
1634 loadmodel->num_texturesperskin = loadmodel->num_textures;
1637 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1639 // fill out all slots with notexture
1640 if (cls.state != ca_dedicated)
1641 skinframe = R_SkinFrame_LoadMissing();
1644 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1646 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1649 if (cls.state != ca_dedicated)
1651 tx->numskinframes = 1;
1652 tx->skinframerate = 1;
1653 tx->skinframes[0] = skinframe;
1654 tx->currentskinframe = tx->skinframes[0];
1656 tx->basematerialflags = MATERIALFLAG_WALL;
1657 if (i == loadmodel->num_textures - 1)
1659 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1660 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1661 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1665 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1666 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1668 tx->currentframe = tx;
1670 // clear water settings
1673 tx->refractfactor = 1;
1674 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1675 tx->reflectfactor = 1;
1676 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1677 tx->r_water_wateralpha = 1;
1678 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1679 tx->offsetscale = 1;
1681 tx->specularscalemod = 1;
1682 tx->specularpowermod = 1;
1683 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1684 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1685 // JUST GREP FOR "specularscalemod = 1".
1690 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1694 s = loadmodel->name;
1695 if (!strncasecmp(s, "maps/", 5))
1697 FS_StripExtension(s, mapname, sizeof(mapname));
1699 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1700 // LordHavoc: mostly rewritten map texture loader
1701 for (i = 0;i < nummiptex;i++)
1703 doffset = MSG_ReadLittleLong(sb);
1704 if (r_nosurftextures.integer)
1708 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1712 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1714 // copy name, but only up to 16 characters
1715 // (the output buffer can hold more than this, but the input buffer is
1717 for (j = 0;j < 16;j++)
1718 name[j] = MSG_ReadByte(&miptexsb);
1720 // pretty up the buffer (replacing any trailing garbage with 0)
1721 for (j = strlen(name);j < 16;j++)
1726 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1727 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1730 mtwidth = MSG_ReadLittleLong(&miptexsb);
1731 mtheight = MSG_ReadLittleLong(&miptexsb);
1733 j = MSG_ReadLittleLong(&miptexsb);
1737 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1739 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1742 mtdata = miptexsb.data + j;
1745 if ((mtwidth & 15) || (mtheight & 15))
1746 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1748 // LordHavoc: force all names to lowercase
1749 for (j = 0;name[j];j++)
1750 if (name[j] >= 'A' && name[j] <= 'Z')
1751 name[j] += 'a' - 'A';
1753 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1754 backuptex = loadmodel->data_textures[i];
1755 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1757 loadmodel->data_textures[i] = backuptex;
1759 tx = loadmodel->data_textures + i;
1760 strlcpy(tx->name, name, sizeof(tx->name));
1761 tx->width = mtwidth;
1762 tx->height = mtheight;
1764 if (tx->name[0] == '*')
1766 if (!strncmp(tx->name, "*lava", 5))
1768 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1769 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1771 else if (!strncmp(tx->name, "*slime", 6))
1773 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1774 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1778 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1779 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1782 else if (!strncmp(tx->name, "sky", 3))
1784 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1785 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1786 tx->supercontents |= SUPERCONTENTS_SOLID; // for the surface traceline we need to hit this surface as a solid...
1790 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1791 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1794 if (cls.state != ca_dedicated)
1796 // LordHavoc: HL sky textures are entirely different than quake
1797 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1799 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1801 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1802 if (data && image_width == image_height * 2)
1804 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1807 else if (mtdata != NULL)
1808 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1812 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);
1814 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);
1816 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1819 // did not find external texture, load it from the bsp or wad3
1820 if (loadmodel->brush.ishlbsp)
1822 // internal texture overrides wad
1823 unsigned char *pixels, *freepixels;
1824 pixels = freepixels = NULL;
1826 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1828 pixels = freepixels = W_GetTextureBGRA(tx->name);
1831 tx->width = image_width;
1832 tx->height = image_height;
1833 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1836 Mem_Free(freepixels);
1838 else if (mtdata) // texture included
1839 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1841 // if skinframe is still NULL the "missing" texture will be used
1843 tx->skinframes[0] = skinframe;
1845 // LordHavoc: some Tenebrae textures get replaced by black
1846 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1847 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1848 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1849 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1852 tx->basematerialflags = MATERIALFLAG_WALL;
1853 if (tx->name[0] == '*')
1855 // LordHavoc: some turbulent textures should not be affected by wateralpha
1856 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1857 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1858 else if (!strncmp(tx->name,"*lava",5)
1859 || !strncmp(tx->name,"*teleport",9)
1860 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1861 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1863 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1864 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1865 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1867 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1869 // replace the texture with black
1870 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1872 else if (!strncmp(tx->name, "sky", 3))
1873 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1874 else if (!strcmp(tx->name, "caulk"))
1875 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1876 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1877 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1879 // start out with no animation
1880 tx->currentframe = tx;
1881 tx->currentskinframe = tx->skinframes[0];
1882 tx->currentmaterialflags = tx->basematerialflags;
1885 // sequence the animations
1886 for (i = 0;i < nummiptex;i++)
1888 tx = loadmodel->data_textures + i;
1889 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1891 if (tx->anim_total[0] || tx->anim_total[1])
1892 continue; // already sequenced
1894 // find the number of frames in the animation
1895 memset(anims, 0, sizeof(anims));
1896 memset(altanims, 0, sizeof(altanims));
1898 for (j = i;j < nummiptex;j++)
1900 tx2 = loadmodel->data_textures + j;
1901 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1905 if (num >= '0' && num <= '9')
1906 anims[num - '0'] = tx2;
1907 else if (num >= 'a' && num <= 'j')
1908 altanims[num - 'a'] = tx2;
1910 Con_Printf("Bad animating texture %s\n", tx->name);
1914 for (j = 0;j < 10;j++)
1921 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1924 for (j = 0;j < max;j++)
1928 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1932 for (j = 0;j < altmax;j++)
1936 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1945 // if there is no alternate animation, duplicate the primary
1946 // animation into the alternate
1948 for (k = 0;k < 10;k++)
1949 altanims[k] = anims[k];
1952 // link together the primary animation
1953 for (j = 0;j < max;j++)
1956 tx2->animated = true;
1957 tx2->anim_total[0] = max;
1958 tx2->anim_total[1] = altmax;
1959 for (k = 0;k < 10;k++)
1961 tx2->anim_frames[0][k] = anims[k];
1962 tx2->anim_frames[1][k] = altanims[k];
1966 // if there really is an alternate anim...
1967 if (anims[0] != altanims[0])
1969 // link together the alternate animation
1970 for (j = 0;j < altmax;j++)
1973 tx2->animated = true;
1974 // the primary/alternate are reversed here
1975 tx2->anim_total[0] = altmax;
1976 tx2->anim_total[1] = max;
1977 for (k = 0;k < 10;k++)
1979 tx2->anim_frames[0][k] = altanims[k];
1980 tx2->anim_frames[1][k] = anims[k];
1987 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
1990 unsigned char *in, *out, *data, d;
1991 char litfilename[MAX_QPATH];
1992 char dlitfilename[MAX_QPATH];
1993 fs_offset_t filesize;
1994 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1996 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
1997 for (i = 0;i < sb->cursize;i++)
1998 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2000 else // LordHavoc: bsp version 29 (normal white lighting)
2002 // LordHavoc: hope is not lost yet, check for a .lit file to load
2003 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2004 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2005 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2006 strlcat (litfilename, ".lit", sizeof (litfilename));
2007 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2008 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2011 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2013 i = LittleLong(((int *)data)[1]);
2016 if (developer_loading.integer)
2017 Con_Printf("loaded %s\n", litfilename);
2018 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2019 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2021 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2024 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2026 i = LittleLong(((int *)data)[1]);
2029 if (developer_loading.integer)
2030 Con_Printf("loaded %s\n", dlitfilename);
2031 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2032 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2033 loadmodel->brushq3.deluxemapping_modelspace = false;
2034 loadmodel->brushq3.deluxemapping = true;
2043 Con_Printf("Unknown .lit file version (%d)\n", i);
2045 else if (filesize == 8)
2046 Con_Print("Empty .lit file, ignoring\n");
2048 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2055 // LordHavoc: oh well, expand the white lighting data
2058 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2060 out = loadmodel->brushq1.lightdata;
2061 for (i = 0;i < sb->cursize;i++)
2071 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2073 loadmodel->brushq1.num_compressedpvs = 0;
2074 loadmodel->brushq1.data_compressedpvs = NULL;
2077 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2078 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2079 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2082 // used only for HalfLife maps
2083 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2085 char key[128], value[4096];
2089 if (!COM_ParseToken_Simple(&data, false, false, true))
2091 if (com_token[0] != '{')
2095 if (!COM_ParseToken_Simple(&data, false, false, true))
2097 if (com_token[0] == '}')
2098 break; // end of worldspawn
2099 if (com_token[0] == '_')
2100 strlcpy(key, com_token + 1, sizeof(key));
2102 strlcpy(key, com_token, sizeof(key));
2103 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2104 key[strlen(key)-1] = 0;
2105 if (!COM_ParseToken_Simple(&data, false, false, true))
2107 dpsnprintf(value, sizeof(value), "%s", com_token);
2108 if (!strcmp("wad", key)) // for HalfLife maps
2110 if (loadmodel->brush.ishlbsp)
2113 for (i = 0;i < (int)sizeof(value);i++)
2114 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2118 for (;i < (int)sizeof(value);i++)
2120 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2121 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2123 else if (value[i] == ';' || value[i] == 0)
2127 W_LoadTextureWadFile(&value[j], false);
2139 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2141 loadmodel->brush.entities = NULL;
2144 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2145 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2146 loadmodel->brush.entities[sb->cursize] = 0;
2147 if (loadmodel->brush.ishlbsp)
2148 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2152 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2156 size_t structsize = 12;
2158 if (sb->cursize % structsize)
2159 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2160 count = sb->cursize / structsize;
2161 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2163 loadmodel->brushq1.vertexes = out;
2164 loadmodel->brushq1.numvertexes = count;
2166 for ( i=0 ; i<count ; i++, out++)
2168 out->position[0] = MSG_ReadLittleFloat(sb);
2169 out->position[1] = MSG_ReadLittleFloat(sb);
2170 out->position[2] = MSG_ReadLittleFloat(sb);
2174 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2178 size_t structsize = (48+4*hullinfo->filehulls);
2180 if (sb->cursize % structsize)
2181 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2183 count = sb->cursize / structsize;
2184 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2186 loadmodel->brushq1.submodels = out;
2187 loadmodel->brush.numsubmodels = count;
2189 for (i = 0; i < count; i++, out++)
2191 // spread out the mins / maxs by a pixel
2192 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2193 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2194 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2195 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2196 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2197 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2198 out->origin[0] = MSG_ReadLittleFloat(sb);
2199 out->origin[1] = MSG_ReadLittleFloat(sb);
2200 out->origin[2] = MSG_ReadLittleFloat(sb);
2201 for (j = 0; j < hullinfo->filehulls; j++)
2202 out->headnode[j] = MSG_ReadLittleLong(sb);
2203 out->visleafs = MSG_ReadLittleLong(sb);
2204 out->firstface = MSG_ReadLittleLong(sb);
2205 out->numfaces = MSG_ReadLittleLong(sb);
2209 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2213 size_t structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2215 if (sb->cursize % structsize)
2216 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2217 count = sb->cursize / structsize;
2218 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2220 loadmodel->brushq1.edges = out;
2221 loadmodel->brushq1.numedges = count;
2223 for ( i=0 ; i<count ; i++, out++)
2225 if (loadmodel->brush.isbsp2)
2227 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2228 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2232 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2233 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2235 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2237 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);
2238 if(!loadmodel->brushq1.numvertexes)
2239 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2247 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2250 int i, j, k, count, miptex;
2251 size_t structsize = 40;
2253 if (sb->cursize % structsize)
2254 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2255 count = sb->cursize / structsize;
2256 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2258 loadmodel->brushq1.texinfo = out;
2259 loadmodel->brushq1.numtexinfo = count;
2261 for (i = 0;i < count;i++, out++)
2263 for (k = 0;k < 2;k++)
2264 for (j = 0;j < 4;j++)
2265 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2267 miptex = MSG_ReadLittleLong(sb);
2268 out->flags = MSG_ReadLittleLong(sb);
2270 out->texture = NULL;
2271 if (loadmodel->data_textures)
2273 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2274 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2276 out->texture = loadmodel->data_textures + miptex;
2278 if (out->flags & TEX_SPECIAL)
2280 // if texture chosen is NULL or the shader needs a lightmap,
2281 // force to notexture water shader
2282 if (out->texture == NULL)
2283 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2287 // if texture chosen is NULL, force to notexture
2288 if (out->texture == NULL)
2289 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2295 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2300 mins[0] = mins[1] = mins[2] = 9999;
2301 maxs[0] = maxs[1] = maxs[2] = -9999;
2303 for (i = 0;i < numverts;i++)
2305 for (j = 0;j < 3;j++, v++)
2315 #define MAX_SUBDIVPOLYTRIANGLES 4096
2316 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2318 static int subdivpolyverts, subdivpolytriangles;
2319 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2320 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2322 static int subdivpolylookupvert(vec3_t v)
2325 for (i = 0;i < subdivpolyverts;i++)
2326 if (subdivpolyvert[i][0] == v[0]
2327 && subdivpolyvert[i][1] == v[1]
2328 && subdivpolyvert[i][2] == v[2])
2330 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2331 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2332 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2333 return subdivpolyverts++;
2336 static void SubdividePolygon(int numverts, float *verts)
2338 int i, i1, i2, i3, f, b, c, p;
2339 vec3_t mins, maxs, front[256], back[256];
2340 float m, *pv, *cv, dist[256], frac;
2343 Host_Error("SubdividePolygon: ran out of verts in buffer");
2345 BoundPoly(numverts, verts, mins, maxs);
2347 for (i = 0;i < 3;i++)
2349 m = (mins[i] + maxs[i]) * 0.5;
2350 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2351 if (maxs[i] - m < 8)
2353 if (m - mins[i] < 8)
2357 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2358 dist[c] = cv[i] - m;
2361 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2365 VectorCopy(pv, front[f]);
2370 VectorCopy(pv, back[b]);
2373 if (dist[p] == 0 || dist[c] == 0)
2375 if ((dist[p] > 0) != (dist[c] > 0) )
2378 frac = dist[p] / (dist[p] - dist[c]);
2379 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2380 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2381 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2387 SubdividePolygon(f, front[0]);
2388 SubdividePolygon(b, back[0]);
2392 i1 = subdivpolylookupvert(verts);
2393 i2 = subdivpolylookupvert(verts + 3);
2394 for (i = 2;i < numverts;i++)
2396 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2398 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2402 i3 = subdivpolylookupvert(verts + i * 3);
2403 subdivpolyindex[subdivpolytriangles][0] = i1;
2404 subdivpolyindex[subdivpolytriangles][1] = i2;
2405 subdivpolyindex[subdivpolytriangles][2] = i3;
2407 subdivpolytriangles++;
2411 //Breaks a polygon up along axial 64 unit
2412 //boundaries so that turbulent and sky warps
2413 //can be done reasonably.
2414 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2420 subdivpolytriangles = 0;
2421 subdivpolyverts = 0;
2422 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2423 if (subdivpolytriangles < 1)
2424 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2426 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2427 mesh->num_vertices = subdivpolyverts;
2428 mesh->num_triangles = subdivpolytriangles;
2429 mesh->vertex = (surfvertex_t *)(mesh + 1);
2430 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2431 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2433 for (i = 0;i < mesh->num_triangles;i++)
2434 for (j = 0;j < 3;j++)
2435 mesh->index[i*3+j] = subdivpolyindex[i][j];
2437 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2439 VectorCopy(subdivpolyvert[i], v->v);
2440 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2441 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2446 extern cvar_t gl_max_lightmapsize;
2447 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2449 msurface_t *surface;
2450 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2451 float texmins[2], texmaxs[2], val;
2452 rtexture_t *lightmaptexture, *deluxemaptexture;
2454 size_t structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2456 if (sb->cursize % structsize)
2457 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2458 count = sb->cursize / structsize;
2459 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2460 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2462 loadmodel->num_surfaces = count;
2464 loadmodel->brushq1.firstrender = true;
2465 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2469 for (surfacenum = 0;surfacenum < count;surfacenum++)
2471 if (loadmodel->brush.isbsp2)
2472 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2474 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2475 totalverts += numedges;
2476 totaltris += numedges - 2;
2479 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2481 lightmaptexture = NULL;
2482 deluxemaptexture = r_texture_blanknormalmap;
2484 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2485 totallightmapsamples = 0;
2489 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2491 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2492 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2493 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2494 firstedge = MSG_ReadLittleLong(sb);
2495 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2496 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2497 for (i = 0;i < MAXLIGHTMAPS;i++)
2498 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2499 lightmapoffset = MSG_ReadLittleLong(sb);
2501 // FIXME: validate edges, texinfo, etc?
2502 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)
2503 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2504 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2505 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2506 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2507 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2509 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2510 surface->texture = surface->lightmapinfo->texinfo->texture;
2512 //surface->flags = surface->texture->flags;
2513 //if (LittleShort(in->side))
2514 // surface->flags |= SURF_PLANEBACK;
2515 //surface->plane = loadmodel->brush.data_planes + planenum;
2517 surface->num_firstvertex = totalverts;
2518 surface->num_vertices = numedges;
2519 surface->num_firsttriangle = totaltris;
2520 surface->num_triangles = numedges - 2;
2521 totalverts += numedges;
2522 totaltris += numedges - 2;
2524 // convert edges back to a normal polygon
2525 for (i = 0;i < surface->num_vertices;i++)
2527 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2529 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2531 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2533 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2534 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2535 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2536 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2537 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2538 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2539 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2540 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2543 for (i = 0;i < surface->num_triangles;i++)
2545 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2546 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2547 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2550 // compile additional data about the surface geometry
2551 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);
2552 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);
2553 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2555 // generate surface extents information
2556 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2557 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2558 for (i = 1;i < surface->num_vertices;i++)
2560 for (j = 0;j < 2;j++)
2562 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2563 texmins[j] = min(texmins[j], val);
2564 texmaxs[j] = max(texmaxs[j], val);
2567 for (i = 0;i < 2;i++)
2569 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2570 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2573 smax = surface->lightmapinfo->extents[0] >> 4;
2574 tmax = surface->lightmapinfo->extents[1] >> 4;
2575 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2576 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2579 surface->lightmaptexture = NULL;
2580 surface->deluxemaptexture = r_texture_blanknormalmap;
2581 if (lightmapoffset == -1)
2583 surface->lightmapinfo->samples = NULL;
2585 // give non-lightmapped water a 1x white lightmap
2586 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2588 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2589 surface->lightmapinfo->styles[0] = 0;
2590 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2594 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2595 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2596 else // LordHavoc: white lighting (bsp version 29)
2598 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2599 if (loadmodel->brushq1.nmaplightdata)
2600 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2603 // check if we should apply a lightmap to this
2604 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2606 if (ssize > 256 || tsize > 256)
2607 Host_Error("Bad surface extents");
2609 if (lightmapsize < ssize)
2610 lightmapsize = ssize;
2611 if (lightmapsize < tsize)
2612 lightmapsize = tsize;
2614 totallightmapsamples += ssize*tsize;
2616 // force lightmap upload on first time seeing the surface
2618 // additionally this is used by the later code to see if a
2619 // lightmap is needed on this surface (rather than duplicating the
2621 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2622 loadmodel->lit = true;
2626 // small maps (such as ammo boxes especially) don't need big lightmap
2627 // textures, so this code tries to guess a good size based on
2628 // totallightmapsamples (size of the lightmaps lump basically), as well as
2629 // trying to max out the size if there is a lot of lightmap data to store
2630 // additionally, never choose a lightmapsize that is smaller than the
2631 // largest surface encountered (as it would fail)
2633 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2636 // now that we've decided the lightmap texture size, we can do the rest
2637 if (cls.state != ca_dedicated)
2639 int stainmapsize = 0;
2640 mod_alloclightmap_state_t allocState;
2642 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2643 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2645 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2646 float u, v, ubase, vbase, uscale, vscale;
2648 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2651 smax = surface->lightmapinfo->extents[0] >> 4;
2652 tmax = surface->lightmapinfo->extents[1] >> 4;
2653 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2654 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2655 stainmapsize += ssize * tsize * 3;
2657 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2659 // allocate a texture pool if we need it
2660 if (loadmodel->texturepool == NULL)
2661 loadmodel->texturepool = R_AllocTexturePool();
2662 // could not find room, make a new lightmap
2663 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2664 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2665 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2666 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);
2667 if (loadmodel->brushq1.nmaplightdata)
2668 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);
2670 Mod_AllocLightmap_Reset(&allocState);
2671 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2673 surface->lightmaptexture = lightmaptexture;
2674 surface->deluxemaptexture = deluxemaptexture;
2675 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2676 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2678 uscale = 1.0f / (float)lightmapsize;
2679 vscale = 1.0f / (float)lightmapsize;
2680 ubase = lightmapx * uscale;
2681 vbase = lightmapy * vscale;
2683 for (i = 0;i < surface->num_vertices;i++)
2685 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);
2686 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);
2687 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2688 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2689 // LordHavoc: calc lightmap data offset for vertex lighting to use
2692 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2696 if (cl_stainmaps.integer)
2698 // allocate stainmaps for permanent marks on walls and clear white
2699 unsigned char *stainsamples = NULL;
2700 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2701 memset(stainsamples, 255, stainmapsize);
2703 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2705 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2707 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2708 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2709 surface->lightmapinfo->stainsamples = stainsamples;
2710 stainsamples += ssize * tsize * 3;
2715 // generate ushort elements array if possible
2716 if (loadmodel->surfmesh.data_element3s)
2717 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2718 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2721 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2724 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2725 node->parent = parent;
2728 // this is a node, recurse to children
2729 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2730 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2731 // combine supercontents of children
2732 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2737 mleaf_t *leaf = (mleaf_t *)node;
2738 // if this is a leaf, calculate supercontents mask from all collidable
2739 // primitives in the leaf (brushes and collision surfaces)
2740 // also flag if the leaf contains any collision surfaces
2741 leaf->combinedsupercontents = 0;
2742 // combine the supercontents values of all brushes in this leaf
2743 for (j = 0;j < leaf->numleafbrushes;j++)
2744 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2745 // check if this leaf contains any collision surfaces (q3 patches)
2746 for (j = 0;j < leaf->numleafsurfaces;j++)
2748 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2749 if (surface->num_collisiontriangles)
2751 leaf->containscollisionsurfaces = true;
2752 leaf->combinedsupercontents |= surface->texture->supercontents;
2758 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2760 int i, j, count, p, child[2];
2762 size_t structsize = loadmodel->brush.isbsp2 ? 44 : 24;
2764 if (sb->cursize % structsize)
2765 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2766 count = sb->cursize / structsize;
2768 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2769 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2771 loadmodel->brush.data_nodes = out;
2772 loadmodel->brush.num_nodes = count;
2774 for ( i=0 ; i<count ; i++, out++)
2776 p = MSG_ReadLittleLong(sb);
2777 out->plane = loadmodel->brush.data_planes + p;
2779 if (loadmodel->brush.isbsp2)
2781 child[0] = MSG_ReadLittleLong(sb);
2782 child[1] = MSG_ReadLittleLong(sb);
2783 out->mins[0] = MSG_ReadLittleFloat(sb);
2784 out->mins[1] = MSG_ReadLittleFloat(sb);
2785 out->mins[2] = MSG_ReadLittleFloat(sb);
2786 out->maxs[0] = MSG_ReadLittleFloat(sb);
2787 out->maxs[1] = MSG_ReadLittleFloat(sb);
2788 out->maxs[2] = MSG_ReadLittleFloat(sb);
2789 out->firstsurface = MSG_ReadLittleLong(sb);
2790 out->numsurfaces = MSG_ReadLittleLong(sb);
2794 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2795 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2796 if (child[0] >= count)
2798 if (child[1] >= count)
2801 out->mins[0] = MSG_ReadLittleShort(sb);
2802 out->mins[1] = MSG_ReadLittleShort(sb);
2803 out->mins[2] = MSG_ReadLittleShort(sb);
2804 out->maxs[0] = MSG_ReadLittleShort(sb);
2805 out->maxs[1] = MSG_ReadLittleShort(sb);
2806 out->maxs[2] = MSG_ReadLittleShort(sb);
2808 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2809 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2812 for (j=0 ; j<2 ; j++)
2814 // LordHavoc: this code supports broken bsp files produced by
2815 // arguire qbsp which can produce more than 32768 nodes, any value
2816 // below count is assumed to be a node number, any other value is
2817 // assumed to be a leaf number
2821 if (p < loadmodel->brush.num_nodes)
2822 out->children[j] = loadmodel->brush.data_nodes + p;
2825 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2826 // map it to the solid leaf
2827 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2832 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2834 if (p < loadmodel->brush.num_leafs)
2835 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2838 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2839 // map it to the solid leaf
2840 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2846 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2849 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2852 int i, j, count, p, firstmarksurface, nummarksurfaces;
2853 size_t structsize = loadmodel->brush.isbsp2 ? 44 : 28;
2855 if (sb->cursize % structsize)
2856 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2857 count = sb->cursize / structsize;
2858 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2860 loadmodel->brush.data_leafs = out;
2861 loadmodel->brush.num_leafs = count;
2862 // get visleafs from the submodel data
2863 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2864 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2865 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2866 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2868 // FIXME: this function could really benefit from some error checking
2869 for ( i=0 ; i<count ; i++, out++)
2871 out->contents = MSG_ReadLittleLong(sb);
2873 out->clusterindex = i - 1;
2874 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2875 out->clusterindex = -1;
2877 p = MSG_ReadLittleLong(sb);
2878 // ignore visofs errors on leaf 0 (solid)
2879 if (p >= 0 && out->clusterindex >= 0)
2881 if (p >= loadmodel->brushq1.num_compressedpvs)
2882 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2884 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);
2887 if (loadmodel->brush.isbsp2)
2889 out->mins[0] = MSG_ReadLittleFloat(sb);
2890 out->mins[1] = MSG_ReadLittleFloat(sb);
2891 out->mins[2] = MSG_ReadLittleFloat(sb);
2892 out->maxs[0] = MSG_ReadLittleFloat(sb);
2893 out->maxs[1] = MSG_ReadLittleFloat(sb);
2894 out->maxs[2] = MSG_ReadLittleFloat(sb);
2896 firstmarksurface = MSG_ReadLittleLong(sb);
2897 nummarksurfaces = MSG_ReadLittleLong(sb);
2901 out->mins[0] = MSG_ReadLittleShort(sb);
2902 out->mins[1] = MSG_ReadLittleShort(sb);
2903 out->mins[2] = MSG_ReadLittleShort(sb);
2904 out->maxs[0] = MSG_ReadLittleShort(sb);
2905 out->maxs[1] = MSG_ReadLittleShort(sb);
2906 out->maxs[2] = MSG_ReadLittleShort(sb);
2908 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2909 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2912 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2914 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2915 out->numleafsurfaces = nummarksurfaces;
2919 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2920 out->firstleafsurface = NULL;
2921 out->numleafsurfaces = 0;
2924 for (j = 0;j < 4;j++)
2925 out->ambient_sound_level[j] = MSG_ReadByte(sb);
2929 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2933 const unsigned char *pvs;
2934 // if there's no vis data, assume supported (because everything is visible all the time)
2935 if (!loadmodel->brush.data_pvsclusters)
2937 // check all liquid leafs to see if they can see into empty leafs, if any
2938 // can we can assume this map supports r_wateralpha
2939 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2941 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2943 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2944 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2945 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2952 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
2957 size_t structsize = loadmodel->brush.isbsp2 ? 12 : 8;
2959 if (sb->cursize % structsize)
2960 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2961 count = sb->cursize / structsize;
2962 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2964 loadmodel->brushq1.clipnodes = out;
2965 loadmodel->brushq1.numclipnodes = count;
2967 for (i = 1; i < MAX_MAP_HULLS; i++)
2969 hull = &loadmodel->brushq1.hulls[i];
2970 hull->clipnodes = out;
2971 hull->firstclipnode = 0;
2972 hull->lastclipnode = count-1;
2973 hull->planes = loadmodel->brush.data_planes;
2974 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2975 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2976 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2977 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2978 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2979 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2980 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2983 for (i=0 ; i<count ; i++, out++)
2985 out->planenum = MSG_ReadLittleLong(sb);
2986 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2987 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
2988 if (loadmodel->brush.isbsp2)
2990 out->children[0] = MSG_ReadLittleLong(sb);
2991 out->children[1] = MSG_ReadLittleLong(sb);
2992 if (out->children[0] >= count)
2993 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
2994 if (out->children[1] >= count)
2995 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
2999 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3000 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3001 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3002 if (out->children[0] >= count)
3003 out->children[0] -= 65536;
3004 if (out->children[1] >= count)
3005 out->children[1] -= 65536;
3010 //Duplicate the drawing hull structure as a clipping hull
3011 static void Mod_Q1BSP_MakeHull0(void)
3018 hull = &loadmodel->brushq1.hulls[0];
3020 in = loadmodel->brush.data_nodes;
3021 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3023 hull->clipnodes = out;
3024 hull->firstclipnode = 0;
3025 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3026 hull->planes = loadmodel->brush.data_planes;
3028 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3030 out->planenum = in->plane - loadmodel->brush.data_planes;
3031 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3032 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3036 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3039 size_t structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3041 if (sb->cursize % structsize)
3042 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3043 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3044 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3046 if (loadmodel->brush.isbsp2)
3048 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3050 j = MSG_ReadLittleLong(sb);
3051 if (j < 0 || j >= loadmodel->num_surfaces)
3052 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3053 loadmodel->brush.data_leafsurfaces[i] = j;
3058 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3060 j = (unsigned short) MSG_ReadLittleShort(sb);
3061 if (j >= loadmodel->num_surfaces)
3062 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3063 loadmodel->brush.data_leafsurfaces[i] = j;
3068 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3071 size_t structsize = 4;
3073 if (sb->cursize % structsize)
3074 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3075 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3076 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3078 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3079 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3083 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3087 size_t structsize = 20;
3089 if (sb->cursize % structsize)
3090 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3091 loadmodel->brush.num_planes = sb->cursize / structsize;
3092 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3094 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3096 out->normal[0] = MSG_ReadLittleFloat(sb);
3097 out->normal[1] = MSG_ReadLittleFloat(sb);
3098 out->normal[2] = MSG_ReadLittleFloat(sb);
3099 out->dist = MSG_ReadLittleFloat(sb);
3100 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3105 static void Mod_Q1BSP_LoadMapBrushes(void)
3109 int submodel, numbrushes;
3110 qboolean firstbrush;
3111 char *text, *maptext;
3112 char mapfilename[MAX_QPATH];
3113 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3114 strlcat (mapfilename, ".map", sizeof (mapfilename));
3115 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3119 if (!COM_ParseToken_Simple(&data, false, false, true))
3124 if (!COM_ParseToken_Simple(&data, false, false, true))
3126 if (com_token[0] != '{')
3132 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3135 if (!COM_ParseToken_Simple(&data, false, false, true))
3137 if (com_token[0] == '}')
3138 break; // end of entity
3139 if (com_token[0] == '{')
3146 if (submodel > loadmodel->brush.numsubmodels)
3148 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3152 model = loadmodel->brush.submodels[submodel];
3159 if (!COM_ParseToken_Simple(&data, false, false, true))
3161 if (com_token[0] == '}')
3162 break; // end of brush
3163 // each brush face should be this format:
3164 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3165 // FIXME: support hl .map format
3166 for (pointnum = 0;pointnum < 3;pointnum++)
3168 COM_ParseToken_Simple(&data, false, false, true);
3169 for (componentnum = 0;componentnum < 3;componentnum++)
3171 COM_ParseToken_Simple(&data, false, false, true);
3172 point[pointnum][componentnum] = atof(com_token);
3174 COM_ParseToken_Simple(&data, false, false, true);
3176 COM_ParseToken_Simple(&data, false, false, true);
3177 strlcpy(facetexture, com_token, sizeof(facetexture));
3178 COM_ParseToken_Simple(&data, false, false, true);
3179 //scroll_s = atof(com_token);
3180 COM_ParseToken_Simple(&data, false, false, true);
3181 //scroll_t = atof(com_token);
3182 COM_ParseToken_Simple(&data, false, false, true);
3183 //rotate = atof(com_token);
3184 COM_ParseToken_Simple(&data, false, false, true);
3185 //scale_s = atof(com_token);
3186 COM_ParseToken_Simple(&data, false, false, true);
3187 //scale_t = atof(com_token);
3188 TriangleNormal(point[0], point[1], point[2], planenormal);
3189 VectorNormalizeDouble(planenormal);
3190 planedist = DotProduct(point[0], planenormal);
3191 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3201 #define MAX_PORTALPOINTS 64
3203 typedef struct portal_s
3206 mnode_t *nodes[2]; // [0] = front side of plane
3207 struct portal_s *next[2];
3209 double points[3*MAX_PORTALPOINTS];
3210 struct portal_s *chain; // all portals are linked into a list
3214 static memexpandablearray_t portalarray;
3216 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3218 // process only nodes (leafs already had their box calculated)
3222 // calculate children first
3223 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3224 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3226 // make combined bounding box from children
3227 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3228 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3229 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3230 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3231 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3232 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3235 static void Mod_Q1BSP_FinalizePortals(void)
3237 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
3241 mleaf_t *leaf, *endleaf;
3243 // tally up portal and point counts and recalculate bounding boxes for all
3244 // leafs (because qbsp is very sloppy)
3245 leaf = loadmodel->brush.data_leafs;
3246 endleaf = leaf + loadmodel->brush.num_leafs;
3247 if (mod_recalculatenodeboxes.integer)
3249 for (;leaf < endleaf;leaf++)
3251 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3252 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3257 for (portalindex = 0;portalindex < portalrange;portalindex++)
3259 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3262 // note: this check must match the one below or it will usually corrupt memory
3263 // 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
3264 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3267 numpoints += p->numpoints * 2;
3270 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3271 loadmodel->brush.num_portals = numportals;
3272 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3273 loadmodel->brush.num_portalpoints = numpoints;
3274 // clear all leaf portal chains
3275 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3276 loadmodel->brush.data_leafs[i].portals = NULL;
3277 // process all portals in the global portal chain, while freeing them
3278 portal = loadmodel->brush.data_portals;
3279 point = loadmodel->brush.data_portalpoints;
3280 for (portalindex = 0;portalindex < portalrange;portalindex++)
3282 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3285 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3287 // note: this check must match the one above or it will usually corrupt memory
3288 // 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
3289 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3291 // first make the back to front portal(forward portal)
3292 portal->points = point;
3293 portal->numpoints = p->numpoints;
3294 portal->plane.dist = p->plane.dist;
3295 VectorCopy(p->plane.normal, portal->plane.normal);
3296 portal->here = (mleaf_t *)p->nodes[1];
3297 portal->past = (mleaf_t *)p->nodes[0];
3299 for (j = 0;j < portal->numpoints;j++)
3301 VectorCopy(p->points + j*3, point->position);
3304 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3305 PlaneClassify(&portal->plane);
3307 // link into leaf's portal chain
3308 portal->next = portal->here->portals;
3309 portal->here->portals = portal;
3311 // advance to next portal
3314 // then make the front to back portal(backward portal)
3315 portal->points = point;
3316 portal->numpoints = p->numpoints;
3317 portal->plane.dist = -p->plane.dist;
3318 VectorNegate(p->plane.normal, portal->plane.normal);
3319 portal->here = (mleaf_t *)p->nodes[0];
3320 portal->past = (mleaf_t *)p->nodes[1];
3322 for (j = portal->numpoints - 1;j >= 0;j--)
3324 VectorCopy(p->points + j*3, point->position);
3327 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3328 PlaneClassify(&portal->plane);
3330 // link into leaf's portal chain
3331 portal->next = portal->here->portals;
3332 portal->here->portals = portal;
3334 // advance to next portal
3337 // add the portal's polygon points to the leaf bounding boxes
3338 if (mod_recalculatenodeboxes.integer)
3340 for (i = 0;i < 2;i++)
3342 leaf = (mleaf_t *)p->nodes[i];
3343 for (j = 0;j < p->numpoints;j++)
3345 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3346 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3347 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3348 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3349 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3350 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3356 // now recalculate the node bounding boxes from the leafs
3357 if (mod_recalculatenodeboxes.integer)
3358 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3366 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3369 Host_Error("AddPortalToNodes: NULL front node");
3371 Host_Error("AddPortalToNodes: NULL back node");
3372 if (p->nodes[0] || p->nodes[1])
3373 Host_Error("AddPortalToNodes: already included");
3374 // 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
3376 p->nodes[0] = front;
3377 p->next[0] = (portal_t *)front->portals;
3378 front->portals = (mportal_t *)p;
3381 p->next[1] = (portal_t *)back->portals;
3382 back->portals = (mportal_t *)p;
3387 RemovePortalFromNode
3390 static void RemovePortalFromNodes(portal_t *portal)
3394 void **portalpointer;
3396 for (i = 0;i < 2;i++)
3398 node = portal->nodes[i];
3400 portalpointer = (void **) &node->portals;
3403 t = (portal_t *)*portalpointer;
3405 Host_Error("RemovePortalFromNodes: portal not in leaf");
3409 if (portal->nodes[0] == node)
3411 *portalpointer = portal->next[0];
3412 portal->nodes[0] = NULL;
3414 else if (portal->nodes[1] == node)
3416 *portalpointer = portal->next[1];
3417 portal->nodes[1] = NULL;
3420 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3424 if (t->nodes[0] == node)
3425 portalpointer = (void **) &t->next[0];
3426 else if (t->nodes[1] == node)
3427 portalpointer = (void **) &t->next[1];
3429 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3434 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3435 static double *portalpointsbuffer;
3436 static int portalpointsbufferoffset;
3437 static int portalpointsbuffersize;
3438 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3441 mnode_t *front, *back, *other_node;
3442 mplane_t clipplane, *plane;
3443 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3444 int numfrontpoints, numbackpoints;
3445 double *frontpoints, *backpoints;
3447 // if a leaf, we're done
3451 // get some space for our clipping operations to use
3452 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3454 portalpointsbuffersize = portalpointsbufferoffset * 2;
3455 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3457 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3458 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3459 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3460 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3462 plane = node->plane;
3464 front = node->children[0];
3465 back = node->children[1];
3467 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3469 // create the new portal by generating a polygon for the node plane,
3470 // and clipping it by all of the other portals(which came from nodes above this one)
3471 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3472 nodeportal->plane = *plane;
3474 // 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)
3475 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);
3476 nodeportal->numpoints = 4;
3477 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3478 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3480 clipplane = portal->plane;
3481 if (portal->nodes[0] == portal->nodes[1])
3482 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3483 if (portal->nodes[0] == node)
3485 else if (portal->nodes[1] == node)
3487 clipplane.dist = -clipplane.dist;
3488 VectorNegate(clipplane.normal, clipplane.normal);
3493 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3494 side = 0; // hush warning
3497 for (i = 0;i < nodeportal->numpoints*3;i++)
3498 frontpoints[i] = nodeportal->points[i];
3499 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);
3500 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3504 if (nodeportal->numpoints < 3)
3506 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3507 nodeportal->numpoints = 0;
3509 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3511 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3512 nodeportal->numpoints = 0;
3515 AddPortalToNodes(nodeportal, front, back);
3517 // split the portals of this node along this node's plane and assign them to the children of this node
3518 // (migrating the portals downward through the tree)
3519 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3521 if (portal->nodes[0] == portal->nodes[1])
3522 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3523 if (portal->nodes[0] == node)
3525 else if (portal->nodes[1] == node)
3529 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3530 side = 0; // hush warning
3532 nextportal = portal->next[side];
3533 if (!portal->numpoints)
3536 other_node = portal->nodes[!side];
3537 RemovePortalFromNodes(portal);
3539 // cut the portal into two portals, one on each side of the node plane
3540 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);
3542 if (!numfrontpoints)
3545 AddPortalToNodes(portal, back, other_node);
3547 AddPortalToNodes(portal, other_node, back);
3553 AddPortalToNodes(portal, front, other_node);
3555 AddPortalToNodes(portal, other_node, front);
3559 // the portal is split
3560 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3561 temp = splitportal->chain;
3562 *splitportal = *portal;
3563 splitportal->chain = temp;
3564 for (i = 0;i < numbackpoints*3;i++)
3565 splitportal->points[i] = backpoints[i];
3566 splitportal->numpoints = numbackpoints;
3567 for (i = 0;i < numfrontpoints*3;i++)
3568 portal->points[i] = frontpoints[i];
3569 portal->numpoints = numfrontpoints;
3573 AddPortalToNodes(portal, front, other_node);
3574 AddPortalToNodes(splitportal, back, other_node);
3578 AddPortalToNodes(portal, other_node, front);
3579 AddPortalToNodes(splitportal, other_node, back);
3583 Mod_Q1BSP_RecursiveNodePortals(front);
3584 Mod_Q1BSP_RecursiveNodePortals(back);
3586 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3589 static void Mod_Q1BSP_MakePortals(void)
3591 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3592 portalpointsbufferoffset = 0;
3593 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3594 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3595 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3596 Mem_Free(portalpointsbuffer);
3597 portalpointsbuffer = NULL;
3598 portalpointsbufferoffset = 0;
3599 portalpointsbuffersize = 0;
3600 Mod_Q1BSP_FinalizePortals();
3601 Mem_ExpandableArray_FreeArray(&portalarray);
3604 //Returns PVS data for a given point
3605 //(note: can return NULL)
3606 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3609 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3611 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3612 if (((mleaf_t *)node)->clusterindex >= 0)
3613 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3618 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)
3622 float d = PlaneDiff(org, node->plane);
3624 node = node->children[0];
3625 else if (d < -radius)
3626 node = node->children[1];
3629 // go down both sides
3630 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3631 node = node->children[1];
3634 // if this leaf is in a cluster, accumulate the pvs bits
3635 if (((mleaf_t *)node)->clusterindex >= 0)
3638 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3639 for (i = 0;i < pvsbytes;i++)
3640 pvsbuffer[i] |= pvs[i];
3644 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3645 //of the given point.
3646 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3648 int bytes = model->brush.num_pvsclusterbytes;
3649 bytes = min(bytes, pvsbufferlength);
3650 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3652 memset(pvsbuffer, 0xFF, bytes);
3656 memset(pvsbuffer, 0, bytes);
3657 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3661 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3666 VectorSubtract(inmaxs, inmins, size);
3667 if (cmodel->brush.ishlbsp)
3670 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3671 else if (size[0] <= 32)
3673 if (size[2] < 54) // pick the nearest of 36 or 72
3674 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3676 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3679 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3684 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3685 else if (size[0] <= 32)
3686 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3688 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3690 VectorCopy(inmins, outmins);
3691 VectorAdd(inmins, hull->clip_size, outmaxs);
3694 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3697 int numshadowmeshtriangles = 0;
3698 msurface_t *surface;
3699 if (cls.state == ca_dedicated)
3701 // make a single combined shadow mesh to allow optimized shadow volume creation
3703 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3705 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3706 numshadowmeshtriangles += surface->num_triangles;
3708 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3709 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3710 if (surface->num_triangles > 0)
3711 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));
3712 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3713 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3714 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3716 return numshadowmeshtriangles;
3719 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);
3721 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3724 sizebuf_t lumpsb[HEADER_LUMPS];
3726 float dist, modelyawradius, modelradius;
3727 msurface_t *surface;
3728 hullinfo_t hullinfo;
3729 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3730 model_brush_lightstyleinfo_t styleinfo[256];
3731 unsigned char *datapointer;
3734 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3736 mod->type = mod_brushq1;
3738 mod->brush.isbsp2 = false;
3739 mod->brush.ishlbsp = false;
3740 i = MSG_ReadLittleLong(&sb);
3744 mod->modeldatatypestring = "Q1BSP";
3747 mod->brush.ishlbsp = true;
3748 mod->modeldatatypestring = "HLBSP";
3750 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3751 mod->brush.isbsp2 = true;
3752 mod->modeldatatypestring = "Q1BSP2";
3755 mod->modeldatatypestring = "Unknown BSP";
3756 Host_Error("Mod_Q1BSP_Load: %s has wrong version number %i: supported versions are 29 (Quake), 30 (Half-Life), \"BSP2\"", mod->name, i);
3760 // fill in hull info
3761 VectorClear (hullinfo.hullsizes[0][0]);
3762 VectorClear (hullinfo.hullsizes[0][1]);
3763 if (mod->brush.ishlbsp)
3765 hullinfo.filehulls = 4;
3766 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3767 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3768 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3769 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3770 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3771 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3775 hullinfo.filehulls = 4;
3776 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3777 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3778 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3779 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3783 for (i = 0; i < HEADER_LUMPS; i++)
3785 int offset = MSG_ReadLittleLong(&sb);
3786 int size = MSG_ReadLittleLong(&sb);
3787 if (offset < 0 || offset + size > sb.cursize)
3788 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);
3789 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3792 mod->soundfromcenter = true;
3793 mod->TraceBox = Mod_Q1BSP_TraceBox;
3794 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
3795 mod->TraceLine = Mod_Q1BSP_TraceLineAgainstSurfaces; // LordHavoc: use the surface-hitting version of TraceLine in all cases
3797 mod->TraceLine = Mod_Q1BSP_TraceLine;
3798 mod->TracePoint = Mod_Q1BSP_TracePoint;
3799 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3800 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3801 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3802 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3803 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3804 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3805 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3806 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3807 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3808 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3809 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3810 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3811 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3812 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3813 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3814 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3815 mod->Draw = R_Q1BSP_Draw;
3816 mod->DrawDepth = R_Q1BSP_DrawDepth;
3817 mod->DrawDebug = R_Q1BSP_DrawDebug;
3818 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3819 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3820 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3821 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3822 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3823 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3824 mod->DrawLight = R_Q1BSP_DrawLight;
3828 mod->brush.qw_md4sum = 0;
3829 mod->brush.qw_md4sum2 = 0;
3830 for (i = 0;i < HEADER_LUMPS;i++)
3833 if (i == LUMP_ENTITIES)
3835 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3836 mod->brush.qw_md4sum ^= LittleLong(temp);
3837 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3839 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3842 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3843 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3844 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3845 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3846 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3847 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3848 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3849 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3850 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3851 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3852 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3853 // load submodels before leafs because they contain the number of vis leafs
3854 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3855 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3856 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3857 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3859 for (i = 0; i < HEADER_LUMPS; i++)
3860 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3861 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3863 // check if the map supports transparent water rendering
3864 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3866 if (mod->brushq1.data_compressedpvs)
3867 Mem_Free(mod->brushq1.data_compressedpvs);
3868 mod->brushq1.data_compressedpvs = NULL;
3869 mod->brushq1.num_compressedpvs = 0;
3871 Mod_Q1BSP_MakeHull0();
3872 if (mod_bsp_portalize.integer)
3873 Mod_Q1BSP_MakePortals();
3875 mod->numframes = 2; // regular and alternate animation
3878 // make a single combined shadow mesh to allow optimized shadow volume creation
3879 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3881 if (loadmodel->brush.numsubmodels)
3882 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3884 // LordHavoc: to clear the fog around the original quake submodel code, I
3886 // first of all, some background info on the submodels:
3887 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3888 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3889 // now the weird for loop itself:
3890 // the loop functions in an odd way, on each iteration it sets up the
3891 // current 'mod' model (which despite the confusing code IS the model of
3892 // the number i), at the end of the loop it duplicates the model to become
3893 // the next submodel, and loops back to set up the new submodel.
3895 // LordHavoc: now the explanation of my sane way (which works identically):
3896 // set up the world model, then on each submodel copy from the world model
3897 // and set up the submodel with the respective model info.
3898 totalstylesurfaces = 0;
3900 for (i = 0;i < mod->brush.numsubmodels;i++)
3902 memset(stylecounts, 0, sizeof(stylecounts));
3903 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3905 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3906 for (j = 0;j < MAXLIGHTMAPS;j++)
3907 stylecounts[surface->lightmapinfo->styles[j]]++;
3909 for (k = 0;k < 255;k++)
3913 totalstylesurfaces += stylecounts[k];
3916 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3917 for (i = 0;i < mod->brush.numsubmodels;i++)
3919 // LordHavoc: this code was originally at the end of this loop, but
3920 // has been transformed to something more readable at the start here.
3925 // duplicate the basic information
3926 dpsnprintf(name, sizeof(name), "*%i", i);
3927 mod = Mod_FindName(name, loadmodel->name);
3928 // copy the base model to this one
3930 // rename the clone back to its proper name
3931 strlcpy(mod->name, name, sizeof(mod->name));
3932 mod->brush.parentmodel = loadmodel;
3933 // textures and memory belong to the main model
3934 mod->texturepool = NULL;
3935 mod->mempool = NULL;
3936 mod->brush.GetPVS = NULL;
3937 mod->brush.FatPVS = NULL;
3938 mod->brush.BoxTouchingPVS = NULL;
3939 mod->brush.BoxTouchingLeafPVS = NULL;
3940 mod->brush.BoxTouchingVisibleLeafs = NULL;
3941 mod->brush.FindBoxClusters = NULL;
3942 mod->brush.LightPoint = NULL;
3943 mod->brush.AmbientSoundLevelsForPoint = NULL;
3946 mod->brush.submodel = i;
3948 if (loadmodel->brush.submodels)
3949 loadmodel->brush.submodels[i] = mod;
3951 bm = &mod->brushq1.submodels[i];
3953 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3954 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3956 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3957 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3960 mod->firstmodelsurface = bm->firstface;
3961 mod->nummodelsurfaces = bm->numfaces;
3963 // set node/leaf parents for this submodel
3964 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3966 // make the model surface list (used by shadowing/lighting)
3967 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3968 Mod_MakeSortedSurfaces(mod);
3970 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3971 // (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)
3972 VectorCopy(bm->mins, mod->normalmins);
3973 VectorCopy(bm->maxs, mod->normalmaxs);
3974 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3975 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3976 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3977 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3978 modelradius = modelyawradius + modelradius * modelradius;
3979 modelyawradius = sqrt(modelyawradius);
3980 modelradius = sqrt(modelradius);
3981 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3982 mod->yawmins[2] = mod->normalmins[2];
3983 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3984 mod->yawmaxs[2] = mod->normalmaxs[2];
3985 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3986 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3987 mod->radius = modelradius;
3988 mod->radius2 = modelradius * modelradius;
3990 // this gets altered below if sky or water is used
3991 mod->DrawSky = NULL;
3992 mod->DrawAddWaterPlanes = NULL;
3994 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3995 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3996 if (mod->nummodelsurfaces)
3998 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3999 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4001 if (j < mod->nummodelsurfaces)
4002 mod->DrawSky = R_Q1BSP_DrawSky;
4004 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4005 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4007 if (j < mod->nummodelsurfaces)
4008 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4010 // build lightstyle update chains
4011 // (used to rapidly mark lightmapupdateflags on many surfaces
4012 // when d_lightstylevalue changes)
4013 memset(stylecounts, 0, sizeof(stylecounts));
4014 for (k = 0;k < mod->nummodelsurfaces;k++)
4016 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4017 for (j = 0;j < MAXLIGHTMAPS;j++)
4018 stylecounts[surface->lightmapinfo->styles[j]]++;
4020 mod->brushq1.num_lightstyles = 0;
4021 for (k = 0;k < 255;k++)
4025 styleinfo[mod->brushq1.num_lightstyles].style = k;
4026 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4027 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4028 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4029 remapstyles[k] = mod->brushq1.num_lightstyles;
4030 mod->brushq1.num_lightstyles++;
4033 for (k = 0;k < mod->nummodelsurfaces;k++)
4035 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4036 for (j = 0;j < MAXLIGHTMAPS;j++)
4038 if (surface->lightmapinfo->styles[j] != 255)
4040 int r = remapstyles[surface->lightmapinfo->styles[j]];
4041 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4045 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4046 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4050 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4051 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4053 //mod->brushq1.num_visleafs = bm->visleafs;
4055 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4056 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4058 if (mod_q1bsp_polygoncollisions.integer)
4060 mod->collision_bih = mod->render_bih;
4061 // point traces and contents checks still use the bsp tree
4062 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4063 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4064 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4065 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4068 // generate VBOs and other shared data before cloning submodels
4072 Mod_Q1BSP_LoadMapBrushes();
4073 //Mod_Q1BSP_ProcessLightList();
4077 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);
4080 static void Mod_Q2BSP_LoadEntities(lump_t *l)
4084 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
4091 in = (void *)(mod_base + l->fileofs);
4092 if (l->filelen % sizeof(*in))
4093 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4094 count = l->filelen / sizeof(*in);
4095 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4098 loadmodel->num = count;
4100 for (i = 0;i < count;i++, in++, out++)
4106 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4113 in = (void *)(mod_base + l->fileofs);
4114 if (l->filelen % sizeof(*in))
4115 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4116 count = l->filelen / sizeof(*in);
4117 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4120 loadmodel->num = count;
4122 for (i = 0;i < count;i++, in++, out++)
4128 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4135 in = (void *)(mod_base + l->fileofs);
4136 if (l->filelen % sizeof(*in))
4137 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4138 count = l->filelen / sizeof(*in);
4139 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4142 loadmodel->num = count;
4144 for (i = 0;i < count;i++, in++, out++)
4150 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4157 in = (void *)(mod_base + l->fileofs);
4158 if (l->filelen % sizeof(*in))
4159 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4160 count = l->filelen / sizeof(*in);
4161 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4164 loadmodel->num = count;
4166 for (i = 0;i < count;i++, in++, out++)
4172 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
4179 in = (void *)(mod_base + l->fileofs);
4180 if (l->filelen % sizeof(*in))
4181 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
4182 count = l->filelen / sizeof(*in);
4183 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4186 loadmodel->num = count;
4188 for (i = 0;i < count;i++, in++, out++)
4194 static void Mod_Q2BSP_LoadFaces(lump_t *l)
4201 in = (void *)(mod_base + l->fileofs);
4202 if (l->filelen % sizeof(*in))
4203 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4204 count = l->filelen / sizeof(*in);
4205 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4208 loadmodel->num = count;
4210 for (i = 0;i < count;i++, in++, out++)
4216 static void Mod_Q2BSP_LoadLighting(lump_t *l)
4223 in = (void *)(mod_base + l->fileofs);
4224 if (l->filelen % sizeof(*in))
4225 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
4226 count = l->filelen / sizeof(*in);
4227 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4230 loadmodel->num = count;
4232 for (i = 0;i < count;i++, in++, out++)
4238 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
4245 in = (void *)(mod_base + l->fileofs);
4246 if (l->filelen % sizeof(*in))
4247 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4248 count = l->filelen / sizeof(*in);
4249 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4252 loadmodel->num = count;
4254 for (i = 0;i < count;i++, in++, out++)
4260 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
4267 in = (void *)(mod_base + l->fileofs);
4268 if (l->filelen % sizeof(*in))
4269 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4270 count = l->filelen / sizeof(*in);
4271 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4274 loadmodel->num = count;
4276 for (i = 0;i < count;i++, in++, out++)
4282 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
4289 in = (void *)(mod_base + l->fileofs);
4290 if (l->filelen % sizeof(*in))
4291 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4292 count = l->filelen / sizeof(*in);
4293 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4296 loadmodel->num = count;
4298 for (i = 0;i < count;i++, in++, out++)
4304 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4311 in = (void *)(mod_base + l->fileofs);
4312 if (l->filelen % sizeof(*in))
4313 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4314 count = l->filelen / sizeof(*in);
4315 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4318 loadmodel->num = count;
4320 for (i = 0;i < count;i++, in++, out++)
4326 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4333 in = (void *)(mod_base + l->fileofs);
4334 if (l->filelen % sizeof(*in))
4335 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4336 count = l->filelen / sizeof(*in);
4337 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4340 loadmodel->num = count;
4342 for (i = 0;i < count;i++, in++, out++)
4348 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4355 in = (void *)(mod_base + l->fileofs);
4356 if (l->filelen % sizeof(*in))
4357 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4358 count = l->filelen / sizeof(*in);
4359 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4362 loadmodel->num = count;
4364 for (i = 0;i < count;i++, in++, out++)
4370 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4377 in = (void *)(mod_base + l->fileofs);
4378 if (l->filelen % sizeof(*in))
4379 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4380 count = l->filelen / sizeof(*in);
4381 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4384 loadmodel->num = count;
4386 for (i = 0;i < count;i++, in++, out++)
4392 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4399 in = (void *)(mod_base + l->fileofs);
4400 if (l->filelen % sizeof(*in))
4401 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4402 count = l->filelen / sizeof(*in);
4403 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4406 loadmodel->num = count;
4408 for (i = 0;i < count;i++, in++, out++)
4414 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4421 in = (void *)(mod_base + l->fileofs);
4422 if (l->filelen % sizeof(*in))
4423 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4424 count = l->filelen / sizeof(*in);
4425 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4428 loadmodel->num = count;
4430 for (i = 0;i < count;i++, in++, out++)
4436 static void Mod_Q2BSP_LoadModels(lump_t *l)
4443 in = (void *)(mod_base + l->fileofs);
4444 if (l->filelen % sizeof(*in))
4445 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4446 count = l->filelen / sizeof(*in);
4447 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4450 loadmodel->num = count;
4452 for (i = 0;i < count;i++, in++, out++)
4458 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4461 q2dheader_t *header;
4463 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4465 mod->modeldatatypestring = "Q2BSP";
4467 mod->type = mod_brushq2;
4469 header = (q2dheader_t *)buffer;
4471 i = LittleLong(header->version);
4472 if (i != Q2BSPVERSION)
4473 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4475 mod_base = (unsigned char *)header;
4477 // swap all the lumps
4478 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4479 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4481 mod->brush.qw_md4sum = 0;
4482 mod->brush.qw_md4sum2 = 0;
4483 for (i = 0;i < Q2HEADER_LUMPS;i++)
4485 if (i == Q2LUMP_ENTITIES)
4487 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4488 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4490 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4493 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4494 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4495 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4496 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4497 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4498 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4499 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4500 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4501 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4502 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4503 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4504 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4505 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4506 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4507 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4508 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4509 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4510 // LordHavoc: must go last because this makes the submodels
4511 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4514 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4515 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4517 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4520 char key[128], value[MAX_INPUTLINE];
4522 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4523 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4524 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4527 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4528 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4529 loadmodel->brush.entities[l->filelen] = 0;
4530 data = loadmodel->brush.entities;
4531 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4532 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4533 loadmodel->brushq3.deluxemapping = false;
4534 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
4538 if (!COM_ParseToken_Simple(&data, false, false, true))
4540 if (com_token[0] == '}')
4541 break; // end of worldspawn
4542 if (com_token[0] == '_')
4543 strlcpy(key, com_token + 1, sizeof(key));
4545 strlcpy(key, com_token, sizeof(key));
4546 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4547 key[strlen(key)-1] = 0;
4548 if (!COM_ParseToken_Simple(&data, false, false, true))
4550 strlcpy(value, com_token, sizeof(value));
4551 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4553 #if _MSC_VER >= 1400
4554 #define sscanf sscanf_s
4557 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4558 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4560 VectorSet(v, 64, 64, 128);
4561 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4562 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]);
4563 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4564 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4567 else if (!strcmp("deluxeMaps", key))
4569 if (!strcmp(com_token, "1"))
4571 loadmodel->brushq3.deluxemapping = true;
4572 loadmodel->brushq3.deluxemapping_modelspace = true;
4574 else if (!strcmp(com_token, "2"))
4576 loadmodel->brushq3.deluxemapping = true;
4577 loadmodel->brushq3.deluxemapping_modelspace = false;
4584 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4590 in = (q3dtexture_t *)(mod_base + l->fileofs);
4591 if (l->filelen % sizeof(*in))
4592 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4593 count = l->filelen / sizeof(*in);
4594 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4596 loadmodel->data_textures = out;
4597 loadmodel->num_textures = count;
4598 loadmodel->num_texturesperskin = loadmodel->num_textures;
4600 for (i = 0;i < count;i++)
4602 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4603 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4604 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4605 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4606 // restore the surfaceflags and supercontents
4607 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4608 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4612 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4618 in = (q3dplane_t *)(mod_base + l->fileofs);
4619 if (l->filelen % sizeof(*in))
4620 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4621 count = l->filelen / sizeof(*in);
4622 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4624 loadmodel->brush.data_planes = out;
4625 loadmodel->brush.num_planes = count;
4627 for (i = 0;i < count;i++, in++, out++)
4629 out->normal[0] = LittleFloat(in->normal[0]);
4630 out->normal[1] = LittleFloat(in->normal[1]);
4631 out->normal[2] = LittleFloat(in->normal[2]);
4632 out->dist = LittleFloat(in->dist);
4637 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4640 q3mbrushside_t *out;
4643 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4644 if (l->filelen % sizeof(*in))
4645 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4646 count = l->filelen / sizeof(*in);
4647 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4649 loadmodel->brush.data_brushsides = out;
4650 loadmodel->brush.num_brushsides = count;
4652 for (i = 0;i < count;i++, in++, out++)
4654 n = LittleLong(in->planeindex);
4655 if (n < 0 || n >= loadmodel->brush.num_planes)
4656 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4657 out->plane = loadmodel->brush.data_planes + n;
4658 n = LittleLong(in->textureindex);
4659 if (n < 0 || n >= loadmodel->num_textures)
4660 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4661 out->texture = loadmodel->data_textures + n;
4665 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4667 q3dbrushside_ig_t *in;
4668 q3mbrushside_t *out;
4671 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4672 if (l->filelen % sizeof(*in))
4673 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4674 count = l->filelen / sizeof(*in);
4675 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4677 loadmodel->brush.data_brushsides = out;
4678 loadmodel->brush.num_brushsides = count;
4680 for (i = 0;i < count;i++, in++, out++)
4682 n = LittleLong(in->planeindex);
4683 if (n < 0 || n >= loadmodel->brush.num_planes)
4684 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4685 out->plane = loadmodel->brush.data_planes + n;
4686 n = LittleLong(in->textureindex);
4687 if (n < 0 || n >= loadmodel->num_textures)
4688 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4689 out->texture = loadmodel->data_textures + n;
4693 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4697 int i, j, n, c, count, maxplanes, q3surfaceflags;
4698 colplanef_t *planes;
4700 in = (q3dbrush_t *)(mod_base + l->fileofs);
4701 if (l->filelen % sizeof(*in))
4702 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4703 count = l->filelen / sizeof(*in);
4704 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4706 loadmodel->brush.data_brushes = out;
4707 loadmodel->brush.num_brushes = count;
4712 for (i = 0;i < count;i++, in++, out++)
4714 n = LittleLong(in->firstbrushside);
4715 c = LittleLong(in->numbrushsides);
4716 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4717 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4718 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4719 out->numbrushsides = c;
4720 n = LittleLong(in->textureindex);
4721 if (n < 0 || n >= loadmodel->num_textures)
4722 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4723 out->texture = loadmodel->data_textures + n;
4725 // make a list of mplane_t structs to construct a colbrush from
4726 if (maxplanes < out->numbrushsides)
4728 maxplanes = out->numbrushsides;
4731 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4734 for (j = 0;j < out->numbrushsides;j++)
4736 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4737 planes[j].dist = out->firstbrushside[j].plane->dist;
4738 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4739 planes[j].texture = out->firstbrushside[j].texture;
4740 q3surfaceflags |= planes[j].q3surfaceflags;
4742 // make the colbrush from the planes
4743 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4745 // this whole loop can take a while (e.g. on redstarrepublic4)
4746 CL_KeepaliveMessage(false);
4752 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4758 in = (q3deffect_t *)(mod_base + l->fileofs);
4759 if (l->filelen % sizeof(*in))
4760 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4761 count = l->filelen / sizeof(*in);
4762 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4764 loadmodel->brushq3.data_effects = out;
4765 loadmodel->brushq3.num_effects = count;
4767 for (i = 0;i < count;i++, in++, out++)
4769 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4770 n = LittleLong(in->brushindex);
4771 if (n >= loadmodel->brush.num_brushes)
4773 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4776 out->brushindex = n;
4777 out->unknown = LittleLong(in->unknown);
4781 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4786 in = (q3dvertex_t *)(mod_base + l->fileofs);
4787 if (l->filelen % sizeof(*in))
4788 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4789 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4790 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4791 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4792 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4793 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4794 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4796 for (i = 0;i < count;i++, in++)
4798 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4799 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4800 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4801 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4802 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4803 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4804 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4805 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4806 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4807 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4808 // svector/tvector are calculated later in face loading
4809 if(mod_q3bsp_sRGBlightmaps.integer)
4811 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
4812 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
4813 // working like this may be odd, but matches q3map2 -gamma 2.2
4814 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4816 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4817 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4818 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4819 // we fix the brightness consistently via lightmapscale
4823 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
4824 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
4825 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
4830 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4832 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
4833 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
4834 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
4838 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4839 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4840 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4843 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4844 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4845 loadmodel->lit = true;
4849 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4855 in = (int *)(mod_base + l->fileofs);
4856 if (l->filelen % sizeof(int[3]))
4857 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4858 count = l->filelen / sizeof(*in);
4860 if(!loadmodel->brushq3.num_vertices)
4863 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4864 loadmodel->brushq3.num_triangles = 0;
4868 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4869 loadmodel->brushq3.num_triangles = count / 3;
4870 loadmodel->brushq3.data_element3i = out;
4872 for (i = 0;i < count;i++, in++, out++)
4874 *out = LittleLong(*in);
4875 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4877 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4883 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4885 q3dlightmap_t *input_pointer;
4903 int mergedrowsxcolumns;
4908 unsigned char *mergedpixels;
4909 unsigned char *mergeddeluxepixels;
4910 unsigned char *mergebuf;
4911 char mapname[MAX_QPATH];
4913 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4916 // defaults for q3bsp
4923 loadmodel->brushq3.lightmapsize = 128;
4925 if (cls.state == ca_dedicated)
4928 if(mod_q3bsp_nolightmaps.integer)
4934 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4935 if (developer_loading.integer)
4936 Con_Printf("Using internal lightmaps\n");
4937 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4938 if (l->filelen % sizeof(*input_pointer))
4939 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4940 count = l->filelen / sizeof(*input_pointer);
4941 for(i = 0; i < count; ++i)
4942 inpixels[i] = input_pointer[i].rgb;
4946 // no internal lightmaps
4947 // try external lightmaps
4948 if (developer_loading.integer)
4949 Con_Printf("Using external lightmaps\n");
4950 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4951 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
4955 // using EXTERNAL lightmaps instead
4956 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4958 Mem_Free(inpixels[0]);
4959 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4969 for(count = 1; ; ++count)
4971 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
4972 if(!inpixels[count])
4973 break; // we got all of them
4974 if(image_width != size || image_height != size)
4976 Mem_Free(inpixels[count]);
4977 inpixels[count] = NULL;
4978 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);
4984 loadmodel->brushq3.lightmapsize = size;
4985 loadmodel->brushq3.num_originallightmaps = count;
4987 // now check the surfaces to see if any of them index an odd numbered
4988 // lightmap, if so this is not a deluxemapped bsp file
4990 // also check what lightmaps are actually used, because q3map2 sometimes
4991 // (always?) makes an unused one at the end, which
4992 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4993 // reason when only one lightmap is used, which can throw off the
4994 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4995 // to see if the second lightmap is blank, if so it is not deluxemapped.
4996 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4997 // in Mod_Q3BSP_LoadEntities was failed
4998 if (!loadmodel->brushq3.deluxemapping)
5000 loadmodel->brushq3.deluxemapping = !(count & 1);
5001 loadmodel->brushq3.deluxemapping_modelspace = true;
5003 if (loadmodel->brushq3.deluxemapping)
5005 int facecount = faceslump->filelen / sizeof(q3dface_t);
5006 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5007 for (i = 0;i < facecount;i++)
5009 j = LittleLong(faces[i].lightmapindex);
5012 endlightmap = max(endlightmap, j + 1);
5013 if ((j & 1) || j + 1 >= count)
5015 loadmodel->brushq3.deluxemapping = false;
5022 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5023 // reason when only one lightmap is used, which can throw off the
5024 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5025 // to see if the second lightmap is blank, if so it is not deluxemapped.
5027 // further research has shown q3map2 sometimes creates a deluxemap and two
5028 // blank lightmaps, which must be handled properly as well
5029 if (endlightmap == 1 && count > 1)
5032 for (i = 0;i < size*size;i++)
5034 if (c[bytesperpixel*i + rgbmap[0]])
5036 if (c[bytesperpixel*i + rgbmap[1]])
5038 if (c[bytesperpixel*i + rgbmap[2]])
5043 // all pixels in the unused lightmap were black...
5044 loadmodel->brushq3.deluxemapping = false;
5049 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5051 // figure out what the most reasonable merge power is within limits
5053 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5054 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5056 // figure out how big the merged texture has to be
5057 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5058 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5059 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5061 mergedwidth = mergegoal;
5062 mergedheight = mergegoal;
5063 // choose non-square size (2x1 aspect) if only half the space is used;
5064 // this really only happens when the entire set fits in one texture, if
5065 // there are multiple textures, we don't worry about shrinking the last
5066 // one to fit, because the driver prefers the same texture size on
5067 // consecutive draw calls...
5068 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5071 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5072 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5073 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5074 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5075 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5076 loadmodel->brushq3.num_lightmapmergedheightpower++;
5077 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5079 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5080 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5081 powerxy = powerx+powery;
5082 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5084 mergedcolumns = 1 << powerx;
5085 mergedrows = 1 << powery;
5086 mergedrowsxcolumns = 1 << powerxy;
5088 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5089 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5090 if (loadmodel->brushq3.deluxemapping)
5091 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5093 // allocate a texture pool if we need it
5094 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5095 loadmodel->texturepool = R_AllocTexturePool();
5097 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5098 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5099 for (i = 0;i < count;i++)
5101 // figure out which merged lightmap texture this fits into
5102 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5103 lightmapindex = i >> powerdxy;
5105 // choose the destination address
5106 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5107 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5108 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5109 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);
5111 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5112 for (j = 0;j < size;j++)
5113 for (k = 0;k < size;k++)
5115 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5116 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5117 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5118 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5121 // upload texture if this was the last tile being written to the texture
5122 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5124 if (loadmodel->brushq3.deluxemapping && (i & 1))
5125 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);
5128 if(mod_q3bsp_sRGBlightmaps.integer)
5131 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5133 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5134 // we fix the brightness consistently via lightmapscale
5137 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5138 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);
5142 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5143 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5144 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);
5150 if (mergeddeluxepixels)
5151 Mem_Free(mergeddeluxepixels);
5152 Mem_Free(mergedpixels);
5155 for(i = 0; i < count; ++i)
5156 Mem_Free(inpixels[i]);
5160 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5165 *collisionstride = stride;
5168 cnt = (num_triangles + stride - 1) / stride;
5169 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5170 for(j = 0; j < cnt; ++j)
5172 mins = &((*collisionbbox6f)[6 * j + 0]);
5173 maxs = &((*collisionbbox6f)[6 * j + 3]);
5174 for(k = 0; k < stride; ++k)
5176 tri = j * stride + k;
5177 if(tri >= num_triangles)
5179 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5180 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5181 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5182 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5183 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5184 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5185 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5186 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5187 if(vert[0] < mins[0]) mins[0] = vert[0];
5188 if(vert[1] < mins[1]) mins[1] = vert[1];
5189 if(vert[2] < mins[2]) mins[2] = vert[2];
5190 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5191 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5192 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5193 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5194 if(vert[0] < mins[0]) mins[0] = vert[0];
5195 if(vert[1] < mins[1]) mins[1] = vert[1];
5196 if(vert[2] < mins[2]) mins[2] = vert[2];
5197 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5198 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5199 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5204 *collisionbbox6f = NULL;
5207 typedef struct patchtess_s
5211 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5214 float *originalvertex3f;
5217 #define PATCHTESS_SAME_LODGROUP(a,b) \
5219 (a).lodgroup[0] == (b).lodgroup[0] && \
5220 (a).lodgroup[1] == (b).lodgroup[1] && \
5221 (a).lodgroup[2] == (b).lodgroup[2] && \
5222 (a).lodgroup[3] == (b).lodgroup[3] && \
5223 (a).lodgroup[4] == (b).lodgroup[4] && \
5224 (a).lodgroup[5] == (b).lodgroup[5] \
5227 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5229 q3dface_t *in, *oldin;
5230 msurface_t *out, *oldout;
5231 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;
5232 float lightmaptcbase[2], lightmaptcscale[2];
5233 //int *originalelement3i;
5234 //int *originalneighbor3i;
5235 float *originalvertex3f;
5236 //float *originalsvector3f;
5237 //float *originaltvector3f;
5238 float *originalnormal3f;
5239 float *originalcolor4f;
5240 float *originaltexcoordtexture2f;
5241 float *originaltexcoordlightmap2f;
5242 float *surfacecollisionvertex3f;
5243 int *surfacecollisionelement3i;
5245 patchtess_t *patchtess = NULL;
5246 int patchtesscount = 0;
5249 in = (q3dface_t *)(mod_base + l->fileofs);
5250 if (l->filelen % sizeof(*in))
5251 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5252 count = l->filelen / sizeof(*in);
5253 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5255 loadmodel->data_surfaces = out;
5256 loadmodel->num_surfaces = count;
5259 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5267 for (;i < count;i++, in++, out++)
5269 // check face type first
5270 type = LittleLong(in->type);
5271 if (type != Q3FACETYPE_FLAT
5272 && type != Q3FACETYPE_PATCH
5273 && type != Q3FACETYPE_MESH
5274 && type != Q3FACETYPE_FLARE)
5276 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5280 n = LittleLong(in->textureindex);
5281 if (n < 0 || n >= loadmodel->num_textures)
5283 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5286 out->texture = loadmodel->data_textures + n;
5287 n = LittleLong(in->effectindex);
5288 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5290 if (developer_extra.integer)
5291 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5297 out->effect = loadmodel->brushq3.data_effects + n;
5299 if (cls.state != ca_dedicated)
5301 out->lightmaptexture = NULL;
5302 out->deluxemaptexture = r_texture_blanknormalmap;
5303 n = LittleLong(in->lightmapindex);
5306 else if (n >= loadmodel->brushq3.num_originallightmaps)
5308 if(loadmodel->brushq3.num_originallightmaps != 0)
5309 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5314 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5315 if (loadmodel->brushq3.deluxemapping)
5316 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5317 loadmodel->lit = true;
5321 firstvertex = LittleLong(in->firstvertex);
5322 numvertices = LittleLong(in->numvertices);
5323 firstelement = LittleLong(in->firstelement);
5324 numtriangles = LittleLong(in->numelements) / 3;
5325 if (numtriangles * 3 != LittleLong(in->numelements))
5327 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));
5330 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5332 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);
5335 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5337 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);
5342 case Q3FACETYPE_FLAT:
5343 case Q3FACETYPE_MESH:
5344 // no processing necessary
5346 case Q3FACETYPE_PATCH:
5347 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5348 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5349 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))
5351 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5354 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5356 // convert patch to Q3FACETYPE_MESH
5357 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5358 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5359 // bound to user settings
5360 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5361 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5362 // bound to sanity settings
5363 xtess = bound(0, xtess, 1024);
5364 ytess = bound(0, ytess, 1024);
5366 // lower quality collision patches! Same procedure as before, but different cvars
5367 // convert patch to Q3FACETYPE_MESH
5368 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5369 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5370 // bound to user settings
5371 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5372 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5373 // bound to sanity settings
5374 cxtess = bound(0, cxtess, 1024);
5375 cytess = bound(0, cytess, 1024);
5377 // store it for the LOD grouping step
5378 patchtess[patchtesscount].info.xsize = patchsize[0];
5379 patchtess[patchtesscount].info.ysize = patchsize[1];
5380 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5381 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5382 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5383 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5385 patchtess[patchtesscount].surface_id = i;
5386 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5387 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5388 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5389 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5390 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5391 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5392 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5395 case Q3FACETYPE_FLARE:
5396 if (developer_extra.integer)
5397 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5401 out->num_vertices = numvertices;
5402 out->num_triangles = numtriangles;
5403 meshvertices += out->num_vertices;
5404 meshtriangles += out->num_triangles;
5407 // Fix patches tesselations so that they make no seams
5411 for(i = 0; i < patchtesscount; ++i)
5413 for(j = i+1; j < patchtesscount; ++j)
5415 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5418 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5425 // Calculate resulting number of triangles
5426 collisionvertices = 0;
5427 collisiontriangles = 0;
5428 for(i = 0; i < patchtesscount; ++i)
5430 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5431 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5432 numvertices = finalwidth * finalheight;
5433 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5435 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5436 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5437 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5438 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5440 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5441 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5442 numvertices = finalwidth * finalheight;
5443 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5445 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5446 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5447 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5448 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5454 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5455 if (collisiontriangles)
5457 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5458 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5462 collisionvertices = 0;
5463 collisiontriangles = 0;
5464 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5466 if (out->num_vertices < 3 || out->num_triangles < 1)
5469 type = LittleLong(in->type);
5470 firstvertex = LittleLong(in->firstvertex);
5471 firstelement = LittleLong(in->firstelement);
5472 out->num_firstvertex = meshvertices;
5473 out->num_firsttriangle = meshtriangles;
5474 out->num_firstcollisiontriangle = collisiontriangles;
5477 case Q3FACETYPE_FLAT:
5478 case Q3FACETYPE_MESH:
5479 // no processing necessary, except for lightmap merging
5480 for (j = 0;j < out->num_vertices;j++)
5482 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5483 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5484 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5485 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5486 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5487 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5488 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5489 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5490 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5491 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5492 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5493 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5494 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5495 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5497 for (j = 0;j < out->num_triangles*3;j++)
5498 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5500 case Q3FACETYPE_PATCH:
5501 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5502 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5503 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5504 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5505 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5506 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5507 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5509 xtess = ytess = cxtess = cytess = -1;
5510 for(j = 0; j < patchtesscount; ++j)
5511 if(patchtess[j].surface_id == i)
5513 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5514 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5515 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5516 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5521 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5522 xtess = ytess = cxtess = cytess = 0;
5525 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5526 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5527 finalvertices = finalwidth * finalheight;
5528 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5529 type = Q3FACETYPE_MESH;
5530 // generate geometry
5531 // (note: normals are skipped because they get recalculated)
5532 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5533 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5534 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5535 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5536 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5537 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5539 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);
5541 if (developer_extra.integer)
5543 if (out->num_triangles < finaltriangles)
5544 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);
5546 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);
5548 // q3map does not put in collision brushes for curves... ugh
5549 // build the lower quality collision geometry
5550 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5551 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5552 finalvertices = finalwidth * finalheight;
5553 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5555 // legacy collision geometry implementation
5556 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5557 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5558 out->num_collisionvertices = finalvertices;
5559 out->num_collisiontriangles = finaltriangles;
5560 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5561 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5563 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5564 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5566 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5568 // now optimize the collision mesh by finding triangle bboxes...
5569 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5570 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);
5572 // store collision geometry for BIH collision tree
5573 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5574 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5575 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5576 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5577 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5579 // remove this once the legacy code is removed
5581 int nc = out->num_collisiontriangles;
5583 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5585 if(nc != out->num_collisiontriangles)
5587 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5592 if (developer_extra.integer)
5593 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);
5595 collisionvertices += finalvertices;
5596 collisiontriangles += out->num_collisiontriangles;
5601 meshvertices += out->num_vertices;
5602 meshtriangles += out->num_triangles;
5603 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5604 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)
5606 if (invalidelements)
5608 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);
5609 for (j = 0;j < out->num_triangles * 3;j++)
5611 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5612 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)
5613 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5617 // calculate a bounding box
5618 VectorClear(out->mins);
5619 VectorClear(out->maxs);
5620 if (out->num_vertices)
5622 if (cls.state != ca_dedicated && out->lightmaptexture)
5624 // figure out which part of the merged lightmap this fits into
5625 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5626 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5627 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5628 lightmapindex &= mergewidth * mergeheight - 1;
5629 lightmaptcscale[0] = 1.0f / mergewidth;
5630 lightmaptcscale[1] = 1.0f / mergeheight;
5631 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5632 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5633 // modify the lightmap texcoords to match this region of the merged lightmap
5634 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5636 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5637 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5640 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5641 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5642 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5644 out->mins[0] = min(out->mins[0], v[0]);
5645 out->maxs[0] = max(out->maxs[0], v[0]);
5646 out->mins[1] = min(out->mins[1], v[1]);
5647 out->maxs[1] = max(out->maxs[1], v[1]);
5648 out->mins[2] = min(out->mins[2], v[2]);
5649 out->maxs[2] = max(out->maxs[2], v[2]);
5651 out->mins[0] -= 1.0f;
5652 out->mins[1] -= 1.0f;
5653 out->mins[2] -= 1.0f;
5654 out->maxs[0] += 1.0f;
5655 out->maxs[1] += 1.0f;
5656 out->maxs[2] += 1.0f;
5658 // set lightmap styles for consistency with q1bsp
5659 //out->lightmapinfo->styles[0] = 0;
5660 //out->lightmapinfo->styles[1] = 255;
5661 //out->lightmapinfo->styles[2] = 255;
5662 //out->lightmapinfo->styles[3] = 255;
5667 for (;i < count;i++, out++)
5669 if(out->num_vertices && out->num_triangles)
5671 if(out->num_vertices == 0)
5673 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5674 if(out->num_triangles == 0)
5675 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5677 else if(out->num_triangles == 0)
5678 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)",
5679 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5680 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5681 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5684 // for per pixel lighting
5685 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);
5687 // generate ushort elements array if possible
5688 if (loadmodel->surfmesh.data_element3s)
5689 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5690 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5692 // free the no longer needed vertex data
5693 loadmodel->brushq3.num_vertices = 0;
5694 if (loadmodel->brushq3.data_vertex3f)
5695 Mem_Free(loadmodel->brushq3.data_vertex3f);
5696 loadmodel->brushq3.data_vertex3f = NULL;
5697 loadmodel->brushq3.data_normal3f = NULL;
5698 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5699 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5700 loadmodel->brushq3.data_color4f = NULL;
5701 // free the no longer needed triangle data
5702 loadmodel->brushq3.num_triangles = 0;
5703 if (loadmodel->brushq3.data_element3i)
5704 Mem_Free(loadmodel->brushq3.data_element3i);
5705 loadmodel->brushq3.data_element3i = NULL;
5708 Mem_Free(patchtess);
5711 static void Mod_Q3BSP_LoadModels(lump_t *l)
5715 int i, j, n, c, count;
5717 in = (q3dmodel_t *)(mod_base + l->fileofs);
5718 if (l->filelen % sizeof(*in))
5719 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5720 count = l->filelen / sizeof(*in);
5721 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5723 loadmodel->brushq3.data_models = out;
5724 loadmodel->brushq3.num_models = count;
5726 for (i = 0;i < count;i++, in++, out++)
5728 for (j = 0;j < 3;j++)
5730 out->mins[j] = LittleFloat(in->mins[j]);
5731 out->maxs[j] = LittleFloat(in->maxs[j]);
5733 n = LittleLong(in->firstface);
5734 c = LittleLong(in->numfaces);
5735 if (n < 0 || n + c > loadmodel->num_surfaces)
5736 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5739 n = LittleLong(in->firstbrush);
5740 c = LittleLong(in->numbrushes);
5741 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5742 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5743 out->firstbrush = n;
5744 out->numbrushes = c;
5748 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5754 in = (int *)(mod_base + l->fileofs);
5755 if (l->filelen % sizeof(*in))
5756 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5757 count = l->filelen / sizeof(*in);
5758 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5760 loadmodel->brush.data_leafbrushes = out;
5761 loadmodel->brush.num_leafbrushes = count;
5763 for (i = 0;i < count;i++, in++, out++)
5765 n = LittleLong(*in);
5766 if (n < 0 || n >= loadmodel->brush.num_brushes)
5767 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5772 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5778 in = (int *)(mod_base + l->fileofs);
5779 if (l->filelen % sizeof(*in))
5780 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5781 count = l->filelen / sizeof(*in);
5782 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5784 loadmodel->brush.data_leafsurfaces = out;
5785 loadmodel->brush.num_leafsurfaces = count;
5787 for (i = 0;i < count;i++, in++, out++)
5789 n = LittleLong(*in);
5790 if (n < 0 || n >= loadmodel->num_surfaces)
5791 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5796 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5800 int i, j, n, c, count;
5802 in = (q3dleaf_t *)(mod_base + l->fileofs);
5803 if (l->filelen % sizeof(*in))
5804 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5805 count = l->filelen / sizeof(*in);
5806 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5808 loadmodel->brush.data_leafs = out;
5809 loadmodel->brush.num_leafs = count;
5811 for (i = 0;i < count;i++, in++, out++)
5815 out->clusterindex = LittleLong(in->clusterindex);
5816 out->areaindex = LittleLong(in->areaindex);
5817 for (j = 0;j < 3;j++)
5819 // yes the mins/maxs are ints
5820 out->mins[j] = LittleLong(in->mins[j]) - 1;
5821 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5823 n = LittleLong(in->firstleafface);
5824 c = LittleLong(in->numleaffaces);
5825 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5826 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5827 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5828 out->numleafsurfaces = c;
5829 n = LittleLong(in->firstleafbrush);
5830 c = LittleLong(in->numleafbrushes);
5831 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5832 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5833 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5834 out->numleafbrushes = c;
5838 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5844 in = (q3dnode_t *)(mod_base + l->fileofs);
5845 if (l->filelen % sizeof(*in))
5846 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5847 count = l->filelen / sizeof(*in);
5849 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5850 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5852 loadmodel->brush.data_nodes = out;
5853 loadmodel->brush.num_nodes = count;
5855 for (i = 0;i < count;i++, in++, out++)
5858 n = LittleLong(in->planeindex);
5859 if (n < 0 || n >= loadmodel->brush.num_planes)
5860 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5861 out->plane = loadmodel->brush.data_planes + n;
5862 for (j = 0;j < 2;j++)
5864 n = LittleLong(in->childrenindex[j]);
5867 if (n >= loadmodel->brush.num_nodes)
5868 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5869 out->children[j] = loadmodel->brush.data_nodes + n;
5874 if (n >= loadmodel->brush.num_leafs)
5875 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5876 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5879 for (j = 0;j < 3;j++)
5881 // yes the mins/maxs are ints
5882 out->mins[j] = LittleLong(in->mins[j]) - 1;
5883 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5887 // set the parent pointers
5888 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5891 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5894 q3dlightgrid_t *out;
5898 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5899 if (l->filelen % sizeof(*in))
5900 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5901 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5902 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5903 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5904 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5905 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5906 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5907 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5908 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5909 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5910 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5911 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5912 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5913 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5914 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]);
5915 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]);
5917 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5920 if (l->filelen < count * (int)sizeof(*in))
5922 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]);
5923 return; // ignore the grid if we cannot understand it
5925 if (l->filelen != count * (int)sizeof(*in))
5926 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5927 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5928 loadmodel->brushq3.data_lightgrid = out;
5929 loadmodel->brushq3.num_lightgrid = count;
5930 // no swapping or validation necessary
5931 memcpy(out, in, count * (int)sizeof(*out));
5933 if(mod_q3bsp_sRGBlightmaps.integer)
5935 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5937 // we fix the brightness consistently via lightmapscale
5941 for(i = 0; i < count; ++i)
5943 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5944 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5945 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5946 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
5947 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
5948 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
5954 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5956 for(i = 0; i < count; ++i)
5958 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5959 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5960 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5961 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
5962 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
5963 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
5974 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5979 if (l->filelen == 0)
5982 // unvised maps often have cluster indices even without pvs, so check
5983 // leafs to find real number of clusters
5984 loadmodel->brush.num_pvsclusters = 1;
5985 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5986 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5989 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5990 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5991 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5992 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5996 in = (q3dpvs_t *)(mod_base + l->fileofs);
5998 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6000 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6001 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6002 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6003 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6004 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6005 if (l->filelen < totalchains + (int)sizeof(*in))
6006 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);
6008 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6009 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6012 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6014 int i, j, k, index[3];
6015 float transformed[3], blend1, blend2, blend, stylescale = 1;
6016 q3dlightgrid_t *a, *s;
6018 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6019 switch(vid.renderpath)
6021 case RENDERPATH_GL20:
6022 case RENDERPATH_D3D9:
6023 case RENDERPATH_D3D10:
6024 case RENDERPATH_D3D11:
6025 case RENDERPATH_SOFT:
6026 case RENDERPATH_GLES2:
6027 // LordHavoc: FIXME: is this true?
6028 stylescale = 1; // added while render
6030 case RENDERPATH_GL11:
6031 case RENDERPATH_GL13:
6032 case RENDERPATH_GLES1:
6033 stylescale = r_refdef.scene.rtlightstylevalue[0];
6037 if (!model->brushq3.num_lightgrid)
6039 ambientcolor[0] = stylescale;
6040 ambientcolor[1] = stylescale;
6041 ambientcolor[2] = stylescale;
6045 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6046 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6047 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6048 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6049 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6050 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6051 index[0] = (int)floor(transformed[0]);
6052 index[1] = (int)floor(transformed[1]);
6053 index[2] = (int)floor(transformed[2]);
6054 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6056 // now lerp the values
6057 VectorClear(diffusenormal);
6058 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6059 for (k = 0;k < 2;k++)
6061 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6062 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6064 for (j = 0;j < 2;j++)
6066 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6067 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6069 for (i = 0;i < 2;i++)
6071 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6072 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6074 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6075 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6076 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6077 // this uses the mod_md3_sin table because the values are
6078 // already in the 0-255 range, the 64+ bias fetches a cosine
6079 // instead of a sine value
6080 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6081 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6082 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6083 //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)));
6088 // normalize the light direction before turning
6089 VectorNormalize(diffusenormal);
6090 //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]);
6093 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6096 double midf, mid[3];
6102 // find the point distances
6103 mplane_t *plane = node->plane;
6104 if (plane->type < 3)
6106 t1 = p1[plane->type] - plane->dist;
6107 t2 = p2[plane->type] - plane->dist;
6111 t1 = DotProduct (plane->normal, p1) - plane->dist;
6112 t2 = DotProduct (plane->normal, p2) - plane->dist;
6119 node = node->children[1];
6128 node = node->children[0];
6134 midf = t1 / (t1 - t2);
6135 VectorLerp(p1, midf, p2, mid);
6137 // recurse both sides, front side first
6138 // return 2 if empty is followed by solid (hit something)
6139 // do not return 2 if both are solid or both empty,
6140 // or if start is solid and end is empty
6141 // as these degenerate cases usually indicate the eye is in solid and
6142 // should see the target point anyway
6143 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6146 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6151 return ((mleaf_t *)node)->clusterindex < 0;
6154 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6156 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6159 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6160 return trace.fraction == 1;
6164 double tracestart[3], traceend[3];
6165 VectorCopy(start, tracestart);
6166 VectorCopy(end, traceend);
6167 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6171 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)
6174 const bih_leaf_t *leaf;
6175 const bih_node_t *node;
6176 const colbrushf_t *brush;
6179 int nodestackpos = 0;
6180 int nodestack[1024];
6182 memset(trace, 0, sizeof(*trace));
6183 trace->fraction = 1;
6184 trace->realfraction = 1;
6185 trace->hitsupercontentsmask = hitsupercontentsmask;
6187 bih = &model->collision_bih;
6191 nodenum = bih->rootnode;
6192 nodestack[nodestackpos++] = nodenum;
6193 while (nodestackpos)
6195 nodenum = nodestack[--nodestackpos];
6196 node = bih->nodes + nodenum;
6198 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6201 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6203 axis = node->type - BIH_SPLITX;
6204 if (start[axis] >= node->frontmin)
6205 nodestack[nodestackpos++] = node->front;
6206 if (start[axis] <= node->backmax)
6207 nodestack[nodestackpos++] = node->back;
6209 else if (node->type == BIH_UNORDERED)
6211 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6213 leaf = bih->leafs + node->children[axis];
6215 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6221 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6222 Collision_TracePointBrushFloat(trace, start, brush);
6224 case BIH_COLLISIONTRIANGLE:
6225 // collision triangle - skipped because they have no volume
6227 case BIH_RENDERTRIANGLE:
6228 // render triangle - skipped because they have no volume
6236 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)
6238 const bih_leaf_t *leaf;
6239 const bih_node_t *node;
6240 const colbrushf_t *brush;
6242 const texture_t *texture;
6243 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6244 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6245 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6250 if (VectorCompare(start, end))
6252 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6256 nodenum = bih->rootnode;
6258 memset(trace, 0, sizeof(*trace));
6259 trace->fraction = 1;
6260 trace->realfraction = 1;
6261 trace->hitsupercontentsmask = hitsupercontentsmask;
6264 nodestackline[nodestackpos][0] = start[0];
6265 nodestackline[nodestackpos][1] = start[1];
6266 nodestackline[nodestackpos][2] = start[2];
6267 nodestackline[nodestackpos][3] = end[0];
6268 nodestackline[nodestackpos][4] = end[1];
6269 nodestackline[nodestackpos][5] = end[2];
6270 nodestack[nodestackpos++] = nodenum;
6271 while (nodestackpos)
6273 nodenum = nodestack[--nodestackpos];
6274 node = bih->nodes + nodenum;
6275 VectorCopy(nodestackline[nodestackpos], nodestart);
6276 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6277 sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6278 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6280 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6282 // recurse children of the split
6283 axis = node->type - BIH_SPLITX;
6284 d1 = node->backmax - nodestart[axis];
6285 d2 = node->backmax - nodeend[axis];
6286 d3 = nodestart[axis] - node->frontmin;
6287 d4 = nodeend[axis] - node->frontmin;
6288 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6290 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;
6291 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;
6292 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;
6293 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6294 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;
6295 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;
6296 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;
6297 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6298 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;
6299 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;
6300 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;
6301 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6302 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6303 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6304 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6305 case 15: /* <<<< */ break;
6308 else if (node->type == BIH_UNORDERED)
6310 // calculate sweep bounds for this node
6311 // copy node bounds into local variables
6312 VectorCopy(node->mins, nodebigmins);
6313 VectorCopy(node->maxs, nodebigmaxs);
6314 // clip line to this node bounds
6315 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); }
6316 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); }
6317 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); }
6318 // some of the line intersected the enlarged node box
6319 // calculate sweep bounds for this node
6320 sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6321 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6323 leaf = bih->leafs + node->children[axis];
6324 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6329 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6330 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6332 case BIH_COLLISIONTRIANGLE:
6333 if (!mod_q3bsp_curves_collisions.integer)
6335 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6336 texture = model->data_textures + leaf->textureindex;
6337 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);
6339 case BIH_RENDERTRIANGLE:
6340 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6341 texture = model->data_textures + leaf->textureindex;
6342 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);
6350 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)
6352 if (VectorCompare(start, end))
6354 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6357 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6360 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)
6363 const bih_leaf_t *leaf;
6364 const bih_node_t *node;
6365 const colbrushf_t *brush;
6367 const texture_t *texture;
6368 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6369 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6370 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6371 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6373 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6375 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6376 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6378 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6382 bih = &model->collision_bih;
6385 nodenum = bih->rootnode;
6387 // box trace, performed as brush trace
6388 memset(trace, 0, sizeof(*trace));
6389 trace->fraction = 1;
6390 trace->realfraction = 1;
6391 trace->hitsupercontentsmask = hitsupercontentsmask;
6393 // calculate tracebox-like parameters for efficient culling
6394 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6395 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6396 VectorSubtract(thisbrush_start->mins, start, startmins);
6397 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6398 VectorSubtract(thisbrush_end->mins, end, endmins);
6399 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6400 mins[0] = min(startmins[0], endmins[0]);
6401 mins[1] = min(startmins[1], endmins[1]);
6402 mins[2] = min(startmins[2], endmins[2]);
6403 maxs[0] = max(startmaxs[0], endmaxs[0]);
6404 maxs[1] = max(startmaxs[1], endmaxs[1]);
6405 maxs[2] = max(startmaxs[2], endmaxs[2]);
6408 nodestackline[nodestackpos][0] = start[0];
6409 nodestackline[nodestackpos][1] = start[1];
6410 nodestackline[nodestackpos][2] = start[2];
6411 nodestackline[nodestackpos][3] = end[0];
6412 nodestackline[nodestackpos][4] = end[1];
6413 nodestackline[nodestackpos][5] = end[2];
6414 nodestack[nodestackpos++] = nodenum;
6415 while (nodestackpos)
6417 nodenum = nodestack[--nodestackpos];
6418 node = bih->nodes + nodenum;
6419 VectorCopy(nodestackline[nodestackpos], nodestart);
6420 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6421 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6422 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6424 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6426 // recurse children of the split
6427 axis = node->type - BIH_SPLITX;
6428 d1 = node->backmax - nodestart[axis] - mins[axis];
6429 d2 = node->backmax - nodeend[axis] - mins[axis];
6430 d3 = nodestart[axis] - node->frontmin + maxs[axis];
6431 d4 = nodeend[axis] - node->frontmin + maxs[axis];
6432 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6434 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;
6435 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;
6436 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;
6437 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6438 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;
6439 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;
6440 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;
6441 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6442 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;
6443 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;
6444 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;
6445 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6446 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6447 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6448 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6449 case 15: /* <<<< */ break;
6452 else if (node->type == BIH_UNORDERED)
6454 // calculate sweep bounds for this node
6455 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6456 VectorSubtract(node->mins, maxs, nodebigmins);
6457 VectorSubtract(node->maxs, mins, nodebigmaxs);
6458 // clip line to this node bounds
6459 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); }
6460 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); }
6461 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); }
6462 // some of the line intersected the enlarged node box
6463 // calculate sweep bounds for this node
6464 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6465 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6467 leaf = bih->leafs + node->children[axis];
6468 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6473 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6474 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6476 case BIH_COLLISIONTRIANGLE:
6477 if (!mod_q3bsp_curves_collisions.integer)
6479 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6480 texture = model->data_textures + leaf->textureindex;
6481 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);
6483 case BIH_RENDERTRIANGLE:
6484 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6485 texture = model->data_textures + leaf->textureindex;
6486 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);
6494 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)
6496 colboxbrushf_t thisbrush_start, thisbrush_end;
6497 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6499 // box trace, performed as brush trace
6500 VectorAdd(start, boxmins, boxstartmins);
6501 VectorAdd(start, boxmaxs, boxstartmaxs);
6502 VectorAdd(end, boxmins, boxendmins);
6503 VectorAdd(end, boxmaxs, boxendmaxs);
6504 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6505 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6506 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6510 static int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6513 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6514 return trace.startsupercontents;
6517 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)
6520 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6522 int hitsupercontents;
6523 VectorSet(end, start[0], start[1], model->normalmins[2]);
6525 memset(trace, 0, sizeof(*trace));
6526 trace->fraction = 1;
6527 trace->realfraction = 1;
6528 trace->hitsupercontentsmask = hitsupercontentsmask;
6530 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6531 hitsupercontents = trace->hitsupercontents;
6532 memset(trace, 0, sizeof(*trace));
6533 trace->fraction = 1;
6534 trace->realfraction = 1;
6535 trace->hitsupercontentsmask = hitsupercontentsmask;
6536 trace->startsupercontents = hitsupercontents;
6540 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6543 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6546 VectorSet(end, start[0], start[1], model->normalmins[2]);
6547 memset(&trace, 0, sizeof(trace));
6549 trace.realfraction = 1;
6550 trace.hitsupercontentsmask = 0;
6551 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6552 return trace.hitsupercontents;
6558 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6563 // find which leaf the point is in
6565 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6566 // point trace the brushes
6567 leaf = (mleaf_t *)node;
6568 for (i = 0;i < leaf->numleafbrushes;i++)
6570 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6571 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6573 brush->markframe = markframe;
6574 Collision_TracePointBrushFloat(trace, point, brush);
6577 // can't do point traces on curves (they have no thickness)
6580 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)
6582 int i, startside, endside;
6583 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6585 msurface_t *surface;
6588 // walk the tree until we hit a leaf, recursing for any split cases
6592 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6594 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6595 node = node->children[1];
6597 // abort if this part of the bsp tree can not be hit by this trace
6598 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6600 plane = node->plane;
6601 // axial planes are much more common than non-axial, so an optimized
6602 // axial case pays off here
6603 if (plane->type < 3)
6605 dist1 = start[plane->type] - plane->dist;
6606 dist2 = end[plane->type] - plane->dist;
6610 dist1 = DotProduct(start, plane->normal) - plane->dist;
6611 dist2 = DotProduct(end, plane->normal) - plane->dist;
6613 startside = dist1 < 0;
6614 endside = dist2 < 0;
6615 if (startside == endside)
6617 // most of the time the line fragment is on one side of the plane
6618 node = node->children[startside];
6622 // line crosses node plane, split the line
6623 dist1 = PlaneDiff(linestart, plane);
6624 dist2 = PlaneDiff(lineend, plane);
6625 midfrac = dist1 / (dist1 - dist2);
6626 VectorLerp(linestart, midfrac, lineend, mid);
6627 // take the near side first
6628 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6629 // if we found an impact on the front side, don't waste time
6630 // exploring the far side
6631 if (midfrac <= trace->realfraction)
6632 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6637 // abort if this part of the bsp tree can not be hit by this trace
6638 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6641 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6642 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6643 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6644 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6645 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6646 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6647 // line trace the brushes
6648 leaf = (mleaf_t *)node;
6650 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6653 for (i = 0;i < leaf->numleafbrushes;i++)
6655 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6656 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6658 brush->markframe = markframe;
6659 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6662 // can't do point traces on curves (they have no thickness)
6663 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6665 // line trace the curves
6666 for (i = 0;i < leaf->numleafsurfaces;i++)
6668 surface = model->data_surfaces + leaf->firstleafsurface[i];
6669 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6671 surface->deprecatedq3collisionmarkframe = markframe;
6672 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);
6678 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)
6684 msurface_t *surface;
6686 float nodesegmentmins[3], nodesegmentmaxs[3];
6687 // walk the tree until we hit a leaf, recursing for any split cases
6691 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6693 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6694 node = node->children[1];
6696 // abort if this part of the bsp tree can not be hit by this trace
6697 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6699 plane = node->plane;
6700 // axial planes are much more common than non-axial, so an optimized
6701 // axial case pays off here
6702 if (plane->type < 3)
6704 // this is an axial plane, compare bounding box directly to it and
6705 // recurse sides accordingly
6706 // recurse down node sides
6707 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6708 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6709 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6710 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6714 // this is a non-axial plane, so check if the start and end boxes
6715 // are both on one side of the plane to handle 'diagonal' cases
6716 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6720 // segment crosses plane
6721 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6724 // if sides == 0 then the trace itself is bogus (Not A Number values),
6725 // in this case we simply pretend the trace hit nothing
6727 return; // ERROR: NAN bounding box!
6728 // take whichever side the segment box is on
6729 node = node->children[sides - 1];
6732 // abort if this part of the bsp tree can not be hit by this trace
6733 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6735 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6736 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6737 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6738 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6739 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6740 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6742 leaf = (mleaf_t *)node;
6744 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6747 for (i = 0;i < leaf->numleafbrushes;i++)
6749 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6750 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6752 brush->markframe = markframe;
6753 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6756 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6758 for (i = 0;i < leaf->numleafsurfaces;i++)
6760 surface = model->data_surfaces + leaf->firstleafsurface[i];
6761 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6763 surface->deprecatedq3collisionmarkframe = markframe;
6764 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);
6771 static int markframe = 0;
6773 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)
6777 memset(trace, 0, sizeof(*trace));
6778 trace->fraction = 1;
6779 trace->realfraction = 1;
6780 trace->hitsupercontentsmask = hitsupercontentsmask;
6781 if (mod_collision_bih.integer)
6782 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6783 else if (model->brush.submodel)
6785 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6786 if (brush->colbrushf)
6787 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6790 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6793 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)
6796 float segmentmins[3], segmentmaxs[3];
6797 msurface_t *surface;
6800 if (VectorCompare(start, end))
6802 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6806 memset(trace, 0, sizeof(*trace));
6807 trace->fraction = 1;
6808 trace->realfraction = 1;
6809 trace->hitsupercontentsmask = hitsupercontentsmask;
6810 segmentmins[0] = min(start[0], end[0]) - 1;
6811 segmentmins[1] = min(start[1], end[1]) - 1;
6812 segmentmins[2] = min(start[2], end[2]) - 1;
6813 segmentmaxs[0] = max(start[0], end[0]) + 1;
6814 segmentmaxs[1] = max(start[1], end[1]) + 1;
6815 segmentmaxs[2] = max(start[2], end[2]) + 1;
6816 if (mod_collision_bih.integer)
6817 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6818 else if (model->brush.submodel)
6820 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6821 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6822 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6823 if (mod_q3bsp_curves_collisions.integer)
6824 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6825 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6826 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);
6829 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6832 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)
6834 float segmentmins[3], segmentmaxs[3];
6836 msurface_t *surface;
6839 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6841 if (VectorCompare(start->mins, end->mins))
6842 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6844 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6848 // box trace, performed as brush trace
6849 memset(trace, 0, sizeof(*trace));
6850 trace->fraction = 1;
6851 trace->realfraction = 1;
6852 trace->hitsupercontentsmask = hitsupercontentsmask;
6853 segmentmins[0] = min(start->mins[0], end->mins[0]);
6854 segmentmins[1] = min(start->mins[1], end->mins[1]);
6855 segmentmins[2] = min(start->mins[2], end->mins[2]);
6856 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6857 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6858 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6859 if (mod_collision_bih.integer)
6860 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6861 else if (model->brush.submodel)
6863 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6864 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6865 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6866 if (mod_q3bsp_curves_collisions.integer)
6867 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6868 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6869 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);
6872 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6875 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)
6877 colboxbrushf_t thisbrush_start, thisbrush_end;
6878 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6880 // box trace, performed as brush trace
6881 VectorAdd(start, boxmins, boxstartmins);
6882 VectorAdd(start, boxmaxs, boxstartmaxs);
6883 VectorAdd(end, boxmins, boxendmins);
6884 VectorAdd(end, boxmaxs, boxendmaxs);
6885 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6886 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6887 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6890 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6893 int supercontents = 0;
6895 if (mod_collision_bih.integer)
6897 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
6899 // test if the point is inside each brush
6900 else if (model->brush.submodel)
6902 // submodels are effectively one leaf
6903 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6904 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6905 supercontents |= brush->colbrushf->supercontents;
6909 mnode_t *node = model->brush.data_nodes;
6911 // find which leaf the point is in
6913 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6914 leaf = (mleaf_t *)node;
6915 // now check the brushes in the leaf
6916 for (i = 0;i < leaf->numleafbrushes;i++)
6918 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6919 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6920 supercontents |= brush->colbrushf->supercontents;
6923 return supercontents;
6926 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)
6928 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
6932 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6940 int nummodelbrushes = model->nummodelbrushes;
6941 int nummodelsurfaces = model->nummodelsurfaces;
6943 const int *collisionelement3i;
6944 const float *collisionvertex3f;
6945 const int *renderelement3i;
6946 const float *rendervertex3f;
6947 bih_leaf_t *bihleafs;
6948 bih_node_t *bihnodes;
6950 int *temp_leafsortscratch;
6951 const msurface_t *surface;
6952 const q3mbrush_t *brush;
6954 // find out how many BIH leaf nodes we need
6956 if (userendersurfaces)
6958 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6959 bihnumleafs += surface->num_triangles;
6963 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6964 if (brush->colbrushf)
6966 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6968 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6969 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
6971 bihnumleafs += surface->num_collisiontriangles;
6978 // allocate the memory for the BIH leaf nodes
6979 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6981 // now populate the BIH leaf nodes
6984 // add render surfaces
6985 renderelement3i = model->surfmesh.data_element3i;
6986 rendervertex3f = model->surfmesh.data_vertex3f;
6987 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6989 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6991 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6993 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6994 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6995 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6996 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6997 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6998 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6999 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7000 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7001 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7002 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7007 if (!userendersurfaces)
7009 // add collision brushes
7010 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7012 if (!brush->colbrushf)
7014 bihleafs[bihleafindex].type = BIH_BRUSH;
7015 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7016 bihleafs[bihleafindex].surfaceindex = -1;
7017 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7018 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7019 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7023 // add collision surfaces
7024 collisionelement3i = model->brush.data_collisionelement3i;
7025 collisionvertex3f = model->brush.data_collisionvertex3f;
7026 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7028 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7030 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7031 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7032 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7033 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7034 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7035 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7036 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7037 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7038 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7039 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7045 // allocate buffers for the produced and temporary data
7046 bihmaxnodes = bihnumleafs + 1;
7047 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7048 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7049 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7052 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7054 // we're done with the temporary data
7055 Mem_Free(temp_leafsort);
7057 // resize the BIH nodes array if it over-allocated
7058 if (out->maxnodes > out->numnodes)
7060 out->maxnodes = out->numnodes;
7061 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7067 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7069 int supercontents = 0;
7070 if (nativecontents & CONTENTSQ3_SOLID)
7071 supercontents |= SUPERCONTENTS_SOLID;
7072 if (nativecontents & CONTENTSQ3_WATER)
7073 supercontents |= SUPERCONTENTS_WATER;
7074 if (nativecontents & CONTENTSQ3_SLIME)
7075 supercontents |= SUPERCONTENTS_SLIME;
7076 if (nativecontents & CONTENTSQ3_LAVA)
7077 supercontents |= SUPERCONTENTS_LAVA;
7078 if (nativecontents & CONTENTSQ3_BODY)
7079 supercontents |= SUPERCONTENTS_BODY;
7080 if (nativecontents & CONTENTSQ3_CORPSE)
7081 supercontents |= SUPERCONTENTS_CORPSE;
7082 if (nativecontents & CONTENTSQ3_NODROP)
7083 supercontents |= SUPERCONTENTS_NODROP;
7084 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7085 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7086 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7087 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7088 if (nativecontents & CONTENTSQ3_DONOTENTER)
7089 supercontents |= SUPERCONTENTS_DONOTENTER;
7090 if (nativecontents & CONTENTSQ3_BOTCLIP)
7091 supercontents |= SUPERCONTENTS_BOTCLIP;
7092 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7093 supercontents |= SUPERCONTENTS_OPAQUE;
7094 return supercontents;
7097 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7099 int nativecontents = 0;
7100 if (supercontents & SUPERCONTENTS_SOLID)
7101 nativecontents |= CONTENTSQ3_SOLID;
7102 if (supercontents & SUPERCONTENTS_WATER)
7103 nativecontents |= CONTENTSQ3_WATER;
7104 if (supercontents & SUPERCONTENTS_SLIME)
7105 nativecontents |= CONTENTSQ3_SLIME;
7106 if (supercontents & SUPERCONTENTS_LAVA)
7107 nativecontents |= CONTENTSQ3_LAVA;
7108 if (supercontents & SUPERCONTENTS_BODY)
7109 nativecontents |= CONTENTSQ3_BODY;
7110 if (supercontents & SUPERCONTENTS_CORPSE)
7111 nativecontents |= CONTENTSQ3_CORPSE;
7112 if (supercontents & SUPERCONTENTS_NODROP)
7113 nativecontents |= CONTENTSQ3_NODROP;
7114 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7115 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7116 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7117 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7118 if (supercontents & SUPERCONTENTS_DONOTENTER)
7119 nativecontents |= CONTENTSQ3_DONOTENTER;
7120 if (supercontents & SUPERCONTENTS_BOTCLIP)
7121 nativecontents |= CONTENTSQ3_BOTCLIP;
7122 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7123 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7124 return nativecontents;
7127 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7132 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7133 node = node->children[1];
7135 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7136 if (loadmodel->brush.num_leafs < numleafs)
7137 loadmodel->brush.num_leafs = numleafs;
7140 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7143 q3dheader_t *header;
7144 float corner[3], yawradius, modelradius;
7146 mod->modeldatatypestring = "Q3BSP";
7148 mod->type = mod_brushq3;
7149 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7152 header = (q3dheader_t *)buffer;
7153 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7154 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7156 i = LittleLong(header->version);
7157 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7158 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7160 mod->soundfromcenter = true;
7161 mod->TraceBox = Mod_Q3BSP_TraceBox;
7162 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7163 mod->TraceLine = Mod_Q3BSP_TraceLine;
7164 mod->TracePoint = Mod_Q3BSP_TracePoint;
7165 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7166 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7167 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7168 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7169 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7170 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7171 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7172 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7173 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7174 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7175 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7176 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7177 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7178 mod->brush.AmbientSoundLevelsForPoint = NULL;
7179 mod->brush.RoundUpToHullSize = NULL;
7180 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7181 mod->Draw = R_Q1BSP_Draw;
7182 mod->DrawDepth = R_Q1BSP_DrawDepth;
7183 mod->DrawDebug = R_Q1BSP_DrawDebug;
7184 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7185 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7186 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7187 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7188 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7189 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7190 mod->DrawLight = R_Q1BSP_DrawLight;
7192 mod_base = (unsigned char *)header;
7194 // swap all the lumps
7195 header->ident = LittleLong(header->ident);
7196 header->version = LittleLong(header->version);
7197 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7198 for (i = 0;i < lumps;i++)
7200 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7201 if((char *) bufferend < (char *) buffer + j)
7202 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7203 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7204 if((char *) bufferend < (char *) buffer + j)
7205 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7208 * NO, do NOT clear them!
7209 * they contain actual data referenced by other stuff.
7210 * Instead, before using the advertisements lump, check header->versio
7212 * Sorry, but otherwise it breaks memory of the first lump.
7213 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7215 header->lumps[i].fileofs = 0;
7216 header->lumps[i].filelen = 0;
7220 mod->brush.qw_md4sum = 0;
7221 mod->brush.qw_md4sum2 = 0;
7222 for (i = 0;i < lumps;i++)
7224 if (i == Q3LUMP_ENTITIES)
7226 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7227 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7229 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7231 // all this checksumming can take a while, so let's send keepalives here too
7232 CL_KeepaliveMessage(false);
7235 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7236 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7237 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7238 if (header->version == Q3BSPVERSION_IG)
7239 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7241 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7242 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7243 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7244 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7245 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7246 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7247 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7248 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7249 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7250 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7251 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7252 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7253 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7254 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7255 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7257 // the MakePortals code works fine on the q3bsp data as well
7258 if (mod_bsp_portalize.integer)
7259 Mod_Q1BSP_MakePortals();
7261 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7262 loadmodel->brush.supportwateralpha = true;
7264 // make a single combined shadow mesh to allow optimized shadow volume creation
7265 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7267 loadmodel->brush.num_leafs = 0;
7268 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7270 if (loadmodel->brush.numsubmodels)
7271 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7274 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7279 // duplicate the basic information
7280 dpsnprintf(name, sizeof(name), "*%i", i);
7281 mod = Mod_FindName(name, loadmodel->name);
7282 // copy the base model to this one
7284 // rename the clone back to its proper name
7285 strlcpy(mod->name, name, sizeof(mod->name));
7286 mod->brush.parentmodel = loadmodel;
7287 // textures and memory belong to the main model
7288 mod->texturepool = NULL;
7289 mod->mempool = NULL;
7290 mod->brush.GetPVS = NULL;
7291 mod->brush.FatPVS = NULL;
7292 mod->brush.BoxTouchingPVS = NULL;
7293 mod->brush.BoxTouchingLeafPVS = NULL;
7294 mod->brush.BoxTouchingVisibleLeafs = NULL;
7295 mod->brush.FindBoxClusters = NULL;
7296 mod->brush.LightPoint = NULL;
7297 mod->brush.AmbientSoundLevelsForPoint = NULL;
7299 mod->brush.submodel = i;
7300 if (loadmodel->brush.submodels)
7301 loadmodel->brush.submodels[i] = mod;
7303 // make the model surface list (used by shadowing/lighting)
7304 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7305 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7306 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7307 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7308 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7309 Mod_MakeSortedSurfaces(mod);
7311 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7312 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7313 // enlarge the bounding box to enclose all geometry of this model,
7314 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7315 // which can in turn mess up the farclip (as well as culling when
7316 // outside the level - an unimportant concern)
7318 //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]);
7319 for (j = 0;j < mod->nummodelsurfaces;j++)
7321 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7322 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7324 if (!surface->num_vertices)
7326 for (k = 0;k < surface->num_vertices;k++, v += 3)
7328 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7329 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7330 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7331 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7332 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7333 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7336 //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]);
7337 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7338 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7339 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7340 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7341 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7342 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7343 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7344 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7345 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7346 mod->yawmins[2] = mod->normalmins[2];
7347 mod->yawmaxs[2] = mod->normalmaxs[2];
7348 mod->radius = modelradius;
7349 mod->radius2 = modelradius * modelradius;
7351 // this gets altered below if sky or water is used
7352 mod->DrawSky = NULL;
7353 mod->DrawAddWaterPlanes = NULL;
7355 for (j = 0;j < mod->nummodelsurfaces;j++)
7356 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7358 if (j < mod->nummodelsurfaces)
7359 mod->DrawSky = R_Q1BSP_DrawSky;
7361 for (j = 0;j < mod->nummodelsurfaces;j++)
7362 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7364 if (j < mod->nummodelsurfaces)
7365 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7367 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7368 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7370 // generate VBOs and other shared data before cloning submodels
7375 if (mod_q3bsp_sRGBlightmaps.integer)
7377 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7379 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7380 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7381 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7382 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7383 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7385 else // if this is NOT set, regular rendering looks right by this requirement anyway
7388 // we want color 1 to do the same as without sRGB
7389 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7390 loadmodel->lightmapscale *= 2.476923f; // fixes max level
7393 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7394 // we need to undo that
7395 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7399 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);
7402 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7404 int i = LittleLong(((int *)buffer)[1]);
7405 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7406 Mod_Q3BSP_Load(mod,buffer, bufferend);
7407 else if (i == Q2BSPVERSION)
7408 Mod_Q2BSP_Load(mod,buffer, bufferend);
7410 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7413 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7415 Host_Error("Mod_MAP_Load: not yet implemented");
7418 typedef struct objvertex_s
7429 static unsigned char nobsp_pvs[1] = {1};
7431 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7433 const char *textbase = (char *)buffer, *text = textbase;
7437 char materialname[MAX_QPATH];
7438 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7439 int index1, index2, index3;
7440 objvertex_t vfirst, vprev, vcurrent;
7443 int numtriangles = 0;
7444 int maxtriangles = 0;
7445 objvertex_t *vertices = NULL;
7447 int maxtextures = 0, numtextures = 0, textureindex = 0;
7448 int maxv = 0, numv = 1;
7449 int maxvt = 0, numvt = 1;
7450 int maxvn = 0, numvn = 1;
7451 char *texturenames = NULL;
7452 float dist, modelradius, modelyawradius, yawradius;
7459 objvertex_t *thisvertex = NULL;
7460 int vertexhashindex;
7461 int *vertexhashtable = NULL;
7462 objvertex_t *vertexhashdata = NULL;
7463 objvertex_t *vdata = NULL;
7464 int vertexhashsize = 0;
7465 int vertexhashcount = 0;
7466 skinfile_t *skinfiles = NULL;
7467 unsigned char *data = NULL;
7468 int *submodelfirstsurface;
7469 msurface_t *surface;
7470 msurface_t *tempsurfaces;
7472 memset(&vfirst, 0, sizeof(vfirst));
7473 memset(&vprev, 0, sizeof(vprev));
7474 memset(&vcurrent, 0, sizeof(vcurrent));
7476 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7478 loadmodel->modeldatatypestring = "OBJ";
7480 loadmodel->type = mod_obj;
7481 loadmodel->soundfromcenter = true;
7482 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7483 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7484 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7485 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7486 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7487 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7488 loadmodel->brush.TraceLineOfSight = NULL;
7489 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7490 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7491 loadmodel->brush.GetPVS = NULL;
7492 loadmodel->brush.FatPVS = NULL;
7493 loadmodel->brush.BoxTouchingPVS = NULL;
7494 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7495 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7496 loadmodel->brush.FindBoxClusters = NULL;
7497 loadmodel->brush.LightPoint = NULL;
7498 loadmodel->brush.FindNonSolidLocation = NULL;
7499 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7500 loadmodel->brush.RoundUpToHullSize = NULL;
7501 loadmodel->brush.PointInLeaf = NULL;
7502 loadmodel->Draw = R_Q1BSP_Draw;
7503 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7504 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7505 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7506 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7507 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7508 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7509 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7510 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7511 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7513 skinfiles = Mod_LoadSkinFiles();
7514 if (loadmodel->numskins < 1)
7515 loadmodel->numskins = 1;
7517 // make skinscenes for the skins (no groups)
7518 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7519 for (i = 0;i < loadmodel->numskins;i++)
7521 loadmodel->skinscenes[i].firstframe = i;
7522 loadmodel->skinscenes[i].framecount = 1;
7523 loadmodel->skinscenes[i].loop = true;
7524 loadmodel->skinscenes[i].framerate = 10;
7530 // we always have model 0, i.e. the first "submodel"
7531 loadmodel->brush.numsubmodels = 1;
7533 // parse the OBJ text now
7536 static char emptyarg[1] = "";
7541 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7542 line[linelen] = text[linelen];
7544 for (argc = 0;argc < 4;argc++)
7545 argv[argc] = emptyarg;
7548 while (*s == ' ' || *s == '\t')
7558 while (*s == ' ' || *s == '\t')
7568 if (argv[0][0] == '#')
7570 if (!strcmp(argv[0], "v"))
7574 maxv = max(maxv * 2, 1024);
7575 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7577 if(mod_obj_orientation.integer)
7579 v[numv*3+0] = atof(argv[1]);
7580 v[numv*3+2] = atof(argv[2]);
7581 v[numv*3+1] = atof(argv[3]);
7585 v[numv*3+0] = atof(argv[1]);
7586 v[numv*3+1] = atof(argv[2]);
7587 v[numv*3+2] = atof(argv[3]);
7591 else if (!strcmp(argv[0], "vt"))
7595 maxvt = max(maxvt * 2, 1024);
7596 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7598 vt[numvt*2+0] = atof(argv[1]);
7599 vt[numvt*2+1] = 1-atof(argv[2]);
7602 else if (!strcmp(argv[0], "vn"))
7606 maxvn = max(maxvn * 2, 1024);
7607 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7609 if(mod_obj_orientation.integer)
7611 vn[numvn*3+0] = atof(argv[1]);
7612 vn[numvn*3+2] = atof(argv[2]);
7613 vn[numvn*3+1] = atof(argv[3]);
7617 vn[numvn*3+0] = atof(argv[1]);
7618 vn[numvn*3+1] = atof(argv[2]);
7619 vn[numvn*3+2] = atof(argv[3]);
7623 else if (!strcmp(argv[0], "f"))
7627 if (maxtextures <= numtextures)
7629 maxtextures = max(maxtextures * 2, 256);
7630 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7632 textureindex = numtextures++;
7633 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7635 for (j = 1;j < argc;j++)
7637 index1 = atoi(argv[j]);
7638 while(argv[j][0] && argv[j][0] != '/')
7642 index2 = atoi(argv[j]);
7643 while(argv[j][0] && argv[j][0] != '/')
7647 index3 = atoi(argv[j]);
7648 // negative refers to a recent vertex
7649 // zero means not specified
7650 // positive means an absolute vertex index
7652 index1 = numv - index1;
7654 index2 = numvt - index2;
7656 index3 = numvn - index3;
7657 vcurrent.nextindex = -1;
7658 vcurrent.textureindex = textureindex;
7659 vcurrent.submodelindex = submodelindex;
7660 if (v && index1 >= 0 && index1 < numv)
7661 VectorCopy(v + 3*index1, vcurrent.v);
7662 if (vt && index2 >= 0 && index2 < numvt)
7663 Vector2Copy(vt + 2*index2, vcurrent.vt);
7664 if (vn && index3 >= 0 && index3 < numvn)
7665 VectorCopy(vn + 3*index3, vcurrent.vn);
7666 if (numtriangles == 0)
7668 VectorCopy(vcurrent.v, mins);
7669 VectorCopy(vcurrent.v, maxs);
7673 mins[0] = min(mins[0], vcurrent.v[0]);
7674 mins[1] = min(mins[1], vcurrent.v[1]);
7675 mins[2] = min(mins[2], vcurrent.v[2]);
7676 maxs[0] = max(maxs[0], vcurrent.v[0]);
7677 maxs[1] = max(maxs[1], vcurrent.v[1]);
7678 maxs[2] = max(maxs[2], vcurrent.v[2]);
7684 if (maxtriangles <= numtriangles)
7686 maxtriangles = max(maxtriangles * 2, 32768);
7687 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7689 if(mod_obj_orientation.integer)
7691 vertices[numtriangles*3+0] = vfirst;
7692 vertices[numtriangles*3+1] = vprev;
7693 vertices[numtriangles*3+2] = vcurrent;
7697 vertices[numtriangles*3+0] = vfirst;
7698 vertices[numtriangles*3+2] = vprev;
7699 vertices[numtriangles*3+1] = vcurrent;
7706 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7708 submodelindex = atof(argv[1]);
7709 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7711 else if (!strcmp(argv[0], "usemtl"))
7713 for (i = 0;i < numtextures;i++)
7714 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7716 if (i < numtextures)
7720 if (maxtextures <= numtextures)
7722 maxtextures = max(maxtextures * 2, 256);
7723 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7725 textureindex = numtextures++;
7726 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7731 // now that we have the OBJ data loaded as-is, we can convert it
7733 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7734 VectorCopy(mins, loadmodel->normalmins);
7735 VectorCopy(maxs, loadmodel->normalmaxs);
7736 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7737 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7738 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7739 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7740 modelradius = modelyawradius + modelradius * modelradius;
7741 modelyawradius = sqrt(modelyawradius);
7742 modelradius = sqrt(modelradius);
7743 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7744 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7745 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7746 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7747 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7748 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7749 loadmodel->radius = modelradius;
7750 loadmodel->radius2 = modelradius * modelradius;
7752 // allocate storage for triangles
7753 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7754 // allocate vertex hash structures to build an optimal vertex subset
7755 vertexhashsize = numtriangles*2;
7756 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7757 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7758 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7759 vertexhashcount = 0;
7761 // gather surface stats for assigning vertex/triangle ranges
7765 loadmodel->num_surfaces = 0;
7766 // allocate storage for the worst case number of surfaces, later we resize
7767 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7768 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7769 surface = tempsurfaces;
7770 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7772 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7773 for (textureindex = 0;textureindex < numtextures;textureindex++)
7775 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7777 thisvertex = vertices + vertexindex;
7778 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7781 // skip the surface creation if there are no triangles for it
7782 if (vertexindex == numtriangles*3)
7784 // create a surface for these vertices
7785 surfacevertices = 0;
7786 surfaceelements = 0;
7787 // we hack in a texture index in the surface to be fixed up later...
7788 surface->texture = (texture_t *)((size_t)textureindex);
7789 // calculate bounds as we go
7790 VectorCopy(thisvertex->v, surface->mins);
7791 VectorCopy(thisvertex->v, surface->maxs);
7792 for (;vertexindex < numtriangles*3;vertexindex++)
7794 thisvertex = vertices + vertexindex;
7795 if (thisvertex->submodelindex != submodelindex)
7797 if (thisvertex->textureindex != textureindex)
7799 // add vertex to surface bounds
7800 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7801 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7802 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7803 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7804 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7805 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7806 // add the vertex if it is not found in the merged set, and
7807 // get its index (triangle element) for the surface
7808 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7809 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7811 vdata = vertexhashdata + i;
7812 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7817 i = vertexhashcount++;
7818 vdata = vertexhashdata + i;
7819 *vdata = *thisvertex;
7820 vdata->nextindex = vertexhashtable[vertexhashindex];
7821 vertexhashtable[vertexhashindex] = i;
7824 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7827 surfacetriangles = surfaceelements / 3;
7828 surface->num_vertices = surfacevertices;
7829 surface->num_triangles = surfacetriangles;
7830 surface->num_firstvertex = firstvertex;
7831 surface->num_firsttriangle = firsttriangle;
7832 firstvertex += surface->num_vertices;
7833 firsttriangle += surface->num_triangles;
7835 loadmodel->num_surfaces++;
7838 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7839 numvertices = firstvertex;
7840 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7841 tempsurfaces = NULL;
7843 // allocate storage for final mesh data
7844 loadmodel->num_textures = numtextures * loadmodel->numskins;
7845 loadmodel->num_texturesperskin = numtextures;
7846 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 *));
7847 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7848 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7849 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7850 loadmodel->surfmesh.num_vertices = numvertices;
7851 loadmodel->surfmesh.num_triangles = numtriangles;
7852 if (r_enableshadowvolumes.integer)
7853 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7854 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7855 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7856 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7857 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7858 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7859 if (loadmodel->surfmesh.num_vertices <= 65536)
7860 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7862 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7864 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7865 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7866 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7869 // load the textures
7870 for (textureindex = 0;textureindex < numtextures;textureindex++)
7871 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7872 Mod_FreeSkinFiles(skinfiles);
7874 // set the surface textures to their real values now that we loaded them...
7875 for (i = 0;i < loadmodel->num_surfaces;i++)
7876 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7880 Mem_Free(texturenames);
7884 Mem_Free(vertexhashtable);
7885 Mem_Free(vertexhashdata);
7887 // make a single combined shadow mesh to allow optimized shadow volume creation
7888 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7890 // compute all the mesh information that was not loaded from the file
7891 if (loadmodel->surfmesh.data_element3s)
7892 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7893 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7894 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7895 // generate normals if the file did not have them
7896 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7897 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);
7898 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);
7899 if (loadmodel->surfmesh.data_neighbor3i)
7900 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7902 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7903 loadmodel->brush.num_visleafs = 1;
7904 loadmodel->brush.num_leafs = 1;
7905 loadmodel->brush.num_nodes = 0;
7906 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7907 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7908 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7909 loadmodel->brush.num_pvsclusters = 1;
7910 loadmodel->brush.num_pvsclusterbytes = 1;
7911 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7912 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7913 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7914 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7915 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7916 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7917 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7918 loadmodel->brush.data_leafs->clusterindex = 0;
7919 loadmodel->brush.data_leafs->areaindex = 0;
7920 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7921 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7922 loadmodel->brush.data_leafs->numleafbrushes = 0;
7923 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7924 loadmodel->brush.supportwateralpha = true;
7926 if (loadmodel->brush.numsubmodels)
7927 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7930 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7935 // duplicate the basic information
7936 dpsnprintf(name, sizeof(name), "*%i", i);
7937 mod = Mod_FindName(name, loadmodel->name);
7938 // copy the base model to this one
7940 // rename the clone back to its proper name
7941 strlcpy(mod->name, name, sizeof(mod->name));
7942 mod->brush.parentmodel = loadmodel;
7943 // textures and memory belong to the main model
7944 mod->texturepool = NULL;
7945 mod->mempool = NULL;
7946 mod->brush.GetPVS = NULL;
7947 mod->brush.FatPVS = NULL;
7948 mod->brush.BoxTouchingPVS = NULL;
7949 mod->brush.BoxTouchingLeafPVS = NULL;
7950 mod->brush.BoxTouchingVisibleLeafs = NULL;
7951 mod->brush.FindBoxClusters = NULL;
7952 mod->brush.LightPoint = NULL;
7953 mod->brush.AmbientSoundLevelsForPoint = NULL;
7955 mod->brush.submodel = i;
7956 if (loadmodel->brush.submodels)
7957 loadmodel->brush.submodels[i] = mod;
7959 // make the model surface list (used by shadowing/lighting)
7960 mod->firstmodelsurface = submodelfirstsurface[i];
7961 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7962 mod->firstmodelbrush = 0;
7963 mod->nummodelbrushes = 0;
7964 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
7965 Mod_MakeSortedSurfaces(mod);
7967 VectorClear(mod->normalmins);
7968 VectorClear(mod->normalmaxs);
7970 for (j = 0;j < mod->nummodelsurfaces;j++)
7972 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7973 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7975 if (!surface->num_vertices)
7980 VectorCopy(v, mod->normalmins);
7981 VectorCopy(v, mod->normalmaxs);
7983 for (k = 0;k < surface->num_vertices;k++, v += 3)
7985 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7986 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7987 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7988 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7989 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7990 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7993 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7994 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7995 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7996 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7997 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7998 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7999 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8000 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8001 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8002 mod->yawmins[2] = mod->normalmins[2];
8003 mod->yawmaxs[2] = mod->normalmaxs[2];
8004 mod->radius = modelradius;
8005 mod->radius2 = modelradius * modelradius;
8007 // this gets altered below if sky or water is used
8008 mod->DrawSky = NULL;
8009 mod->DrawAddWaterPlanes = NULL;
8011 for (j = 0;j < mod->nummodelsurfaces;j++)
8012 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8014 if (j < mod->nummodelsurfaces)
8015 mod->DrawSky = R_Q1BSP_DrawSky;
8017 for (j = 0;j < mod->nummodelsurfaces;j++)
8018 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8020 if (j < mod->nummodelsurfaces)
8021 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8023 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8024 mod->render_bih = mod->collision_bih;
8026 // generate VBOs and other shared data before cloning submodels
8031 Mem_Free(submodelfirstsurface);
8033 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);