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 r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
31 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)"};
32 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)"};
33 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)"};
34 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
35 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
36 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)"};
37 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)"};
38 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)"};
39 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
40 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
41 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)"};
42 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)"};
43 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
44 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
45 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, ..."};
46 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)"};
47 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
48 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces"};
49 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
50 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
52 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)"};
53 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"};
54 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"};
56 static texture_t mod_q1bsp_texture_solid;
57 static texture_t mod_q1bsp_texture_sky;
58 static texture_t mod_q1bsp_texture_lava;
59 static texture_t mod_q1bsp_texture_slime;
60 static texture_t mod_q1bsp_texture_water;
62 void Mod_BrushInit(void)
64 // Cvar_RegisterVariable(&r_subdivide_size);
65 Cvar_RegisterVariable(&r_novis);
66 Cvar_RegisterVariable(&r_nosurftextures);
67 Cvar_RegisterVariable(&r_subdivisions_tolerance);
68 Cvar_RegisterVariable(&r_subdivisions_mintess);
69 Cvar_RegisterVariable(&r_subdivisions_maxtess);
70 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
71 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
72 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
73 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
74 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
75 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
76 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
77 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
78 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
79 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
80 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
81 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
82 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
83 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
84 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
85 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
86 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
87 Cvar_RegisterVariable(&mod_collision_bih);
88 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
90 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
91 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
92 mod_q1bsp_texture_solid.surfaceflags = 0;
93 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
95 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
96 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
97 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
98 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
100 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
101 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
102 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
103 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
105 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
106 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
107 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
108 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
110 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
111 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
112 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
113 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
116 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
123 // LordHavoc: modified to start at first clip node,
124 // in other words: first node of the (sub)model
125 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
127 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
129 return (mleaf_t *)node;
132 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
136 leaf = Mod_Q1BSP_PointInLeaf(model, p);
139 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
142 memcpy(out, leaf->ambient_sound_level, i);
148 memset(out, 0, outsize);
151 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
154 int nodestackindex = 0;
155 mnode_t *node, *nodestack[1024];
156 if (!model->brush.num_pvsclusters)
158 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
164 // node - recurse down the BSP tree
165 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
169 return -1; // ERROR: NAN bounding box!
170 // box is on one side of plane, take that path
171 node = node->children[sides-1];
175 // box crosses plane, take one path and remember the other
176 if (nodestackindex < 1024)
177 nodestack[nodestackindex++] = node->children[0];
178 node = node->children[1];
184 // leaf - add clusterindex to list
185 if (numclusters < maxclusters)
186 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
190 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
194 if (nodestackindex < 1024)
195 nodestack[nodestackindex++] = node->children[0];
196 node = node->children[1];
201 // leaf - add clusterindex to list
202 if (numclusters < maxclusters)
203 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
208 // try another path we didn't take earlier
209 if (nodestackindex == 0)
211 node = nodestack[--nodestackindex];
213 // return number of clusters found (even if more than the maxclusters)
217 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
219 int nodestackindex = 0;
220 mnode_t *node, *nodestack[1024];
221 if (!model->brush.num_pvsclusters)
223 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
229 // node - recurse down the BSP tree
230 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
234 return -1; // ERROR: NAN bounding box!
235 // box is on one side of plane, take that path
236 node = node->children[sides-1];
240 // box crosses plane, take one path and remember the other
241 if (nodestackindex < 1024)
242 nodestack[nodestackindex++] = node->children[0];
243 node = node->children[1];
249 // leaf - check cluster bit
250 int clusterindex = ((mleaf_t *)node)->clusterindex;
251 if (CHECKPVSBIT(pvs, clusterindex))
253 // it is visible, return immediately with the news
258 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
262 if (nodestackindex < 1024)
263 nodestack[nodestackindex++] = node->children[0];
264 node = node->children[1];
269 // leaf - check cluster bit
270 int clusterindex = ((mleaf_t *)node)->clusterindex;
271 if (CHECKPVSBIT(pvs, clusterindex))
273 // it is visible, return immediately with the news
279 // nothing to see here, try another path we didn't take earlier
280 if (nodestackindex == 0)
282 node = nodestack[--nodestackindex];
288 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
290 int nodestackindex = 0;
291 mnode_t *node, *nodestack[1024];
292 if (!model->brush.num_leafs)
294 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
300 // node - recurse down the BSP tree
301 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
305 return -1; // ERROR: NAN bounding box!
306 // box is on one side of plane, take that path
307 node = node->children[sides-1];
311 // box crosses plane, take one path and remember the other
312 if (nodestackindex < 1024)
313 nodestack[nodestackindex++] = node->children[0];
314 node = node->children[1];
320 // leaf - check cluster bit
321 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
322 if (CHECKPVSBIT(pvs, clusterindex))
324 // it is visible, return immediately with the news
329 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
333 if (nodestackindex < 1024)
334 nodestack[nodestackindex++] = node->children[0];
335 node = node->children[1];
340 // leaf - check cluster bit
341 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
342 if (CHECKPVSBIT(pvs, clusterindex))
344 // it is visible, return immediately with the news
350 // nothing to see here, try another path we didn't take earlier
351 if (nodestackindex == 0)
353 node = nodestack[--nodestackindex];
359 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
361 int nodestackindex = 0;
362 mnode_t *node, *nodestack[1024];
363 if (!model->brush.num_leafs)
365 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
371 // node - recurse down the BSP tree
372 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
376 return -1; // ERROR: NAN bounding box!
377 // box is on one side of plane, take that path
378 node = node->children[sides-1];
382 // box crosses plane, take one path and remember the other
383 if (nodestackindex < 1024)
384 nodestack[nodestackindex++] = node->children[0];
385 node = node->children[1];
391 // leaf - check if it is visible
392 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
394 // it is visible, return immediately with the news
399 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
403 if (nodestackindex < 1024)
404 nodestack[nodestackindex++] = node->children[0];
405 node = node->children[1];
410 // leaf - check if it is visible
411 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
413 // it is visible, return immediately with the news
419 // nothing to see here, try another path we didn't take earlier
420 if (nodestackindex == 0)
422 node = nodestack[--nodestackindex];
428 typedef struct findnonsolidlocationinfo_s
431 vec3_t absmin, absmax;
437 findnonsolidlocationinfo_t;
439 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
442 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
444 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
445 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
446 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
447 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
448 VectorSubtract(vert[1], vert[0], edge[0]);
449 VectorSubtract(vert[2], vert[1], edge[1]);
450 CrossProduct(edge[1], edge[0], facenormal);
451 if (facenormal[0] || facenormal[1] || facenormal[2])
453 VectorNormalize(facenormal);
454 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
455 if (f <= info->bestdist && f >= -info->bestdist)
457 VectorSubtract(vert[0], vert[2], edge[2]);
458 VectorNormalize(edge[0]);
459 VectorNormalize(edge[1]);
460 VectorNormalize(edge[2]);
461 CrossProduct(facenormal, edge[0], edgenormal[0]);
462 CrossProduct(facenormal, edge[1], edgenormal[1]);
463 CrossProduct(facenormal, edge[2], edgenormal[2]);
465 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
466 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
467 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
469 // we got lucky, the center is within the face
470 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
474 if (info->bestdist > dist)
476 info->bestdist = dist;
477 VectorScale(facenormal, (info->radius - -dist), info->nudge);
482 if (info->bestdist > dist)
484 info->bestdist = dist;
485 VectorScale(facenormal, (info->radius - dist), info->nudge);
491 // check which edge or vertex the center is nearest
492 for (i = 0;i < 3;i++)
494 f = DotProduct(info->center, edge[i]);
495 if (f >= DotProduct(vert[0], edge[i])
496 && f <= DotProduct(vert[1], edge[i]))
499 VectorMA(info->center, -f, edge[i], point);
500 dist = sqrt(DotProduct(point, point));
501 if (info->bestdist > dist)
503 info->bestdist = dist;
504 VectorScale(point, (info->radius / dist), info->nudge);
506 // skip both vertex checks
507 // (both are further away than this edge)
512 // not on edge, check first vertex of edge
513 VectorSubtract(info->center, vert[i], point);
514 dist = sqrt(DotProduct(point, point));
515 if (info->bestdist > dist)
517 info->bestdist = dist;
518 VectorScale(point, (info->radius / dist), info->nudge);
527 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
529 int surfacenum, k, *mark;
531 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
533 surface = info->model->data_surfaces + *mark;
534 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
536 if(surface->deprecatedq3num_bboxstride > 0)
539 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
540 for(i = 0; i < cnt; ++i)
542 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
544 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
546 tri = i * surface->deprecatedq3num_bboxstride + k;
547 if(tri >= surface->num_triangles)
549 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
556 for (k = 0;k < surface->num_triangles;k++)
558 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
565 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
569 float f = PlaneDiff(info->center, node->plane);
570 if (f >= -info->bestdist)
571 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
572 if (f <= info->bestdist)
573 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
577 if (((mleaf_t *)node)->numleafsurfaces)
578 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
582 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
585 findnonsolidlocationinfo_t info;
591 VectorCopy(in, info.center);
592 info.radius = radius;
597 VectorClear(info.nudge);
598 info.bestdist = radius;
599 VectorCopy(info.center, info.absmin);
600 VectorCopy(info.center, info.absmax);
601 info.absmin[0] -= info.radius + 1;
602 info.absmin[1] -= info.radius + 1;
603 info.absmin[2] -= info.radius + 1;
604 info.absmax[0] += info.radius + 1;
605 info.absmax[1] += info.radius + 1;
606 info.absmax[2] += info.radius + 1;
607 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
608 VectorAdd(info.center, info.nudge, info.center);
610 while (info.bestdist < radius && ++i < 10);
611 VectorCopy(info.center, out);
614 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
616 switch(nativecontents)
621 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
623 return SUPERCONTENTS_WATER;
625 return SUPERCONTENTS_SLIME;
627 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
629 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
634 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
636 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
637 return CONTENTS_SOLID;
638 if (supercontents & SUPERCONTENTS_SKY)
640 if (supercontents & SUPERCONTENTS_LAVA)
641 return CONTENTS_LAVA;
642 if (supercontents & SUPERCONTENTS_SLIME)
643 return CONTENTS_SLIME;
644 if (supercontents & SUPERCONTENTS_WATER)
645 return CONTENTS_WATER;
646 return CONTENTS_EMPTY;
649 typedef struct RecursiveHullCheckTraceInfo_s
651 // the hull we're tracing through
654 // the trace structure to fill in
657 // start, end, and end - start (in model space)
662 RecursiveHullCheckTraceInfo_t;
664 // 1/32 epsilon to keep floating point happy
665 #define DIST_EPSILON (0.03125)
667 #define HULLCHECKSTATE_EMPTY 0
668 #define HULLCHECKSTATE_SOLID 1
669 #define HULLCHECKSTATE_DONE 2
671 extern cvar_t collision_prefernudgedfraction;
672 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
674 // status variables, these don't need to be saved on the stack when
675 // recursing... but are because this should be thread-safe
676 // (note: tracing against a bbox is not thread-safe, yet)
681 // variables that need to be stored on the stack when recursing
686 // LordHavoc: a goto! everyone flee in terror... :)
691 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
692 if (!t->trace->startfound)
694 t->trace->startfound = true;
695 t->trace->startsupercontents |= num;
697 if (num & SUPERCONTENTS_LIQUIDSMASK)
698 t->trace->inwater = true;
700 t->trace->inopen = true;
701 if (num & SUPERCONTENTS_SOLID)
702 t->trace->hittexture = &mod_q1bsp_texture_solid;
703 else if (num & SUPERCONTENTS_SKY)
704 t->trace->hittexture = &mod_q1bsp_texture_sky;
705 else if (num & SUPERCONTENTS_LAVA)
706 t->trace->hittexture = &mod_q1bsp_texture_lava;
707 else if (num & SUPERCONTENTS_SLIME)
708 t->trace->hittexture = &mod_q1bsp_texture_slime;
710 t->trace->hittexture = &mod_q1bsp_texture_water;
711 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
712 t->trace->hitsupercontents = num;
713 if (num & t->trace->hitsupercontentsmask)
715 // if the first leaf is solid, set startsolid
716 if (t->trace->allsolid)
717 t->trace->startsolid = true;
718 #if COLLISIONPARANOID >= 3
721 return HULLCHECKSTATE_SOLID;
725 t->trace->allsolid = false;
726 #if COLLISIONPARANOID >= 3
729 return HULLCHECKSTATE_EMPTY;
733 // find the point distances
734 node = t->hull->clipnodes + num;
736 plane = t->hull->planes + node->planenum;
739 t1 = p1[plane->type] - plane->dist;
740 t2 = p2[plane->type] - plane->dist;
744 t1 = DotProduct (plane->normal, p1) - plane->dist;
745 t2 = DotProduct (plane->normal, p2) - plane->dist;
752 #if COLLISIONPARANOID >= 3
755 num = node->children[1];
764 #if COLLISIONPARANOID >= 3
767 num = node->children[0];
773 // the line intersects, find intersection point
774 // LordHavoc: this uses the original trace for maximum accuracy
775 #if COLLISIONPARANOID >= 3
780 t1 = t->start[plane->type] - plane->dist;
781 t2 = t->end[plane->type] - plane->dist;
785 t1 = DotProduct (plane->normal, t->start) - plane->dist;
786 t2 = DotProduct (plane->normal, t->end) - plane->dist;
789 midf = t1 / (t1 - t2);
790 midf = bound(p1f, midf, p2f);
791 VectorMA(t->start, midf, t->dist, mid);
793 // recurse both sides, front side first
794 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
795 // if this side is not empty, return what it is (solid or done)
796 if (ret != HULLCHECKSTATE_EMPTY)
799 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
800 // if other side is not solid, return what it is (empty or done)
801 if (ret != HULLCHECKSTATE_SOLID)
804 // front is air and back is solid, this is the impact point...
807 t->trace->plane.dist = -plane->dist;
808 VectorNegate (plane->normal, t->trace->plane.normal);
812 t->trace->plane.dist = plane->dist;
813 VectorCopy (plane->normal, t->trace->plane.normal);
816 // calculate the true fraction
817 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
818 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
819 midf = t1 / (t1 - t2);
820 t->trace->realfraction = bound(0, midf, 1);
822 // calculate the return fraction which is nudged off the surface a bit
823 midf = (t1 - DIST_EPSILON) / (t1 - t2);
824 t->trace->fraction = bound(0, midf, 1);
826 if (collision_prefernudgedfraction.integer)
827 t->trace->realfraction = t->trace->fraction;
829 #if COLLISIONPARANOID >= 3
832 return HULLCHECKSTATE_DONE;
835 //#if COLLISIONPARANOID < 2
836 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
839 mclipnode_t *nodes = t->hull->clipnodes;
840 mplane_t *planes = t->hull->planes;
842 VectorCopy(t->start, point);
845 plane = planes + nodes[num].planenum;
846 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
848 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
849 t->trace->startsupercontents |= num;
850 if (num & SUPERCONTENTS_LIQUIDSMASK)
851 t->trace->inwater = true;
853 t->trace->inopen = true;
854 if (num & t->trace->hitsupercontentsmask)
856 t->trace->allsolid = t->trace->startsolid = true;
857 return HULLCHECKSTATE_SOLID;
861 t->trace->allsolid = t->trace->startsolid = false;
862 return HULLCHECKSTATE_EMPTY;
867 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)
869 RecursiveHullCheckTraceInfo_t rhc;
871 memset(&rhc, 0, sizeof(rhc));
872 memset(trace, 0, sizeof(trace_t));
874 rhc.trace->fraction = 1;
875 rhc.trace->realfraction = 1;
876 rhc.trace->allsolid = true;
877 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
878 VectorCopy(start, rhc.start);
879 VectorCopy(start, rhc.end);
880 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
883 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)
885 RecursiveHullCheckTraceInfo_t rhc;
887 if (VectorCompare(start, end))
889 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
893 memset(&rhc, 0, sizeof(rhc));
894 memset(trace, 0, sizeof(trace_t));
896 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
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(end, rhc.end);
903 VectorSubtract(rhc.end, rhc.start, rhc.dist);
904 #if COLLISIONPARANOID >= 2
905 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]);
906 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
911 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
912 memset(&testtrace, 0, sizeof(trace_t));
913 rhc.trace = &testtrace;
914 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
915 rhc.trace->fraction = 1;
916 rhc.trace->realfraction = 1;
917 rhc.trace->allsolid = true;
918 VectorCopy(test, rhc.start);
919 VectorCopy(test, rhc.end);
920 VectorClear(rhc.dist);
921 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
922 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
923 if (!trace->startsolid && testtrace.startsolid)
924 Con_Printf(" - ended in solid!\n");
928 if (VectorLength2(rhc.dist))
929 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
931 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
935 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)
937 // this function currently only supports same size start and end
939 RecursiveHullCheckTraceInfo_t rhc;
941 if (VectorCompare(boxmins, boxmaxs))
943 if (VectorCompare(start, end))
944 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
946 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
950 memset(&rhc, 0, sizeof(rhc));
951 memset(trace, 0, sizeof(trace_t));
953 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
954 rhc.trace->fraction = 1;
955 rhc.trace->realfraction = 1;
956 rhc.trace->allsolid = true;
957 VectorSubtract(boxmaxs, boxmins, boxsize);
959 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
960 else if (model->brush.ishlbsp)
962 // LordHavoc: this has to have a minor tolerance (the .1) because of
963 // minor float precision errors from the box being transformed around
964 if (boxsize[0] < 32.1)
966 if (boxsize[2] < 54) // pick the nearest of 36 or 72
967 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
969 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
972 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
976 // LordHavoc: this has to have a minor tolerance (the .1) because of
977 // minor float precision errors from the box being transformed around
978 if (boxsize[0] < 32.1)
979 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
981 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
983 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
984 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
985 VectorSubtract(rhc.end, rhc.start, rhc.dist);
986 #if COLLISIONPARANOID >= 2
987 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]);
988 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
993 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
994 memset(&testtrace, 0, sizeof(trace_t));
995 rhc.trace = &testtrace;
996 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
997 rhc.trace->fraction = 1;
998 rhc.trace->realfraction = 1;
999 rhc.trace->allsolid = true;
1000 VectorCopy(test, rhc.start);
1001 VectorCopy(test, rhc.end);
1002 VectorClear(rhc.dist);
1003 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1004 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1005 if (!trace->startsolid && testtrace.startsolid)
1006 Con_Printf(" - ended in solid!\n");
1010 if (VectorLength2(rhc.dist))
1011 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1013 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1017 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1019 int num = model->brushq1.hulls[0].firstclipnode;
1021 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1022 mplane_t *planes = model->brushq1.hulls[0].planes;
1025 plane = planes + nodes[num].planenum;
1026 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1028 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1031 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)
1035 colplanef_t cbox_planes[6];
1037 cbox.hasaabbplanes = true;
1038 cbox.supercontents = boxsupercontents;
1041 cbox.numtriangles = 0;
1042 cbox.planes = cbox_planes;
1044 cbox.elements = NULL;
1052 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];
1053 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];
1054 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];
1055 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];
1056 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];
1057 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];
1058 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1059 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1060 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1061 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1062 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1063 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1064 memset(trace, 0, sizeof(trace_t));
1065 trace->hitsupercontentsmask = hitsupercontentsmask;
1066 trace->fraction = 1;
1067 trace->realfraction = 1;
1068 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1070 RecursiveHullCheckTraceInfo_t rhc;
1071 static hull_t box_hull;
1072 static mclipnode_t box_clipnodes[6];
1073 static mplane_t box_planes[6];
1074 // fill in a default trace
1075 memset(&rhc, 0, sizeof(rhc));
1076 memset(trace, 0, sizeof(trace_t));
1077 //To keep everything totally uniform, bounding boxes are turned into small
1078 //BSP trees instead of being compared directly.
1079 // create a temp hull from bounding box sizes
1080 box_planes[0].dist = cmaxs[0] - mins[0];
1081 box_planes[1].dist = cmins[0] - maxs[0];
1082 box_planes[2].dist = cmaxs[1] - mins[1];
1083 box_planes[3].dist = cmins[1] - maxs[1];
1084 box_planes[4].dist = cmaxs[2] - mins[2];
1085 box_planes[5].dist = cmins[2] - maxs[2];
1086 #if COLLISIONPARANOID >= 3
1087 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]);
1090 if (box_hull.clipnodes == NULL)
1094 //Set up the planes and clipnodes so that the six floats of a bounding box
1095 //can just be stored out and get a proper hull_t structure.
1097 box_hull.clipnodes = box_clipnodes;
1098 box_hull.planes = box_planes;
1099 box_hull.firstclipnode = 0;
1100 box_hull.lastclipnode = 5;
1102 for (i = 0;i < 6;i++)
1104 box_clipnodes[i].planenum = i;
1108 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1110 box_clipnodes[i].children[side^1] = i + 1;
1112 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1114 box_planes[i].type = i>>1;
1115 box_planes[i].normal[i>>1] = 1;
1119 // trace a line through the generated clipping hull
1120 //rhc.boxsupercontents = boxsupercontents;
1121 rhc.hull = &box_hull;
1123 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1124 rhc.trace->fraction = 1;
1125 rhc.trace->realfraction = 1;
1126 rhc.trace->allsolid = true;
1127 VectorCopy(start, rhc.start);
1128 VectorCopy(end, rhc.end);
1129 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1130 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1131 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1132 if (rhc.trace->startsupercontents)
1133 rhc.trace->startsupercontents = boxsupercontents;
1137 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)
1139 memset(trace, 0, sizeof(trace_t));
1140 trace->fraction = 1;
1141 trace->realfraction = 1;
1142 if (BoxesOverlap(start, start, cmins, cmaxs))
1144 trace->startsupercontents |= boxsupercontents;
1145 if (hitsupercontentsmask & boxsupercontents)
1147 trace->startsolid = true;
1148 trace->allsolid = true;
1153 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1156 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1157 return trace.fraction == 1;
1160 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)
1164 float mid, distz = endz - startz;
1168 return false; // didn't hit anything
1170 switch (node->plane->type)
1173 node = node->children[x < node->plane->dist];
1176 node = node->children[y < node->plane->dist];
1179 side = startz < node->plane->dist;
1180 if ((endz < node->plane->dist) == side)
1182 node = node->children[side];
1185 // found an intersection
1186 mid = node->plane->dist;
1189 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1190 front += startz * node->plane->normal[2];
1191 back += endz * node->plane->normal[2];
1192 side = front < node->plane->dist;
1193 if ((back < node->plane->dist) == side)
1195 node = node->children[side];
1198 // found an intersection
1199 mid = startz + distz * (front - node->plane->dist) / (front - back);
1203 // go down front side
1204 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1205 return true; // hit something
1208 // check for impact on this node
1209 if (node->numsurfaces)
1211 int i, dsi, dti, lmwidth, lmheight;
1213 msurface_t *surface;
1214 unsigned char *lightmap;
1215 int maps, line3, size3;
1218 float scale, w, w00, w01, w10, w11;
1220 surface = model->data_surfaces + node->firstsurface;
1221 for (i = 0;i < node->numsurfaces;i++, surface++)
1223 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1224 continue; // no lightmaps
1226 // location we want to sample in the lightmap
1227 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;
1228 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;
1233 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1234 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1237 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1239 // calculate bilinear interpolation factors
1240 // and also multiply by fixedpoint conversion factors
1243 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1244 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1245 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1246 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1248 // values for pointer math
1249 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1250 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1252 // look up the pixel
1253 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1255 // bilinear filter each lightmap style, and sum them
1256 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1258 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1259 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1260 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1261 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1262 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1266 return true; // success
1271 // go down back side
1272 node = node->children[side ^ 1];
1274 distz = endz - startz;
1279 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1281 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1282 VectorSet(diffusenormal, 0, 0, 1);
1284 if (!model->brushq1.lightdata)
1286 VectorSet(ambientcolor, 1, 1, 1);
1287 VectorSet(diffusecolor, 0, 0, 0);
1291 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);
1294 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1297 unsigned char *outstart = out;
1298 while (out < outend)
1302 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));
1312 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));
1315 for (c = *in++;c > 0;c--)
1319 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));
1330 R_Q1BSP_LoadSplitSky
1332 A sky texture is 256*128, with the right side being a masked overlay
1335 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1340 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1341 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1343 // allocate a texture pool if we need it
1344 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1345 loadmodel->texturepool = R_AllocTexturePool();
1347 if (bytesperpixel == 4)
1349 for (y = 0;y < h;y++)
1351 for (x = 0;x < w;x++)
1353 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1354 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1360 // make an average value for the back to avoid
1361 // a fringe on the top level
1370 for (y = 0;y < h;y++)
1372 for (x = 0;x < w;x++)
1374 p = src[x*width+y+w];
1375 r += palette_rgb[p][0];
1376 g += palette_rgb[p][1];
1377 b += palette_rgb[p][2];
1380 bgra.b[2] = r/(w*h);
1381 bgra.b[1] = g/(w*h);
1382 bgra.b[0] = b/(w*h);
1384 for (y = 0;y < h;y++)
1386 for (x = 0;x < w;x++)
1388 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1390 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1395 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h);
1396 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h);
1397 Mem_Free(solidpixels);
1398 Mem_Free(alphapixels);
1401 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1403 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1404 skinframe_t *skinframe;
1406 texture_t *tx, *tx2, *anims[10], *altanims[10];
1408 unsigned char *data, *mtdata;
1410 char mapname[MAX_QPATH], name[MAX_QPATH];
1411 unsigned char zero[4];
1413 memset(zero, 0, sizeof(zero));
1415 loadmodel->data_textures = NULL;
1417 // add two slots for notexture walls and notexture liquids
1420 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1421 m->nummiptex = LittleLong (m->nummiptex);
1422 loadmodel->num_textures = m->nummiptex + 2;
1423 loadmodel->num_texturesperskin = loadmodel->num_textures;
1428 loadmodel->num_textures = 2;
1429 loadmodel->num_texturesperskin = loadmodel->num_textures;
1432 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1434 // fill out all slots with notexture
1435 if (cls.state != ca_dedicated)
1436 skinframe = R_SkinFrame_LoadMissing();
1439 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1441 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1444 if (cls.state != ca_dedicated)
1446 tx->numskinframes = 1;
1447 tx->skinframerate = 1;
1448 tx->skinframes[0] = skinframe;
1449 tx->currentskinframe = tx->skinframes[0];
1451 tx->basematerialflags = MATERIALFLAG_WALL;
1452 if (i == loadmodel->num_textures - 1)
1454 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1455 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1456 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1460 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1461 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1463 tx->currentframe = tx;
1465 // clear water settings
1468 tx->refractfactor = 1;
1469 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1470 tx->reflectfactor = 1;
1471 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1472 tx->r_water_wateralpha = 1;
1473 tx->offsetmapping = OFFSETMAPPING_OFF;
1474 tx->offsetscale = 1;
1475 tx->specularscalemod = 1;
1476 tx->specularpowermod = 1;
1481 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1485 s = loadmodel->name;
1486 if (!strncasecmp(s, "maps/", 5))
1488 FS_StripExtension(s, mapname, sizeof(mapname));
1490 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1492 // LordHavoc: mostly rewritten map texture loader
1493 for (i = 0;i < m->nummiptex;i++)
1495 dofs[i] = LittleLong(dofs[i]);
1496 if (r_nosurftextures.integer)
1500 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1503 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1505 // copy name, but only up to 16 characters
1506 // (the output buffer can hold more than this, but the input buffer is
1508 for (j = 0;j < 16 && dmiptex->name[j];j++)
1509 name[j] = dmiptex->name[j];
1514 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1515 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1518 mtwidth = LittleLong(dmiptex->width);
1519 mtheight = LittleLong(dmiptex->height);
1521 j = LittleLong(dmiptex->offsets[0]);
1525 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1527 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1530 mtdata = (unsigned char *)dmiptex + j;
1533 if ((mtwidth & 15) || (mtheight & 15))
1534 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1536 // LordHavoc: force all names to lowercase
1537 for (j = 0;name[j];j++)
1538 if (name[j] >= 'A' && name[j] <= 'Z')
1539 name[j] += 'a' - 'A';
1541 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1544 tx = loadmodel->data_textures + i;
1545 strlcpy(tx->name, name, sizeof(tx->name));
1546 tx->width = mtwidth;
1547 tx->height = mtheight;
1549 if (tx->name[0] == '*')
1551 if (!strncmp(tx->name, "*lava", 5))
1553 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1554 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1556 else if (!strncmp(tx->name, "*slime", 6))
1558 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1559 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1563 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1564 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1567 else if (!strncmp(tx->name, "sky", 3))
1569 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1570 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1574 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1575 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1578 if (cls.state != ca_dedicated)
1580 // LordHavoc: HL sky textures are entirely different than quake
1581 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1583 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), false, false, r_texture_convertsRGB_skin.integer != 0, NULL);
1585 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), false, false, r_texture_convertsRGB_skin.integer != 0, NULL);
1586 if (data && image_width == image_height * 2)
1588 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1591 else if (mtdata != NULL)
1592 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1596 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1598 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1601 // did not find external texture, load it from the bsp or wad3
1602 if (loadmodel->brush.ishlbsp)
1604 // internal texture overrides wad
1605 unsigned char *pixels, *freepixels;
1606 pixels = freepixels = NULL;
1608 pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1610 pixels = freepixels = W_GetTextureBGRA(tx->name);
1613 tx->width = image_width;
1614 tx->height = image_height;
1615 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height);
1618 Mem_Free(freepixels);
1620 else if (mtdata) // texture included
1621 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1623 // if skinframe is still NULL the "missing" texture will be used
1625 tx->skinframes[0] = skinframe;
1628 tx->basematerialflags = MATERIALFLAG_WALL;
1629 if (tx->name[0] == '*')
1631 // LordHavoc: some turbulent textures should not be affected by wateralpha
1632 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1634 // replace the texture with transparent black
1635 Vector4Set(zero, 128, 128, 128, 128);
1636 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zero, 1, 1);
1637 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1639 else if (!strncmp(tx->name,"*lava",5)
1640 || !strncmp(tx->name,"*teleport",9)
1641 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1642 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1644 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1645 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1646 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1648 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1650 // replace the texture with black
1651 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zero, 1, 1);
1652 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1654 else if (!strncmp(tx->name, "sky", 3))
1655 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1656 else if (!strcmp(tx->name, "caulk"))
1657 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1658 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1659 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1661 // start out with no animation
1662 tx->currentframe = tx;
1663 tx->currentskinframe = tx->skinframes[0];
1667 // sequence the animations
1668 for (i = 0;i < m->nummiptex;i++)
1670 tx = loadmodel->data_textures + i;
1671 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1673 if (tx->anim_total[0] || tx->anim_total[1])
1674 continue; // already sequenced
1676 // find the number of frames in the animation
1677 memset(anims, 0, sizeof(anims));
1678 memset(altanims, 0, sizeof(altanims));
1680 for (j = i;j < m->nummiptex;j++)
1682 tx2 = loadmodel->data_textures + j;
1683 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1687 if (num >= '0' && num <= '9')
1688 anims[num - '0'] = tx2;
1689 else if (num >= 'a' && num <= 'j')
1690 altanims[num - 'a'] = tx2;
1692 Con_Printf("Bad animating texture %s\n", tx->name);
1696 for (j = 0;j < 10;j++)
1703 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1706 for (j = 0;j < max;j++)
1710 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1714 for (j = 0;j < altmax;j++)
1718 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1727 // if there is no alternate animation, duplicate the primary
1728 // animation into the alternate
1730 for (k = 0;k < 10;k++)
1731 altanims[k] = anims[k];
1734 // link together the primary animation
1735 for (j = 0;j < max;j++)
1738 tx2->animated = true;
1739 tx2->anim_total[0] = max;
1740 tx2->anim_total[1] = altmax;
1741 for (k = 0;k < 10;k++)
1743 tx2->anim_frames[0][k] = anims[k];
1744 tx2->anim_frames[1][k] = altanims[k];
1748 // if there really is an alternate anim...
1749 if (anims[0] != altanims[0])
1751 // link together the alternate animation
1752 for (j = 0;j < altmax;j++)
1755 tx2->animated = true;
1756 // the primary/alternate are reversed here
1757 tx2->anim_total[0] = altmax;
1758 tx2->anim_total[1] = max;
1759 for (k = 0;k < 10;k++)
1761 tx2->anim_frames[0][k] = altanims[k];
1762 tx2->anim_frames[1][k] = anims[k];
1769 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1772 unsigned char *in, *out, *data, d;
1773 char litfilename[MAX_QPATH];
1774 char dlitfilename[MAX_QPATH];
1775 fs_offset_t filesize;
1776 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1778 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1779 for (i=0; i<l->filelen; i++)
1780 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1782 else // LordHavoc: bsp version 29 (normal white lighting)
1784 // LordHavoc: hope is not lost yet, check for a .lit file to load
1785 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1786 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1787 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1788 strlcat (litfilename, ".lit", sizeof (litfilename));
1789 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1790 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1793 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1795 i = LittleLong(((int *)data)[1]);
1798 if (developer_loading.integer)
1799 Con_Printf("loaded %s\n", litfilename);
1800 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1801 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1803 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1806 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1808 i = LittleLong(((int *)data)[1]);
1811 if (developer_loading.integer)
1812 Con_Printf("loaded %s\n", dlitfilename);
1813 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1814 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
1815 loadmodel->brushq3.deluxemapping_modelspace = false;
1816 loadmodel->brushq3.deluxemapping = true;
1825 Con_Printf("Unknown .lit file version (%d)\n", i);
1827 else if (filesize == 8)
1828 Con_Print("Empty .lit file, ignoring\n");
1830 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
1837 // LordHavoc: oh well, expand the white lighting data
1840 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1841 in = mod_base + l->fileofs;
1842 out = loadmodel->brushq1.lightdata;
1843 for (i = 0;i < l->filelen;i++)
1853 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1855 loadmodel->brushq1.num_compressedpvs = 0;
1856 loadmodel->brushq1.data_compressedpvs = NULL;
1859 loadmodel->brushq1.num_compressedpvs = l->filelen;
1860 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1861 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1864 // used only for HalfLife maps
1865 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1867 char key[128], value[4096];
1871 if (!COM_ParseToken_Simple(&data, false, false))
1873 if (com_token[0] != '{')
1877 if (!COM_ParseToken_Simple(&data, false, false))
1879 if (com_token[0] == '}')
1880 break; // end of worldspawn
1881 if (com_token[0] == '_')
1882 strlcpy(key, com_token + 1, sizeof(key));
1884 strlcpy(key, com_token, sizeof(key));
1885 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1886 key[strlen(key)-1] = 0;
1887 if (!COM_ParseToken_Simple(&data, false, false))
1889 dpsnprintf(value, sizeof(value), "%s", com_token);
1890 if (!strcmp("wad", key)) // for HalfLife maps
1892 if (loadmodel->brush.ishlbsp)
1895 for (i = 0;i < (int)sizeof(value);i++)
1896 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1900 for (;i < (int)sizeof(value);i++)
1902 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1903 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1905 else if (value[i] == ';' || value[i] == 0)
1909 W_LoadTextureWadFile(&value[j], false);
1921 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1923 loadmodel->brush.entities = NULL;
1926 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
1927 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1928 loadmodel->brush.entities[l->filelen] = 0;
1929 if (loadmodel->brush.ishlbsp)
1930 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1934 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1940 in = (dvertex_t *)(mod_base + l->fileofs);
1941 if (l->filelen % sizeof(*in))
1942 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1943 count = l->filelen / sizeof(*in);
1944 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1946 loadmodel->brushq1.vertexes = out;
1947 loadmodel->brushq1.numvertexes = count;
1949 for ( i=0 ; i<count ; i++, in++, out++)
1951 out->position[0] = LittleFloat(in->point[0]);
1952 out->position[1] = LittleFloat(in->point[1]);
1953 out->position[2] = LittleFloat(in->point[2]);
1957 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1958 // can be used for this
1960 int SB_ReadInt (unsigned char **buffer)
1963 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1969 float SB_ReadFloat (unsigned char **buffer)
1977 u.i = SB_ReadInt (buffer);
1981 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1983 unsigned char *index;
1987 index = (unsigned char *)(mod_base + l->fileofs);
1988 if (l->filelen % (48+4*hullinfo->filehulls))
1989 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1991 count = l->filelen / (48+4*hullinfo->filehulls);
1992 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1994 loadmodel->brushq1.submodels = out;
1995 loadmodel->brush.numsubmodels = count;
1997 for (i = 0; i < count; i++, out++)
1999 // spread out the mins / maxs by a pixel
2000 out->mins[0] = SB_ReadFloat (&index) - 1;
2001 out->mins[1] = SB_ReadFloat (&index) - 1;
2002 out->mins[2] = SB_ReadFloat (&index) - 1;
2003 out->maxs[0] = SB_ReadFloat (&index) + 1;
2004 out->maxs[1] = SB_ReadFloat (&index) + 1;
2005 out->maxs[2] = SB_ReadFloat (&index) + 1;
2006 out->origin[0] = SB_ReadFloat (&index);
2007 out->origin[1] = SB_ReadFloat (&index);
2008 out->origin[2] = SB_ReadFloat (&index);
2009 for (j = 0; j < hullinfo->filehulls; j++)
2010 out->headnode[j] = SB_ReadInt (&index);
2011 out->visleafs = SB_ReadInt (&index);
2012 out->firstface = SB_ReadInt (&index);
2013 out->numfaces = SB_ReadInt (&index);
2017 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2023 in = (dedge_t *)(mod_base + l->fileofs);
2024 if (l->filelen % sizeof(*in))
2025 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2026 count = l->filelen / sizeof(*in);
2027 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2029 loadmodel->brushq1.edges = out;
2030 loadmodel->brushq1.numedges = count;
2032 for ( i=0 ; i<count ; i++, in++, out++)
2034 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2035 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2036 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2038 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);
2039 if(!loadmodel->brushq1.numvertexes)
2040 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2048 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2052 int i, j, k, count, miptex;
2054 in = (texinfo_t *)(mod_base + l->fileofs);
2055 if (l->filelen % sizeof(*in))
2056 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2057 count = l->filelen / sizeof(*in);
2058 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2060 loadmodel->brushq1.texinfo = out;
2061 loadmodel->brushq1.numtexinfo = count;
2063 for (i = 0;i < count;i++, in++, out++)
2065 for (k = 0;k < 2;k++)
2066 for (j = 0;j < 4;j++)
2067 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2069 miptex = LittleLong(in->miptex);
2070 out->flags = LittleLong(in->flags);
2072 out->texture = NULL;
2073 if (loadmodel->data_textures)
2075 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2076 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2078 out->texture = loadmodel->data_textures + miptex;
2080 if (out->flags & TEX_SPECIAL)
2082 // if texture chosen is NULL or the shader needs a lightmap,
2083 // force to notexture water shader
2084 if (out->texture == NULL)
2085 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2089 // if texture chosen is NULL, force to notexture
2090 if (out->texture == NULL)
2091 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2097 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2102 mins[0] = mins[1] = mins[2] = 9999;
2103 maxs[0] = maxs[1] = maxs[2] = -9999;
2105 for (i = 0;i < numverts;i++)
2107 for (j = 0;j < 3;j++, v++)
2117 #define MAX_SUBDIVPOLYTRIANGLES 4096
2118 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2120 static int subdivpolyverts, subdivpolytriangles;
2121 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2122 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2124 static int subdivpolylookupvert(vec3_t v)
2127 for (i = 0;i < subdivpolyverts;i++)
2128 if (subdivpolyvert[i][0] == v[0]
2129 && subdivpolyvert[i][1] == v[1]
2130 && subdivpolyvert[i][2] == v[2])
2132 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2133 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2134 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2135 return subdivpolyverts++;
2138 static void SubdividePolygon(int numverts, float *verts)
2140 int i, i1, i2, i3, f, b, c, p;
2141 vec3_t mins, maxs, front[256], back[256];
2142 float m, *pv, *cv, dist[256], frac;
2145 Host_Error("SubdividePolygon: ran out of verts in buffer");
2147 BoundPoly(numverts, verts, mins, maxs);
2149 for (i = 0;i < 3;i++)
2151 m = (mins[i] + maxs[i]) * 0.5;
2152 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2153 if (maxs[i] - m < 8)
2155 if (m - mins[i] < 8)
2159 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2160 dist[c] = cv[i] - m;
2163 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2167 VectorCopy(pv, front[f]);
2172 VectorCopy(pv, back[b]);
2175 if (dist[p] == 0 || dist[c] == 0)
2177 if ((dist[p] > 0) != (dist[c] > 0) )
2180 frac = dist[p] / (dist[p] - dist[c]);
2181 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2182 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2183 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2189 SubdividePolygon(f, front[0]);
2190 SubdividePolygon(b, back[0]);
2194 i1 = subdivpolylookupvert(verts);
2195 i2 = subdivpolylookupvert(verts + 3);
2196 for (i = 2;i < numverts;i++)
2198 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2200 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2204 i3 = subdivpolylookupvert(verts + i * 3);
2205 subdivpolyindex[subdivpolytriangles][0] = i1;
2206 subdivpolyindex[subdivpolytriangles][1] = i2;
2207 subdivpolyindex[subdivpolytriangles][2] = i3;
2209 subdivpolytriangles++;
2213 //Breaks a polygon up along axial 64 unit
2214 //boundaries so that turbulent and sky warps
2215 //can be done reasonably.
2216 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2222 subdivpolytriangles = 0;
2223 subdivpolyverts = 0;
2224 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2225 if (subdivpolytriangles < 1)
2226 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2228 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2229 mesh->num_vertices = subdivpolyverts;
2230 mesh->num_triangles = subdivpolytriangles;
2231 mesh->vertex = (surfvertex_t *)(mesh + 1);
2232 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2233 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2235 for (i = 0;i < mesh->num_triangles;i++)
2236 for (j = 0;j < 3;j++)
2237 mesh->index[i*3+j] = subdivpolyindex[i][j];
2239 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2241 VectorCopy(subdivpolyvert[i], v->v);
2242 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2243 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2248 extern cvar_t gl_max_lightmapsize;
2249 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2252 msurface_t *surface;
2253 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2254 float texmins[2], texmaxs[2], val;
2255 rtexture_t *lightmaptexture, *deluxemaptexture;
2257 in = (dface_t *)(mod_base + l->fileofs);
2258 if (l->filelen % sizeof(*in))
2259 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2260 count = l->filelen / sizeof(*in);
2261 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2262 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2264 loadmodel->num_surfaces = count;
2266 loadmodel->brushq1.firstrender = true;
2267 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2271 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2273 numedges = (unsigned short)LittleShort(in->numedges);
2274 totalverts += numedges;
2275 totaltris += numedges - 2;
2278 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2280 lightmaptexture = NULL;
2281 deluxemaptexture = r_texture_blanknormalmap;
2283 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2284 totallightmapsamples = 0;
2288 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2290 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2292 // FIXME: validate edges, texinfo, etc?
2293 firstedge = LittleLong(in->firstedge);
2294 numedges = (unsigned short)LittleShort(in->numedges);
2295 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)
2296 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2297 i = (unsigned short)LittleShort(in->texinfo);
2298 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2299 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2300 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2301 surface->texture = surface->lightmapinfo->texinfo->texture;
2303 planenum = (unsigned short)LittleShort(in->planenum);
2304 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2305 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2307 //surface->flags = surface->texture->flags;
2308 //if (LittleShort(in->side))
2309 // surface->flags |= SURF_PLANEBACK;
2310 //surface->plane = loadmodel->brush.data_planes + planenum;
2312 surface->num_firstvertex = totalverts;
2313 surface->num_vertices = numedges;
2314 surface->num_firsttriangle = totaltris;
2315 surface->num_triangles = numedges - 2;
2316 totalverts += numedges;
2317 totaltris += numedges - 2;
2319 // convert edges back to a normal polygon
2320 for (i = 0;i < surface->num_vertices;i++)
2322 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2324 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2326 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2328 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2329 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2330 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2331 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2332 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2333 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2334 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2335 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2338 for (i = 0;i < surface->num_triangles;i++)
2340 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2341 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2342 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2345 // compile additional data about the surface geometry
2346 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);
2347 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);
2348 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2350 // generate surface extents information
2351 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2352 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2353 for (i = 1;i < surface->num_vertices;i++)
2355 for (j = 0;j < 2;j++)
2357 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2358 texmins[j] = min(texmins[j], val);
2359 texmaxs[j] = max(texmaxs[j], val);
2362 for (i = 0;i < 2;i++)
2364 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2365 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2368 smax = surface->lightmapinfo->extents[0] >> 4;
2369 tmax = surface->lightmapinfo->extents[1] >> 4;
2370 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2371 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2374 for (i = 0;i < MAXLIGHTMAPS;i++)
2375 surface->lightmapinfo->styles[i] = in->styles[i];
2376 surface->lightmaptexture = NULL;
2377 surface->deluxemaptexture = r_texture_blanknormalmap;
2378 i = LittleLong(in->lightofs);
2381 surface->lightmapinfo->samples = NULL;
2383 // give non-lightmapped water a 1x white lightmap
2384 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2386 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2387 surface->lightmapinfo->styles[0] = 0;
2388 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2392 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2393 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2394 else // LordHavoc: white lighting (bsp version 29)
2396 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2397 if (loadmodel->brushq1.nmaplightdata)
2398 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2401 // check if we should apply a lightmap to this
2402 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2404 if (ssize > 256 || tsize > 256)
2405 Host_Error("Bad surface extents");
2407 if (lightmapsize < ssize)
2408 lightmapsize = ssize;
2409 if (lightmapsize < tsize)
2410 lightmapsize = tsize;
2412 totallightmapsamples += ssize*tsize;
2414 // force lightmap upload on first time seeing the surface
2416 // additionally this is used by the later code to see if a
2417 // lightmap is needed on this surface (rather than duplicating the
2419 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2420 loadmodel->lit = true;
2424 // small maps (such as ammo boxes especially) don't need big lightmap
2425 // textures, so this code tries to guess a good size based on
2426 // totallightmapsamples (size of the lightmaps lump basically), as well as
2427 // trying to max out the size if there is a lot of lightmap data to store
2428 // additionally, never choose a lightmapsize that is smaller than the
2429 // largest surface encountered (as it would fail)
2431 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2434 // now that we've decided the lightmap texture size, we can do the rest
2435 if (cls.state != ca_dedicated)
2437 int stainmapsize = 0;
2438 mod_alloclightmap_state_t allocState;
2440 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2441 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2443 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2444 float u, v, ubase, vbase, uscale, vscale;
2446 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2449 smax = surface->lightmapinfo->extents[0] >> 4;
2450 tmax = surface->lightmapinfo->extents[1] >> 4;
2451 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2452 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2453 stainmapsize += ssize * tsize * 3;
2455 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2457 // allocate a texture pool if we need it
2458 if (loadmodel->texturepool == NULL)
2459 loadmodel->texturepool = R_AllocTexturePool();
2460 // could not find room, make a new lightmap
2461 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2462 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2463 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2464 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2465 if (loadmodel->brushq1.nmaplightdata)
2466 loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2468 Mod_AllocLightmap_Reset(&allocState);
2469 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2471 surface->lightmaptexture = lightmaptexture;
2472 surface->deluxemaptexture = deluxemaptexture;
2473 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2474 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2476 uscale = 1.0f / (float)lightmapsize;
2477 vscale = 1.0f / (float)lightmapsize;
2478 ubase = lightmapx * uscale;
2479 vbase = lightmapy * vscale;
2481 for (i = 0;i < surface->num_vertices;i++)
2483 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);
2484 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);
2485 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2486 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2487 // LordHavoc: calc lightmap data offset for vertex lighting to use
2490 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2494 if (cl_stainmaps.integer)
2496 // allocate stainmaps for permanent marks on walls and clear white
2497 unsigned char *stainsamples = NULL;
2498 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2499 memset(stainsamples, 255, stainmapsize);
2501 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2503 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2505 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2506 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2507 surface->lightmapinfo->stainsamples = stainsamples;
2508 stainsamples += ssize * tsize * 3;
2513 // generate ushort elements array if possible
2514 if (loadmodel->surfmesh.data_element3s)
2515 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2516 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2519 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2522 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2523 node->parent = parent;
2526 // this is a node, recurse to children
2527 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2528 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2529 // combine supercontents of children
2530 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2535 mleaf_t *leaf = (mleaf_t *)node;
2536 // if this is a leaf, calculate supercontents mask from all collidable
2537 // primitives in the leaf (brushes and collision surfaces)
2538 // also flag if the leaf contains any collision surfaces
2539 leaf->combinedsupercontents = 0;
2540 // combine the supercontents values of all brushes in this leaf
2541 for (j = 0;j < leaf->numleafbrushes;j++)
2542 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2543 // check if this leaf contains any collision surfaces (q3 patches)
2544 for (j = 0;j < leaf->numleafsurfaces;j++)
2546 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2547 if (surface->num_collisiontriangles)
2549 leaf->containscollisionsurfaces = true;
2550 leaf->combinedsupercontents |= surface->texture->supercontents;
2556 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2562 in = (dnode_t *)(mod_base + l->fileofs);
2563 if (l->filelen % sizeof(*in))
2564 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2565 count = l->filelen / sizeof(*in);
2566 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2568 loadmodel->brush.data_nodes = out;
2569 loadmodel->brush.num_nodes = count;
2571 for ( i=0 ; i<count ; i++, in++, out++)
2573 for (j=0 ; j<3 ; j++)
2575 out->mins[j] = LittleShort(in->mins[j]);
2576 out->maxs[j] = LittleShort(in->maxs[j]);
2579 p = LittleLong(in->planenum);
2580 out->plane = loadmodel->brush.data_planes + p;
2582 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2583 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2585 for (j=0 ; j<2 ; j++)
2587 // LordHavoc: this code supports broken bsp files produced by
2588 // arguire qbsp which can produce more than 32768 nodes, any value
2589 // below count is assumed to be a node number, any other value is
2590 // assumed to be a leaf number
2591 p = (unsigned short)LittleShort(in->children[j]);
2594 if (p < loadmodel->brush.num_nodes)
2595 out->children[j] = loadmodel->brush.data_nodes + p;
2598 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2599 // map it to the solid leaf
2600 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2605 // note this uses 65535 intentionally, -1 is leaf 0
2607 if (p < loadmodel->brush.num_leafs)
2608 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2611 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2612 // map it to the solid leaf
2613 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2619 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2622 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2628 in = (dleaf_t *)(mod_base + l->fileofs);
2629 if (l->filelen % sizeof(*in))
2630 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2631 count = l->filelen / sizeof(*in);
2632 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2634 loadmodel->brush.data_leafs = out;
2635 loadmodel->brush.num_leafs = count;
2636 // get visleafs from the submodel data
2637 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2638 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2639 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2640 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2642 for ( i=0 ; i<count ; i++, in++, out++)
2644 for (j=0 ; j<3 ; j++)
2646 out->mins[j] = LittleShort(in->mins[j]);
2647 out->maxs[j] = LittleShort(in->maxs[j]);
2650 // FIXME: this function could really benefit from some error checking
2652 out->contents = LittleLong(in->contents);
2654 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2655 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2656 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2658 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", (int)(out->firstleafsurface - loadmodel->brush.data_leafsurfaces), (int)(out->firstleafsurface + out->numleafsurfaces - loadmodel->brush.data_leafsurfaces), 0, loadmodel->brush.num_leafsurfaces);
2659 out->firstleafsurface = NULL;
2660 out->numleafsurfaces = 0;
2663 out->clusterindex = i - 1;
2664 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2665 out->clusterindex = -1;
2667 p = LittleLong(in->visofs);
2668 // ignore visofs errors on leaf 0 (solid)
2669 if (p >= 0 && out->clusterindex >= 0)
2671 if (p >= loadmodel->brushq1.num_compressedpvs)
2672 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2674 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);
2677 for (j = 0;j < 4;j++)
2678 out->ambient_sound_level[j] = in->ambient_level[j];
2680 // FIXME: Insert caustics here
2684 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2688 const unsigned char *pvs;
2689 // if there's no vis data, assume supported (because everything is visible all the time)
2690 if (!loadmodel->brush.data_pvsclusters)
2692 // check all liquid leafs to see if they can see into empty leafs, if any
2693 // can we can assume this map supports r_wateralpha
2694 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2696 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2698 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2699 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2700 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2707 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2714 in = (dclipnode_t *)(mod_base + l->fileofs);
2715 if (l->filelen % sizeof(*in))
2716 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2717 count = l->filelen / sizeof(*in);
2718 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2720 loadmodel->brushq1.clipnodes = out;
2721 loadmodel->brushq1.numclipnodes = count;
2723 for (i = 1; i < MAX_MAP_HULLS; i++)
2725 hull = &loadmodel->brushq1.hulls[i];
2726 hull->clipnodes = out;
2727 hull->firstclipnode = 0;
2728 hull->lastclipnode = count-1;
2729 hull->planes = loadmodel->brush.data_planes;
2730 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2731 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2732 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2733 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2734 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2735 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2736 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2739 for (i=0 ; i<count ; i++, out++, in++)
2741 out->planenum = LittleLong(in->planenum);
2742 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2743 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2744 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2745 if (out->children[0] >= count)
2746 out->children[0] -= 65536;
2747 if (out->children[1] >= count)
2748 out->children[1] -= 65536;
2749 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2750 Host_Error("Corrupt clipping hull(out of range planenum)");
2754 //Duplicate the drawing hull structure as a clipping hull
2755 static void Mod_Q1BSP_MakeHull0(void)
2762 hull = &loadmodel->brushq1.hulls[0];
2764 in = loadmodel->brush.data_nodes;
2765 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2767 hull->clipnodes = out;
2768 hull->firstclipnode = 0;
2769 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2770 hull->planes = loadmodel->brush.data_planes;
2772 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2774 out->planenum = in->plane - loadmodel->brush.data_planes;
2775 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2776 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2780 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2785 in = (short *)(mod_base + l->fileofs);
2786 if (l->filelen % sizeof(*in))
2787 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2788 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2789 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2791 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2793 j = (unsigned short) LittleShort(in[i]);
2794 if (j >= loadmodel->num_surfaces)
2795 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2796 loadmodel->brush.data_leafsurfaces[i] = j;
2800 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2805 in = (int *)(mod_base + l->fileofs);
2806 if (l->filelen % sizeof(*in))
2807 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2808 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2809 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2811 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2812 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2816 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2822 in = (dplane_t *)(mod_base + l->fileofs);
2823 if (l->filelen % sizeof(*in))
2824 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2826 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2827 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2829 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2831 out->normal[0] = LittleFloat(in->normal[0]);
2832 out->normal[1] = LittleFloat(in->normal[1]);
2833 out->normal[2] = LittleFloat(in->normal[2]);
2834 out->dist = LittleFloat(in->dist);
2840 static void Mod_Q1BSP_LoadMapBrushes(void)
2844 int submodel, numbrushes;
2845 qboolean firstbrush;
2846 char *text, *maptext;
2847 char mapfilename[MAX_QPATH];
2848 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2849 strlcat (mapfilename, ".map", sizeof (mapfilename));
2850 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
2854 if (!COM_ParseToken_Simple(&data, false, false))
2859 if (!COM_ParseToken_Simple(&data, false, false))
2861 if (com_token[0] != '{')
2867 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2870 if (!COM_ParseToken_Simple(&data, false, false))
2872 if (com_token[0] == '}')
2873 break; // end of entity
2874 if (com_token[0] == '{')
2881 if (submodel > loadmodel->brush.numsubmodels)
2883 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2887 model = loadmodel->brush.submodels[submodel];
2894 if (!COM_ParseToken_Simple(&data, false, false))
2896 if (com_token[0] == '}')
2897 break; // end of brush
2898 // each brush face should be this format:
2899 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2900 // FIXME: support hl .map format
2901 for (pointnum = 0;pointnum < 3;pointnum++)
2903 COM_ParseToken_Simple(&data, false, false);
2904 for (componentnum = 0;componentnum < 3;componentnum++)
2906 COM_ParseToken_Simple(&data, false, false);
2907 point[pointnum][componentnum] = atof(com_token);
2909 COM_ParseToken_Simple(&data, false, false);
2911 COM_ParseToken_Simple(&data, false, false);
2912 strlcpy(facetexture, com_token, sizeof(facetexture));
2913 COM_ParseToken_Simple(&data, false, false);
2914 //scroll_s = atof(com_token);
2915 COM_ParseToken_Simple(&data, false, false);
2916 //scroll_t = atof(com_token);
2917 COM_ParseToken_Simple(&data, false, false);
2918 //rotate = atof(com_token);
2919 COM_ParseToken_Simple(&data, false, false);
2920 //scale_s = atof(com_token);
2921 COM_ParseToken_Simple(&data, false, false);
2922 //scale_t = atof(com_token);
2923 TriangleNormal(point[0], point[1], point[2], planenormal);
2924 VectorNormalizeDouble(planenormal);
2925 planedist = DotProduct(point[0], planenormal);
2926 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2936 #define MAX_PORTALPOINTS 64
2938 typedef struct portal_s
2941 mnode_t *nodes[2]; // [0] = front side of plane
2942 struct portal_s *next[2];
2944 double points[3*MAX_PORTALPOINTS];
2945 struct portal_s *chain; // all portals are linked into a list
2949 static memexpandablearray_t portalarray;
2951 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2953 // process only nodes (leafs already had their box calculated)
2957 // calculate children first
2958 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2959 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2961 // make combined bounding box from children
2962 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2963 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2964 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2965 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2966 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2967 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2970 static void Mod_Q1BSP_FinalizePortals(void)
2972 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
2976 mleaf_t *leaf, *endleaf;
2978 // tally up portal and point counts and recalculate bounding boxes for all
2979 // leafs (because qbsp is very sloppy)
2980 leaf = loadmodel->brush.data_leafs;
2981 endleaf = leaf + loadmodel->brush.num_leafs;
2982 if (mod_recalculatenodeboxes.integer)
2984 for (;leaf < endleaf;leaf++)
2986 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
2987 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2992 for (portalindex = 0;portalindex < portalrange;portalindex++)
2994 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
2997 // note: this check must match the one below or it will usually corrupt memory
2998 // 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
2999 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3002 numpoints += p->numpoints * 2;
3005 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3006 loadmodel->brush.num_portals = numportals;
3007 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3008 loadmodel->brush.num_portalpoints = numpoints;
3009 // clear all leaf portal chains
3010 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3011 loadmodel->brush.data_leafs[i].portals = NULL;
3012 // process all portals in the global portal chain, while freeing them
3013 portal = loadmodel->brush.data_portals;
3014 point = loadmodel->brush.data_portalpoints;
3015 for (portalindex = 0;portalindex < portalrange;portalindex++)
3017 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3020 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3022 // note: this check must match the one above or it will usually corrupt memory
3023 // 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
3024 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3026 // first make the back to front portal(forward portal)
3027 portal->points = point;
3028 portal->numpoints = p->numpoints;
3029 portal->plane.dist = p->plane.dist;
3030 VectorCopy(p->plane.normal, portal->plane.normal);
3031 portal->here = (mleaf_t *)p->nodes[1];
3032 portal->past = (mleaf_t *)p->nodes[0];
3034 for (j = 0;j < portal->numpoints;j++)
3036 VectorCopy(p->points + j*3, point->position);
3039 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3040 PlaneClassify(&portal->plane);
3042 // link into leaf's portal chain
3043 portal->next = portal->here->portals;
3044 portal->here->portals = portal;
3046 // advance to next portal
3049 // then make the front to back portal(backward portal)
3050 portal->points = point;
3051 portal->numpoints = p->numpoints;
3052 portal->plane.dist = -p->plane.dist;
3053 VectorNegate(p->plane.normal, portal->plane.normal);
3054 portal->here = (mleaf_t *)p->nodes[0];
3055 portal->past = (mleaf_t *)p->nodes[1];
3057 for (j = portal->numpoints - 1;j >= 0;j--)
3059 VectorCopy(p->points + j*3, point->position);
3062 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3063 PlaneClassify(&portal->plane);
3065 // link into leaf's portal chain
3066 portal->next = portal->here->portals;
3067 portal->here->portals = portal;
3069 // advance to next portal
3072 // add the portal's polygon points to the leaf bounding boxes
3073 if (mod_recalculatenodeboxes.integer)
3075 for (i = 0;i < 2;i++)
3077 leaf = (mleaf_t *)p->nodes[i];
3078 for (j = 0;j < p->numpoints;j++)
3080 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3081 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3082 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3083 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3084 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3085 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3091 // now recalculate the node bounding boxes from the leafs
3092 if (mod_recalculatenodeboxes.integer)
3093 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3101 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3104 Host_Error("AddPortalToNodes: NULL front node");
3106 Host_Error("AddPortalToNodes: NULL back node");
3107 if (p->nodes[0] || p->nodes[1])
3108 Host_Error("AddPortalToNodes: already included");
3109 // 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
3111 p->nodes[0] = front;
3112 p->next[0] = (portal_t *)front->portals;
3113 front->portals = (mportal_t *)p;
3116 p->next[1] = (portal_t *)back->portals;
3117 back->portals = (mportal_t *)p;
3122 RemovePortalFromNode
3125 static void RemovePortalFromNodes(portal_t *portal)
3129 void **portalpointer;
3131 for (i = 0;i < 2;i++)
3133 node = portal->nodes[i];
3135 portalpointer = (void **) &node->portals;
3138 t = (portal_t *)*portalpointer;
3140 Host_Error("RemovePortalFromNodes: portal not in leaf");
3144 if (portal->nodes[0] == node)
3146 *portalpointer = portal->next[0];
3147 portal->nodes[0] = NULL;
3149 else if (portal->nodes[1] == node)
3151 *portalpointer = portal->next[1];
3152 portal->nodes[1] = NULL;
3155 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3159 if (t->nodes[0] == node)
3160 portalpointer = (void **) &t->next[0];
3161 else if (t->nodes[1] == node)
3162 portalpointer = (void **) &t->next[1];
3164 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3169 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3170 static double *portalpointsbuffer;
3171 static int portalpointsbufferoffset;
3172 static int portalpointsbuffersize;
3173 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3176 mnode_t *front, *back, *other_node;
3177 mplane_t clipplane, *plane;
3178 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3179 int numfrontpoints, numbackpoints;
3180 double *frontpoints, *backpoints;
3182 // if a leaf, we're done
3186 // get some space for our clipping operations to use
3187 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3189 portalpointsbuffersize = portalpointsbufferoffset * 2;
3190 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3192 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3193 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3194 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3195 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3197 plane = node->plane;
3199 front = node->children[0];
3200 back = node->children[1];
3202 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3204 // create the new portal by generating a polygon for the node plane,
3205 // and clipping it by all of the other portals(which came from nodes above this one)
3206 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3207 nodeportal->plane = *plane;
3209 // 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)
3210 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);
3211 nodeportal->numpoints = 4;
3212 side = 0; // shut up compiler warning
3213 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3215 clipplane = portal->plane;
3216 if (portal->nodes[0] == portal->nodes[1])
3217 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3218 if (portal->nodes[0] == node)
3220 else if (portal->nodes[1] == node)
3222 clipplane.dist = -clipplane.dist;
3223 VectorNegate(clipplane.normal, clipplane.normal);
3227 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3229 for (i = 0;i < nodeportal->numpoints*3;i++)
3230 frontpoints[i] = nodeportal->points[i];
3231 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);
3232 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3236 if (nodeportal->numpoints < 3)
3238 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3239 nodeportal->numpoints = 0;
3241 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3243 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3244 nodeportal->numpoints = 0;
3247 AddPortalToNodes(nodeportal, front, back);
3249 // split the portals of this node along this node's plane and assign them to the children of this node
3250 // (migrating the portals downward through the tree)
3251 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3253 if (portal->nodes[0] == portal->nodes[1])
3254 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3255 if (portal->nodes[0] == node)
3257 else if (portal->nodes[1] == node)
3260 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3261 nextportal = portal->next[side];
3262 if (!portal->numpoints)
3265 other_node = portal->nodes[!side];
3266 RemovePortalFromNodes(portal);
3268 // cut the portal into two portals, one on each side of the node plane
3269 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);
3271 if (!numfrontpoints)
3274 AddPortalToNodes(portal, back, other_node);
3276 AddPortalToNodes(portal, other_node, back);
3282 AddPortalToNodes(portal, front, other_node);
3284 AddPortalToNodes(portal, other_node, front);
3288 // the portal is split
3289 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3290 temp = splitportal->chain;
3291 *splitportal = *portal;
3292 splitportal->chain = temp;
3293 for (i = 0;i < numbackpoints*3;i++)
3294 splitportal->points[i] = backpoints[i];
3295 splitportal->numpoints = numbackpoints;
3296 for (i = 0;i < numfrontpoints*3;i++)
3297 portal->points[i] = frontpoints[i];
3298 portal->numpoints = numfrontpoints;
3302 AddPortalToNodes(portal, front, other_node);
3303 AddPortalToNodes(splitportal, back, other_node);
3307 AddPortalToNodes(portal, other_node, front);
3308 AddPortalToNodes(splitportal, other_node, back);
3312 Mod_Q1BSP_RecursiveNodePortals(front);
3313 Mod_Q1BSP_RecursiveNodePortals(back);
3315 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3318 static void Mod_Q1BSP_MakePortals(void)
3320 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3321 portalpointsbufferoffset = 0;
3322 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3323 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3324 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3325 Mem_Free(portalpointsbuffer);
3326 portalpointsbuffer = NULL;
3327 portalpointsbufferoffset = 0;
3328 portalpointsbuffersize = 0;
3329 Mod_Q1BSP_FinalizePortals();
3330 Mem_ExpandableArray_FreeArray(&portalarray);
3333 //Returns PVS data for a given point
3334 //(note: can return NULL)
3335 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3338 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3340 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3341 if (((mleaf_t *)node)->clusterindex >= 0)
3342 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3347 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)
3351 float d = PlaneDiff(org, node->plane);
3353 node = node->children[0];
3354 else if (d < -radius)
3355 node = node->children[1];
3358 // go down both sides
3359 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3360 node = node->children[1];
3363 // if this leaf is in a cluster, accumulate the pvs bits
3364 if (((mleaf_t *)node)->clusterindex >= 0)
3367 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3368 for (i = 0;i < pvsbytes;i++)
3369 pvsbuffer[i] |= pvs[i];
3373 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3374 //of the given point.
3375 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3377 int bytes = model->brush.num_pvsclusterbytes;
3378 bytes = min(bytes, pvsbufferlength);
3379 if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3381 memset(pvsbuffer, 0xFF, bytes);
3385 memset(pvsbuffer, 0, bytes);
3386 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3390 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3395 VectorSubtract(inmaxs, inmins, size);
3396 if (cmodel->brush.ishlbsp)
3399 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3400 else if (size[0] <= 32)
3402 if (size[2] < 54) // pick the nearest of 36 or 72
3403 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3405 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3408 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3413 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3414 else if (size[0] <= 32)
3415 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3417 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3419 VectorCopy(inmins, outmins);
3420 VectorAdd(inmins, hull->clip_size, outmaxs);
3423 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3426 int numshadowmeshtriangles = 0;
3427 msurface_t *surface;
3428 if (cls.state == ca_dedicated)
3430 // make a single combined shadow mesh to allow optimized shadow volume creation
3432 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3434 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3435 numshadowmeshtriangles += surface->num_triangles;
3437 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3438 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3439 if (surface->num_triangles > 0)
3440 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));
3441 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, true, false);
3442 if (mod->brush.shadowmesh)
3443 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3445 return numshadowmeshtriangles;
3448 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3453 float dist, modelyawradius, modelradius;
3454 msurface_t *surface;
3455 hullinfo_t hullinfo;
3456 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3457 model_brush_lightstyleinfo_t styleinfo[256];
3458 unsigned char *datapointer;
3460 mod->modeldatatypestring = "Q1BSP";
3462 mod->type = mod_brushq1;
3464 header = (dheader_t *)buffer;
3466 i = LittleLong(header->version);
3467 if (i != BSPVERSION && i != 30)
3468 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3469 mod->brush.ishlbsp = i == 30;
3471 // fill in hull info
3472 VectorClear (hullinfo.hullsizes[0][0]);
3473 VectorClear (hullinfo.hullsizes[0][1]);
3474 if (mod->brush.ishlbsp)
3476 mod->modeldatatypestring = "HLBSP";
3478 hullinfo.filehulls = 4;
3479 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3480 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3481 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3482 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3483 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3484 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3488 hullinfo.filehulls = 4;
3489 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3490 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3491 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3492 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3496 mod_base = (unsigned char*)buffer;
3497 for (i = 0; i < HEADER_LUMPS; i++)
3499 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3500 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3503 mod->soundfromcenter = true;
3504 mod->TraceBox = Mod_Q1BSP_TraceBox;
3505 mod->TraceLine = Mod_Q1BSP_TraceLine;
3506 mod->TracePoint = Mod_Q1BSP_TracePoint;
3507 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3508 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3509 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3510 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3511 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3512 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3513 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3514 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3515 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3516 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3517 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3518 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3519 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3520 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3521 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3522 mod->Draw = R_Q1BSP_Draw;
3523 mod->DrawDepth = R_Q1BSP_DrawDepth;
3524 mod->DrawDebug = R_Q1BSP_DrawDebug;
3525 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3526 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3527 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3528 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3529 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3530 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3531 mod->DrawLight = R_Q1BSP_DrawLight;
3535 mod->brush.qw_md4sum = 0;
3536 mod->brush.qw_md4sum2 = 0;
3537 for (i = 0;i < HEADER_LUMPS;i++)
3540 if (i == LUMP_ENTITIES)
3542 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3543 mod->brush.qw_md4sum ^= LittleLong(temp);
3544 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3546 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3547 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3550 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3551 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3552 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3553 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3554 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3555 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3556 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3557 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3558 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3559 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3560 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3561 // load submodels before leafs because they contain the number of vis leafs
3562 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3563 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3564 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3565 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3567 // check if the map supports transparent water rendering
3568 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3570 if (mod->brushq1.data_compressedpvs)
3571 Mem_Free(mod->brushq1.data_compressedpvs);
3572 mod->brushq1.data_compressedpvs = NULL;
3573 mod->brushq1.num_compressedpvs = 0;
3575 Mod_Q1BSP_MakeHull0();
3576 Mod_Q1BSP_MakePortals();
3578 mod->numframes = 2; // regular and alternate animation
3581 // make a single combined shadow mesh to allow optimized shadow volume creation
3582 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3584 if (loadmodel->brush.numsubmodels)
3585 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3587 // LordHavoc: to clear the fog around the original quake submodel code, I
3589 // first of all, some background info on the submodels:
3590 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3591 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3592 // now the weird for loop itself:
3593 // the loop functions in an odd way, on each iteration it sets up the
3594 // current 'mod' model (which despite the confusing code IS the model of
3595 // the number i), at the end of the loop it duplicates the model to become
3596 // the next submodel, and loops back to set up the new submodel.
3598 // LordHavoc: now the explanation of my sane way (which works identically):
3599 // set up the world model, then on each submodel copy from the world model
3600 // and set up the submodel with the respective model info.
3601 totalstylesurfaces = 0;
3603 for (i = 0;i < mod->brush.numsubmodels;i++)
3605 memset(stylecounts, 0, sizeof(stylecounts));
3606 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3608 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3609 for (j = 0;j < MAXLIGHTMAPS;j++)
3610 stylecounts[surface->lightmapinfo->styles[j]]++;
3612 for (k = 0;k < 255;k++)
3616 totalstylesurfaces += stylecounts[k];
3619 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3620 for (i = 0;i < mod->brush.numsubmodels;i++)
3622 // LordHavoc: this code was originally at the end of this loop, but
3623 // has been transformed to something more readable at the start here.
3628 // duplicate the basic information
3629 dpsnprintf(name, sizeof(name), "*%i", i);
3630 mod = Mod_FindName(name, loadmodel->name);
3631 // copy the base model to this one
3633 // rename the clone back to its proper name
3634 strlcpy(mod->name, name, sizeof(mod->name));
3635 mod->brush.parentmodel = loadmodel;
3636 // textures and memory belong to the main model
3637 mod->texturepool = NULL;
3638 mod->mempool = NULL;
3639 mod->brush.GetPVS = NULL;
3640 mod->brush.FatPVS = NULL;
3641 mod->brush.BoxTouchingPVS = NULL;
3642 mod->brush.BoxTouchingLeafPVS = NULL;
3643 mod->brush.BoxTouchingVisibleLeafs = NULL;
3644 mod->brush.FindBoxClusters = NULL;
3645 mod->brush.LightPoint = NULL;
3646 mod->brush.AmbientSoundLevelsForPoint = NULL;
3649 mod->brush.submodel = i;
3651 if (loadmodel->brush.submodels)
3652 loadmodel->brush.submodels[i] = mod;
3654 bm = &mod->brushq1.submodels[i];
3656 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3657 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3659 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3660 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3663 mod->firstmodelsurface = bm->firstface;
3664 mod->nummodelsurfaces = bm->numfaces;
3666 // set node/leaf parents for this submodel
3667 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3669 // make the model surface list (used by shadowing/lighting)
3670 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3671 Mod_MakeSortedSurfaces(mod);
3673 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3674 // (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)
3675 VectorCopy(bm->mins, mod->normalmins);
3676 VectorCopy(bm->maxs, mod->normalmaxs);
3677 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3678 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3679 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3680 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3681 modelradius = modelyawradius + modelradius * modelradius;
3682 modelyawradius = sqrt(modelyawradius);
3683 modelradius = sqrt(modelradius);
3684 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3685 mod->yawmins[2] = mod->normalmins[2];
3686 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3687 mod->yawmaxs[2] = mod->normalmaxs[2];
3688 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3689 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3690 mod->radius = modelradius;
3691 mod->radius2 = modelradius * modelradius;
3693 // this gets altered below if sky or water is used
3694 mod->DrawSky = NULL;
3695 mod->DrawAddWaterPlanes = NULL;
3697 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3698 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3699 if (mod->nummodelsurfaces)
3701 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3702 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3704 if (j < mod->nummodelsurfaces)
3705 mod->DrawSky = R_Q1BSP_DrawSky;
3707 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3708 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
3710 if (j < mod->nummodelsurfaces)
3711 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3713 // build lightstyle update chains
3714 // (used to rapidly mark lightmapupdateflags on many surfaces
3715 // when d_lightstylevalue changes)
3716 memset(stylecounts, 0, sizeof(stylecounts));
3717 for (k = 0;k < mod->nummodelsurfaces;k++)
3719 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3720 for (j = 0;j < MAXLIGHTMAPS;j++)
3721 stylecounts[surface->lightmapinfo->styles[j]]++;
3723 mod->brushq1.num_lightstyles = 0;
3724 for (k = 0;k < 255;k++)
3728 styleinfo[mod->brushq1.num_lightstyles].style = k;
3729 styleinfo[mod->brushq1.num_lightstyles].value = 0;
3730 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3731 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3732 remapstyles[k] = mod->brushq1.num_lightstyles;
3733 mod->brushq1.num_lightstyles++;
3736 for (k = 0;k < mod->nummodelsurfaces;k++)
3738 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3739 for (j = 0;j < MAXLIGHTMAPS;j++)
3741 if (surface->lightmapinfo->styles[j] != 255)
3743 int r = remapstyles[surface->lightmapinfo->styles[j]];
3744 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3748 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3749 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3753 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3754 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3756 //mod->brushq1.num_visleafs = bm->visleafs;
3758 // build a Bounding Interval Hierarchy for culling triangles in light rendering
3759 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
3761 if (mod_q1bsp_polygoncollisions.integer)
3763 mod->collision_bih = mod->render_bih;
3764 // point traces and contents checks still use the bsp tree
3765 mod->TraceLine = Mod_CollisionBIH_TraceLine;
3766 mod->TraceBox = Mod_CollisionBIH_TraceBox;
3767 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
3770 // generate VBOs and other shared data before cloning submodels
3774 Mod_Q1BSP_LoadMapBrushes();
3775 //Mod_Q1BSP_ProcessLightList();
3779 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);
3782 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3786 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3793 in = (void *)(mod_base + l->fileofs);
3794 if (l->filelen % sizeof(*in))
3795 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3796 count = l->filelen / sizeof(*in);
3797 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3800 loadmodel->num = count;
3802 for (i = 0;i < count;i++, in++, out++)
3808 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3815 in = (void *)(mod_base + l->fileofs);
3816 if (l->filelen % sizeof(*in))
3817 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3818 count = l->filelen / sizeof(*in);
3819 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3822 loadmodel->num = count;
3824 for (i = 0;i < count;i++, in++, out++)
3830 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3837 in = (void *)(mod_base + l->fileofs);
3838 if (l->filelen % sizeof(*in))
3839 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3840 count = l->filelen / sizeof(*in);
3841 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3844 loadmodel->num = count;
3846 for (i = 0;i < count;i++, in++, out++)
3852 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3859 in = (void *)(mod_base + l->fileofs);
3860 if (l->filelen % sizeof(*in))
3861 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3862 count = l->filelen / sizeof(*in);
3863 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3866 loadmodel->num = count;
3868 for (i = 0;i < count;i++, in++, out++)
3874 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3881 in = (void *)(mod_base + l->fileofs);
3882 if (l->filelen % sizeof(*in))
3883 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3884 count = l->filelen / sizeof(*in);
3885 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3888 loadmodel->num = count;
3890 for (i = 0;i < count;i++, in++, out++)
3896 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3903 in = (void *)(mod_base + l->fileofs);
3904 if (l->filelen % sizeof(*in))
3905 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3906 count = l->filelen / sizeof(*in);
3907 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3910 loadmodel->num = count;
3912 for (i = 0;i < count;i++, in++, out++)
3918 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3925 in = (void *)(mod_base + l->fileofs);
3926 if (l->filelen % sizeof(*in))
3927 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3928 count = l->filelen / sizeof(*in);
3929 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3932 loadmodel->num = count;
3934 for (i = 0;i < count;i++, in++, out++)
3940 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3947 in = (void *)(mod_base + l->fileofs);
3948 if (l->filelen % sizeof(*in))
3949 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3950 count = l->filelen / sizeof(*in);
3951 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3954 loadmodel->num = count;
3956 for (i = 0;i < count;i++, in++, out++)
3962 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3969 in = (void *)(mod_base + l->fileofs);
3970 if (l->filelen % sizeof(*in))
3971 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3972 count = l->filelen / sizeof(*in);
3973 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3976 loadmodel->num = count;
3978 for (i = 0;i < count;i++, in++, out++)
3984 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3991 in = (void *)(mod_base + l->fileofs);
3992 if (l->filelen % sizeof(*in))
3993 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3994 count = l->filelen / sizeof(*in);
3995 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3998 loadmodel->num = count;
4000 for (i = 0;i < count;i++, in++, out++)
4006 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4013 in = (void *)(mod_base + l->fileofs);
4014 if (l->filelen % sizeof(*in))
4015 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4016 count = l->filelen / sizeof(*in);
4017 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4020 loadmodel->num = count;
4022 for (i = 0;i < count;i++, in++, out++)
4028 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4035 in = (void *)(mod_base + l->fileofs);
4036 if (l->filelen % sizeof(*in))
4037 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4038 count = l->filelen / sizeof(*in);
4039 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4042 loadmodel->num = count;
4044 for (i = 0;i < count;i++, in++, out++)
4050 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4057 in = (void *)(mod_base + l->fileofs);
4058 if (l->filelen % sizeof(*in))
4059 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4060 count = l->filelen / sizeof(*in);
4061 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4064 loadmodel->num = count;
4066 for (i = 0;i < count;i++, in++, out++)
4072 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4079 in = (void *)(mod_base + l->fileofs);
4080 if (l->filelen % sizeof(*in))
4081 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4082 count = l->filelen / sizeof(*in);
4083 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4086 loadmodel->num = count;
4088 for (i = 0;i < count;i++, in++, out++)
4094 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4101 in = (void *)(mod_base + l->fileofs);
4102 if (l->filelen % sizeof(*in))
4103 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4104 count = l->filelen / sizeof(*in);
4105 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4108 loadmodel->num = count;
4110 for (i = 0;i < count;i++, in++, out++)
4116 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4123 in = (void *)(mod_base + l->fileofs);
4124 if (l->filelen % sizeof(*in))
4125 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4126 count = l->filelen / sizeof(*in);
4127 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4130 loadmodel->num = count;
4132 for (i = 0;i < count;i++, in++, out++)
4138 static void Mod_Q2BSP_LoadModels(lump_t *l)
4145 in = (void *)(mod_base + l->fileofs);
4146 if (l->filelen % sizeof(*in))
4147 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4148 count = l->filelen / sizeof(*in);
4149 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4152 loadmodel->num = count;
4154 for (i = 0;i < count;i++, in++, out++)
4160 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4163 q2dheader_t *header;
4165 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4167 mod->modeldatatypestring = "Q2BSP";
4169 mod->type = mod_brushq2;
4171 header = (q2dheader_t *)buffer;
4173 i = LittleLong(header->version);
4174 if (i != Q2BSPVERSION)
4175 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4177 mod_base = (unsigned char *)header;
4179 // swap all the lumps
4180 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4181 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4183 mod->brush.qw_md4sum = 0;
4184 mod->brush.qw_md4sum2 = 0;
4185 for (i = 0;i < Q2HEADER_LUMPS;i++)
4187 if (i == Q2LUMP_ENTITIES)
4189 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4190 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4192 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4195 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4196 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4197 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4198 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4199 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4200 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4201 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4202 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4203 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4204 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4205 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4206 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4207 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4208 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4209 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4210 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4211 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4212 // LordHavoc: must go last because this makes the submodels
4213 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4216 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4217 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4219 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4222 char key[128], value[MAX_INPUTLINE];
4224 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4225 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4226 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4229 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4230 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4231 loadmodel->brush.entities[l->filelen] = 0;
4232 data = loadmodel->brush.entities;
4233 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4234 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4235 loadmodel->brushq3.deluxemapping = false;
4236 if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4240 if (!COM_ParseToken_Simple(&data, false, false))
4242 if (com_token[0] == '}')
4243 break; // end of worldspawn
4244 if (com_token[0] == '_')
4245 strlcpy(key, com_token + 1, sizeof(key));
4247 strlcpy(key, com_token, sizeof(key));
4248 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4249 key[strlen(key)-1] = 0;
4250 if (!COM_ParseToken_Simple(&data, false, false))
4252 strlcpy(value, com_token, sizeof(value));
4253 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4255 #if _MSC_VER >= 1400
4256 #define sscanf sscanf_s
4259 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4260 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4262 VectorSet(v, 64, 64, 128);
4263 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4264 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]);
4265 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4266 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4269 else if (!strcmp("deluxeMaps", key))
4271 if (!strcmp(com_token, "1"))
4273 loadmodel->brushq3.deluxemapping = true;
4274 loadmodel->brushq3.deluxemapping_modelspace = true;
4276 else if (!strcmp(com_token, "2"))
4278 loadmodel->brushq3.deluxemapping = true;
4279 loadmodel->brushq3.deluxemapping_modelspace = false;
4286 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4292 in = (q3dtexture_t *)(mod_base + l->fileofs);
4293 if (l->filelen % sizeof(*in))
4294 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4295 count = l->filelen / sizeof(*in);
4296 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4298 loadmodel->data_textures = out;
4299 loadmodel->num_textures = count;
4300 loadmodel->num_texturesperskin = loadmodel->num_textures;
4302 for (i = 0;i < count;i++)
4304 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4305 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4306 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4307 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4308 // restore the surfaceflags and supercontents
4309 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4310 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4314 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4320 in = (q3dplane_t *)(mod_base + l->fileofs);
4321 if (l->filelen % sizeof(*in))
4322 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4323 count = l->filelen / sizeof(*in);
4324 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4326 loadmodel->brush.data_planes = out;
4327 loadmodel->brush.num_planes = count;
4329 for (i = 0;i < count;i++, in++, out++)
4331 out->normal[0] = LittleFloat(in->normal[0]);
4332 out->normal[1] = LittleFloat(in->normal[1]);
4333 out->normal[2] = LittleFloat(in->normal[2]);
4334 out->dist = LittleFloat(in->dist);
4339 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4342 q3mbrushside_t *out;
4345 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4346 if (l->filelen % sizeof(*in))
4347 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4348 count = l->filelen / sizeof(*in);
4349 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4351 loadmodel->brush.data_brushsides = out;
4352 loadmodel->brush.num_brushsides = count;
4354 for (i = 0;i < count;i++, in++, out++)
4356 n = LittleLong(in->planeindex);
4357 if (n < 0 || n >= loadmodel->brush.num_planes)
4358 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4359 out->plane = loadmodel->brush.data_planes + n;
4360 n = LittleLong(in->textureindex);
4361 if (n < 0 || n >= loadmodel->num_textures)
4362 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4363 out->texture = loadmodel->data_textures + n;
4367 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4369 q3dbrushside_ig_t *in;
4370 q3mbrushside_t *out;
4373 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4374 if (l->filelen % sizeof(*in))
4375 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4376 count = l->filelen / sizeof(*in);
4377 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4379 loadmodel->brush.data_brushsides = out;
4380 loadmodel->brush.num_brushsides = count;
4382 for (i = 0;i < count;i++, in++, out++)
4384 n = LittleLong(in->planeindex);
4385 if (n < 0 || n >= loadmodel->brush.num_planes)
4386 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4387 out->plane = loadmodel->brush.data_planes + n;
4388 n = LittleLong(in->textureindex);
4389 if (n < 0 || n >= loadmodel->num_textures)
4390 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4391 out->texture = loadmodel->data_textures + n;
4395 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4399 int i, j, n, c, count, maxplanes, q3surfaceflags;
4400 colplanef_t *planes;
4402 in = (q3dbrush_t *)(mod_base + l->fileofs);
4403 if (l->filelen % sizeof(*in))
4404 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4405 count = l->filelen / sizeof(*in);
4406 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4408 loadmodel->brush.data_brushes = out;
4409 loadmodel->brush.num_brushes = count;
4414 for (i = 0;i < count;i++, in++, out++)
4416 n = LittleLong(in->firstbrushside);
4417 c = LittleLong(in->numbrushsides);
4418 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4419 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4420 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4421 out->numbrushsides = c;
4422 n = LittleLong(in->textureindex);
4423 if (n < 0 || n >= loadmodel->num_textures)
4424 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4425 out->texture = loadmodel->data_textures + n;
4427 // make a list of mplane_t structs to construct a colbrush from
4428 if (maxplanes < out->numbrushsides)
4430 maxplanes = out->numbrushsides;
4433 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4436 for (j = 0;j < out->numbrushsides;j++)
4438 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4439 planes[j].dist = out->firstbrushside[j].plane->dist;
4440 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4441 planes[j].texture = out->firstbrushside[j].texture;
4442 q3surfaceflags |= planes[j].q3surfaceflags;
4444 // make the colbrush from the planes
4445 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4447 // this whole loop can take a while (e.g. on redstarrepublic4)
4448 CL_KeepaliveMessage(false);
4454 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4460 in = (q3deffect_t *)(mod_base + l->fileofs);
4461 if (l->filelen % sizeof(*in))
4462 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4463 count = l->filelen / sizeof(*in);
4464 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4466 loadmodel->brushq3.data_effects = out;
4467 loadmodel->brushq3.num_effects = count;
4469 for (i = 0;i < count;i++, in++, out++)
4471 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4472 n = LittleLong(in->brushindex);
4473 if (n >= loadmodel->brush.num_brushes)
4475 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4478 out->brushindex = n;
4479 out->unknown = LittleLong(in->unknown);
4483 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4488 in = (q3dvertex_t *)(mod_base + l->fileofs);
4489 if (l->filelen % sizeof(*in))
4490 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4491 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4492 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4493 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4494 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4495 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4496 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4498 for (i = 0;i < count;i++, in++)
4500 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4501 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4502 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4503 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4504 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4505 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4506 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4507 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4508 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4509 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4510 // svector/tvector are calculated later in face loading
4511 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4512 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4513 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4514 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4515 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4516 loadmodel->lit = true;
4520 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4526 in = (int *)(mod_base + l->fileofs);
4527 if (l->filelen % sizeof(int[3]))
4528 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4529 count = l->filelen / sizeof(*in);
4531 if(!loadmodel->brushq3.num_vertices)
4534 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4535 loadmodel->brushq3.num_triangles = 0;
4539 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4540 loadmodel->brushq3.num_triangles = count / 3;
4541 loadmodel->brushq3.data_element3i = out;
4543 for (i = 0;i < count;i++, in++, out++)
4545 *out = LittleLong(*in);
4546 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4548 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4554 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4556 q3dlightmap_t *input_pointer;
4574 int mergedrowsxcolumns;
4579 unsigned char *mergedpixels;
4580 unsigned char *mergeddeluxepixels;
4581 unsigned char *mergebuf;
4582 char mapname[MAX_QPATH];
4584 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4586 // defaults for q3bsp
4593 loadmodel->brushq3.lightmapsize = 128;
4595 if (cls.state == ca_dedicated)
4598 if(mod_q3bsp_nolightmaps.integer)
4604 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4605 if (developer_loading.integer)
4606 Con_Printf("Using internal lightmaps\n");
4607 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4608 if (l->filelen % sizeof(*input_pointer))
4609 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4610 count = l->filelen / sizeof(*input_pointer);
4611 for(i = 0; i < count; ++i)
4612 inpixels[i] = input_pointer[i].rgb;
4616 // no internal lightmaps
4617 // try external lightmaps
4618 if (developer_loading.integer)
4619 Con_Printf("Using external lightmaps\n");
4620 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4621 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false, NULL);
4625 // using EXTERNAL lightmaps instead
4626 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4628 Mem_Free(inpixels[0]);
4629 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4639 for(count = 1; ; ++count)
4641 inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false, NULL);
4642 if(!inpixels[count])
4643 break; // we got all of them
4644 if(image_width != size || image_height != size)
4646 Mem_Free(inpixels[count]);
4647 inpixels[count] = NULL;
4648 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);
4654 loadmodel->brushq3.lightmapsize = size;
4655 loadmodel->brushq3.num_originallightmaps = count;
4657 // now check the surfaces to see if any of them index an odd numbered
4658 // lightmap, if so this is not a deluxemapped bsp file
4660 // also check what lightmaps are actually used, because q3map2 sometimes
4661 // (always?) makes an unused one at the end, which
4662 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4663 // reason when only one lightmap is used, which can throw off the
4664 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4665 // to see if the second lightmap is blank, if so it is not deluxemapped.
4666 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4667 // in Mod_Q3BSP_LoadEntities was failed
4668 if (!loadmodel->brushq3.deluxemapping)
4670 loadmodel->brushq3.deluxemapping = !(count & 1);
4671 loadmodel->brushq3.deluxemapping_modelspace = true;
4673 if (loadmodel->brushq3.deluxemapping)
4675 int facecount = faceslump->filelen / sizeof(q3dface_t);
4676 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4677 for (i = 0;i < facecount;i++)
4679 j = LittleLong(faces[i].lightmapindex);
4682 endlightmap = max(endlightmap, j + 1);
4683 if ((j & 1) || j + 1 >= count)
4685 loadmodel->brushq3.deluxemapping = false;
4692 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4693 // reason when only one lightmap is used, which can throw off the
4694 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4695 // to see if the second lightmap is blank, if so it is not deluxemapped.
4697 // further research has shown q3map2 sometimes creates a deluxemap and two
4698 // blank lightmaps, which must be handled properly as well
4699 if (endlightmap == 1 && count > 1)
4702 for (i = 0;i < size*size;i++)
4704 if (c[bytesperpixel*i + rgbmap[0]])
4706 if (c[bytesperpixel*i + rgbmap[1]])
4708 if (c[bytesperpixel*i + rgbmap[2]])
4713 // all pixels in the unused lightmap were black...
4714 loadmodel->brushq3.deluxemapping = false;
4719 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4721 // figure out what the most reasonable merge power is within limits
4723 // find the appropriate NxN dimensions to merge to, to avoid wasted space
4724 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
4726 // figure out how big the merged texture has to be
4727 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
4728 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
4729 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
4731 mergedwidth = mergegoal;
4732 mergedheight = mergegoal;
4733 // choose non-square size (2x1 aspect) if only half the space is used;
4734 // this really only happens when the entire set fits in one texture, if
4735 // there are multiple textures, we don't worry about shrinking the last
4736 // one to fit, because the driver prefers the same texture size on
4737 // consecutive draw calls...
4738 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
4741 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
4742 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
4743 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
4744 loadmodel->brushq3.num_lightmapmergedwidthpower++;
4745 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
4746 loadmodel->brushq3.num_lightmapmergedheightpower++;
4747 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
4749 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
4750 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
4751 powerxy = powerx+powery;
4752 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
4754 mergedcolumns = 1 << powerx;
4755 mergedrows = 1 << powery;
4756 mergedrowsxcolumns = 1 << powerxy;
4758 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
4759 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4760 if (loadmodel->brushq3.deluxemapping)
4761 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4763 // allocate a texture pool if we need it
4764 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4765 loadmodel->texturepool = R_AllocTexturePool();
4767 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
4768 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
4769 for (i = 0;i < count;i++)
4771 // figure out which merged lightmap texture this fits into
4772 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
4773 lightmapindex = i >> powerdxy;
4775 // choose the destination address
4776 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
4777 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
4778 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
4779 Con_Printf("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);
4781 // convert pixels from RGB or BGRA while copying them into the destination rectangle
4782 for (j = 0;j < size;j++)
4783 for (k = 0;k < size;k++)
4785 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
4786 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
4787 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
4788 mergebuf[(j*mergedwidth+k)*4+3] = 255;
4791 // upload texture if this was the last tile being written to the texture
4792 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
4794 if (loadmodel->brushq3.deluxemapping && (i & 1))
4795 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%04i", lightmapindex), mergedwidth, mergedheight, mergeddeluxepixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
4797 loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
4801 if (mergeddeluxepixels)
4802 Mem_Free(mergeddeluxepixels);
4803 Mem_Free(mergedpixels);
4806 for(i = 0; i < count; ++i)
4807 Mem_Free(inpixels[i]);
4811 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
4816 *collisionstride = stride;
4819 cnt = (num_triangles + stride - 1) / stride;
4820 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
4821 for(j = 0; j < cnt; ++j)
4823 mins = &((*collisionbbox6f)[6 * j + 0]);
4824 maxs = &((*collisionbbox6f)[6 * j + 3]);
4825 for(k = 0; k < stride; ++k)
4827 tri = j * stride + k;
4828 if(tri >= num_triangles)
4830 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
4831 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
4832 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
4833 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
4834 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
4835 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
4836 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
4837 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
4838 if(vert[0] < mins[0]) mins[0] = vert[0];
4839 if(vert[1] < mins[1]) mins[1] = vert[1];
4840 if(vert[2] < mins[2]) mins[2] = vert[2];
4841 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4842 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4843 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4844 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
4845 if(vert[0] < mins[0]) mins[0] = vert[0];
4846 if(vert[1] < mins[1]) mins[1] = vert[1];
4847 if(vert[2] < mins[2]) mins[2] = vert[2];
4848 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4849 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4850 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4855 *collisionbbox6f = NULL;
4858 typedef struct patchtess_s
4862 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
4865 float *originalvertex3f;
4868 #define PATCHTESS_SAME_LODGROUP(a,b) \
4870 (a).lodgroup[0] == (b).lodgroup[0] && \
4871 (a).lodgroup[1] == (b).lodgroup[1] && \
4872 (a).lodgroup[2] == (b).lodgroup[2] && \
4873 (a).lodgroup[3] == (b).lodgroup[3] && \
4874 (a).lodgroup[4] == (b).lodgroup[4] && \
4875 (a).lodgroup[5] == (b).lodgroup[5] \
4878 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4880 q3dface_t *in, *oldin;
4881 msurface_t *out, *oldout;
4882 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;
4883 float lightmaptcbase[2], lightmaptcscale[2];
4884 //int *originalelement3i;
4885 //int *originalneighbor3i;
4886 float *originalvertex3f;
4887 //float *originalsvector3f;
4888 //float *originaltvector3f;
4889 float *originalnormal3f;
4890 float *originalcolor4f;
4891 float *originaltexcoordtexture2f;
4892 float *originaltexcoordlightmap2f;
4893 float *surfacecollisionvertex3f;
4894 int *surfacecollisionelement3i;
4896 patchtess_t *patchtess = NULL;
4897 int patchtesscount = 0;
4900 in = (q3dface_t *)(mod_base + l->fileofs);
4901 if (l->filelen % sizeof(*in))
4902 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4903 count = l->filelen / sizeof(*in);
4904 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4906 loadmodel->data_surfaces = out;
4907 loadmodel->num_surfaces = count;
4910 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
4918 for (;i < count;i++, in++, out++)
4920 // check face type first
4921 type = LittleLong(in->type);
4922 if (type != Q3FACETYPE_FLAT
4923 && type != Q3FACETYPE_PATCH
4924 && type != Q3FACETYPE_MESH
4925 && type != Q3FACETYPE_FLARE)
4927 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4931 n = LittleLong(in->textureindex);
4932 if (n < 0 || n >= loadmodel->num_textures)
4934 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4937 out->texture = loadmodel->data_textures + n;
4938 n = LittleLong(in->effectindex);
4939 if (n < -1 || n >= loadmodel->brushq3.num_effects)
4941 if (developer_extra.integer)
4942 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4948 out->effect = loadmodel->brushq3.data_effects + n;
4950 if (cls.state != ca_dedicated)
4952 out->lightmaptexture = NULL;
4953 out->deluxemaptexture = r_texture_blanknormalmap;
4954 n = LittleLong(in->lightmapindex);
4957 else if (n >= loadmodel->brushq3.num_originallightmaps)
4959 if(loadmodel->brushq3.num_originallightmaps != 0)
4960 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
4965 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
4966 if (loadmodel->brushq3.deluxemapping)
4967 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
4968 loadmodel->lit = true;
4972 firstvertex = LittleLong(in->firstvertex);
4973 numvertices = LittleLong(in->numvertices);
4974 firstelement = LittleLong(in->firstelement);
4975 numtriangles = LittleLong(in->numelements) / 3;
4976 if (numtriangles * 3 != LittleLong(in->numelements))
4978 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));
4981 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4983 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);
4986 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4988 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);
4993 case Q3FACETYPE_FLAT:
4994 case Q3FACETYPE_MESH:
4995 // no processing necessary
4997 case Q3FACETYPE_PATCH:
4998 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4999 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5000 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))
5002 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5005 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5007 // convert patch to Q3FACETYPE_MESH
5008 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5009 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5010 // bound to user settings
5011 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5012 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5013 // bound to sanity settings
5014 xtess = bound(0, xtess, 1024);
5015 ytess = bound(0, ytess, 1024);
5017 // lower quality collision patches! Same procedure as before, but different cvars
5018 // convert patch to Q3FACETYPE_MESH
5019 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5020 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5021 // bound to user settings
5022 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5023 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5024 // bound to sanity settings
5025 cxtess = bound(0, cxtess, 1024);
5026 cytess = bound(0, cytess, 1024);
5028 // store it for the LOD grouping step
5029 patchtess[patchtesscount].info.xsize = patchsize[0];
5030 patchtess[patchtesscount].info.ysize = patchsize[1];
5031 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5032 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5033 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5034 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5036 patchtess[patchtesscount].surface_id = i;
5037 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5038 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5039 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5040 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5041 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5042 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5043 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5046 case Q3FACETYPE_FLARE:
5047 if (developer_extra.integer)
5048 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5052 out->num_vertices = numvertices;
5053 out->num_triangles = numtriangles;
5054 meshvertices += out->num_vertices;
5055 meshtriangles += out->num_triangles;
5058 // Fix patches tesselations so that they make no seams
5062 for(i = 0; i < patchtesscount; ++i)
5064 for(j = i+1; j < patchtesscount; ++j)
5066 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5069 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5076 // Calculate resulting number of triangles
5077 collisionvertices = 0;
5078 collisiontriangles = 0;
5079 for(i = 0; i < patchtesscount; ++i)
5081 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5082 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5083 numvertices = finalwidth * finalheight;
5084 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5086 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5087 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5088 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5089 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5091 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5092 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5093 numvertices = finalwidth * finalheight;
5094 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5096 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5097 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5098 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5099 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5105 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5106 if (collisiontriangles)
5108 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5109 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5113 collisionvertices = 0;
5114 collisiontriangles = 0;
5115 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5117 if (out->num_vertices < 3 || out->num_triangles < 1)
5120 type = LittleLong(in->type);
5121 firstvertex = LittleLong(in->firstvertex);
5122 firstelement = LittleLong(in->firstelement);
5123 out->num_firstvertex = meshvertices;
5124 out->num_firsttriangle = meshtriangles;
5125 out->num_firstcollisiontriangle = collisiontriangles;
5128 case Q3FACETYPE_FLAT:
5129 case Q3FACETYPE_MESH:
5130 // no processing necessary, except for lightmap merging
5131 for (j = 0;j < out->num_vertices;j++)
5133 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5134 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5135 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5136 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5137 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5138 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5139 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5140 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5141 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5142 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5143 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5144 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5145 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5146 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5148 for (j = 0;j < out->num_triangles*3;j++)
5149 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5151 case Q3FACETYPE_PATCH:
5152 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5153 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5154 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5155 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5156 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5157 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5158 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5160 xtess = ytess = cxtess = cytess = -1;
5161 for(j = 0; j < patchtesscount; ++j)
5162 if(patchtess[j].surface_id == i)
5164 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5165 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5166 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5167 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5172 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5173 xtess = ytess = cxtess = cytess = 0;
5176 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5177 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5178 finalvertices = finalwidth * finalheight;
5179 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5180 type = Q3FACETYPE_MESH;
5181 // generate geometry
5182 // (note: normals are skipped because they get recalculated)
5183 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5184 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5185 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5186 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5187 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5188 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5190 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);
5192 if (developer_extra.integer)
5194 if (out->num_triangles < finaltriangles)
5195 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);
5197 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);
5199 // q3map does not put in collision brushes for curves... ugh
5200 // build the lower quality collision geometry
5201 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5202 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5203 finalvertices = finalwidth * finalheight;
5204 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5206 // legacy collision geometry implementation
5207 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5208 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5209 out->num_collisionvertices = finalvertices;
5210 out->num_collisiontriangles = finaltriangles;
5211 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5212 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5214 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5215 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5217 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5219 // now optimize the collision mesh by finding triangle bboxes...
5220 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5221 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);
5223 // store collision geometry for BIH collision tree
5224 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5225 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5226 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5227 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5228 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5230 // remove this once the legacy code is removed
5232 int nc = out->num_collisiontriangles;
5234 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5236 if(nc != out->num_collisiontriangles)
5238 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5243 if (developer_extra.integer)
5244 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);
5246 collisionvertices += finalvertices;
5247 collisiontriangles += out->num_collisiontriangles;
5252 meshvertices += out->num_vertices;
5253 meshtriangles += out->num_triangles;
5254 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5255 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)
5257 if (invalidelements)
5259 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);
5260 for (j = 0;j < out->num_triangles * 3;j++)
5262 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5263 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)
5264 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5268 // calculate a bounding box
5269 VectorClear(out->mins);
5270 VectorClear(out->maxs);
5271 if (out->num_vertices)
5273 if (cls.state != ca_dedicated && out->lightmaptexture)
5275 // figure out which part of the merged lightmap this fits into
5276 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5277 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5278 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5279 lightmapindex &= mergewidth * mergeheight - 1;
5280 lightmaptcscale[0] = 1.0f / mergewidth;
5281 lightmaptcscale[1] = 1.0f / mergeheight;
5282 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5283 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5284 // modify the lightmap texcoords to match this region of the merged lightmap
5285 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5287 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5288 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5291 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5292 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5293 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5295 out->mins[0] = min(out->mins[0], v[0]);
5296 out->maxs[0] = max(out->maxs[0], v[0]);
5297 out->mins[1] = min(out->mins[1], v[1]);
5298 out->maxs[1] = max(out->maxs[1], v[1]);
5299 out->mins[2] = min(out->mins[2], v[2]);
5300 out->maxs[2] = max(out->maxs[2], v[2]);
5302 out->mins[0] -= 1.0f;
5303 out->mins[1] -= 1.0f;
5304 out->mins[2] -= 1.0f;
5305 out->maxs[0] += 1.0f;
5306 out->maxs[1] += 1.0f;
5307 out->maxs[2] += 1.0f;
5309 // set lightmap styles for consistency with q1bsp
5310 //out->lightmapinfo->styles[0] = 0;
5311 //out->lightmapinfo->styles[1] = 255;
5312 //out->lightmapinfo->styles[2] = 255;
5313 //out->lightmapinfo->styles[3] = 255;
5318 for (;i < count;i++, out++)
5320 if(out->num_vertices && out->num_triangles)
5322 if(out->num_vertices == 0)
5324 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5325 if(out->num_triangles == 0)
5326 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5328 else if(out->num_triangles == 0)
5329 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)",
5330 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5331 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5332 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5335 // for per pixel lighting
5336 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);
5338 // generate ushort elements array if possible
5339 if (loadmodel->surfmesh.data_element3s)
5340 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5341 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5343 // free the no longer needed vertex data
5344 loadmodel->brushq3.num_vertices = 0;
5345 if (loadmodel->brushq3.data_vertex3f)
5346 Mem_Free(loadmodel->brushq3.data_vertex3f);
5347 loadmodel->brushq3.data_vertex3f = NULL;
5348 loadmodel->brushq3.data_normal3f = NULL;
5349 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5350 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5351 loadmodel->brushq3.data_color4f = NULL;
5352 // free the no longer needed triangle data
5353 loadmodel->brushq3.num_triangles = 0;
5354 if (loadmodel->brushq3.data_element3i)
5355 Mem_Free(loadmodel->brushq3.data_element3i);
5356 loadmodel->brushq3.data_element3i = NULL;
5359 Mem_Free(patchtess);
5362 static void Mod_Q3BSP_LoadModels(lump_t *l)
5366 int i, j, n, c, count;
5368 in = (q3dmodel_t *)(mod_base + l->fileofs);
5369 if (l->filelen % sizeof(*in))
5370 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5371 count = l->filelen / sizeof(*in);
5372 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5374 loadmodel->brushq3.data_models = out;
5375 loadmodel->brushq3.num_models = count;
5377 for (i = 0;i < count;i++, in++, out++)
5379 for (j = 0;j < 3;j++)
5381 out->mins[j] = LittleFloat(in->mins[j]);
5382 out->maxs[j] = LittleFloat(in->maxs[j]);
5384 n = LittleLong(in->firstface);
5385 c = LittleLong(in->numfaces);
5386 if (n < 0 || n + c > loadmodel->num_surfaces)
5387 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5390 n = LittleLong(in->firstbrush);
5391 c = LittleLong(in->numbrushes);
5392 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5393 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5394 out->firstbrush = n;
5395 out->numbrushes = c;
5399 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5405 in = (int *)(mod_base + l->fileofs);
5406 if (l->filelen % sizeof(*in))
5407 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5408 count = l->filelen / sizeof(*in);
5409 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5411 loadmodel->brush.data_leafbrushes = out;
5412 loadmodel->brush.num_leafbrushes = count;
5414 for (i = 0;i < count;i++, in++, out++)
5416 n = LittleLong(*in);
5417 if (n < 0 || n >= loadmodel->brush.num_brushes)
5418 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5423 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5429 in = (int *)(mod_base + l->fileofs);
5430 if (l->filelen % sizeof(*in))
5431 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5432 count = l->filelen / sizeof(*in);
5433 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5435 loadmodel->brush.data_leafsurfaces = out;
5436 loadmodel->brush.num_leafsurfaces = count;
5438 for (i = 0;i < count;i++, in++, out++)
5440 n = LittleLong(*in);
5441 if (n < 0 || n >= loadmodel->num_surfaces)
5442 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5447 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5451 int i, j, n, c, count;
5453 in = (q3dleaf_t *)(mod_base + l->fileofs);
5454 if (l->filelen % sizeof(*in))
5455 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5456 count = l->filelen / sizeof(*in);
5457 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5459 loadmodel->brush.data_leafs = out;
5460 loadmodel->brush.num_leafs = count;
5462 for (i = 0;i < count;i++, in++, out++)
5466 out->clusterindex = LittleLong(in->clusterindex);
5467 out->areaindex = LittleLong(in->areaindex);
5468 for (j = 0;j < 3;j++)
5470 // yes the mins/maxs are ints
5471 out->mins[j] = LittleLong(in->mins[j]) - 1;
5472 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5474 n = LittleLong(in->firstleafface);
5475 c = LittleLong(in->numleaffaces);
5476 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5477 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5478 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5479 out->numleafsurfaces = c;
5480 n = LittleLong(in->firstleafbrush);
5481 c = LittleLong(in->numleafbrushes);
5482 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5483 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5484 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5485 out->numleafbrushes = c;
5489 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5495 in = (q3dnode_t *)(mod_base + l->fileofs);
5496 if (l->filelen % sizeof(*in))
5497 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5498 count = l->filelen / sizeof(*in);
5499 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5501 loadmodel->brush.data_nodes = out;
5502 loadmodel->brush.num_nodes = count;
5504 for (i = 0;i < count;i++, in++, out++)
5507 n = LittleLong(in->planeindex);
5508 if (n < 0 || n >= loadmodel->brush.num_planes)
5509 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5510 out->plane = loadmodel->brush.data_planes + n;
5511 for (j = 0;j < 2;j++)
5513 n = LittleLong(in->childrenindex[j]);
5516 if (n >= loadmodel->brush.num_nodes)
5517 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5518 out->children[j] = loadmodel->brush.data_nodes + n;
5523 if (n >= loadmodel->brush.num_leafs)
5524 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5525 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5528 for (j = 0;j < 3;j++)
5530 // yes the mins/maxs are ints
5531 out->mins[j] = LittleLong(in->mins[j]) - 1;
5532 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5536 // set the parent pointers
5537 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5540 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5543 q3dlightgrid_t *out;
5546 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5547 if (l->filelen % sizeof(*in))
5548 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5549 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5550 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5551 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5552 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5553 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5554 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5555 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5556 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5557 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5558 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5559 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5560 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5561 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5562 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]);
5563 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]);
5565 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5568 if (l->filelen < count * (int)sizeof(*in))
5570 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]);
5571 return; // ignore the grid if we cannot understand it
5573 if (l->filelen != count * (int)sizeof(*in))
5574 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5575 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5576 loadmodel->brushq3.data_lightgrid = out;
5577 loadmodel->brushq3.num_lightgrid = count;
5578 // no swapping or validation necessary
5579 memcpy(out, in, count * (int)sizeof(*out));
5583 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5588 if (l->filelen == 0)
5591 // unvised maps often have cluster indices even without pvs, so check
5592 // leafs to find real number of clusters
5593 loadmodel->brush.num_pvsclusters = 1;
5594 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5595 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5598 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5599 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5600 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5601 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5605 in = (q3dpvs_t *)(mod_base + l->fileofs);
5607 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5609 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5610 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5611 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5612 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5613 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5614 if (l->filelen < totalchains + (int)sizeof(*in))
5615 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);
5617 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5618 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5621 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5623 int i, j, k, index[3];
5624 float transformed[3], blend1, blend2, blend, stylescale;
5625 q3dlightgrid_t *a, *s;
5627 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5628 if (vid.renderpath == RENDERPATH_GL20)
5629 stylescale = 1; // added while render
5631 stylescale = r_refdef.scene.rtlightstylevalue[0];
5633 if (!model->brushq3.num_lightgrid)
5635 ambientcolor[0] = stylescale;
5636 ambientcolor[1] = stylescale;
5637 ambientcolor[2] = stylescale;
5641 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5642 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5643 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5644 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5645 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5646 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5647 index[0] = (int)floor(transformed[0]);
5648 index[1] = (int)floor(transformed[1]);
5649 index[2] = (int)floor(transformed[2]);
5650 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5652 // now lerp the values
5653 VectorClear(diffusenormal);
5654 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5655 for (k = 0;k < 2;k++)
5657 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5658 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5660 for (j = 0;j < 2;j++)
5662 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5663 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5665 for (i = 0;i < 2;i++)
5667 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5668 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5670 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5671 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5672 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5673 // this uses the mod_md3_sin table because the values are
5674 // already in the 0-255 range, the 64+ bias fetches a cosine
5675 // instead of a sine value
5676 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5677 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5678 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5679 //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)));
5684 // normalize the light direction before turning
5685 VectorNormalize(diffusenormal);
5686 //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]);
5689 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5692 double midf, mid[3];
5698 // find the point distances
5699 mplane_t *plane = node->plane;
5700 if (plane->type < 3)
5702 t1 = p1[plane->type] - plane->dist;
5703 t2 = p2[plane->type] - plane->dist;
5707 t1 = DotProduct (plane->normal, p1) - plane->dist;
5708 t2 = DotProduct (plane->normal, p2) - plane->dist;
5715 node = node->children[1];
5724 node = node->children[0];
5730 midf = t1 / (t1 - t2);
5731 VectorLerp(p1, midf, p2, mid);
5733 // recurse both sides, front side first
5734 // return 2 if empty is followed by solid (hit something)
5735 // do not return 2 if both are solid or both empty,
5736 // or if start is solid and end is empty
5737 // as these degenerate cases usually indicate the eye is in solid and
5738 // should see the target point anyway
5739 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
5742 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5747 return ((mleaf_t *)node)->clusterindex < 0;
5750 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5752 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
5755 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
5756 return trace.fraction == 1;
5760 double tracestart[3], traceend[3];
5761 VectorCopy(start, tracestart);
5762 VectorCopy(end, traceend);
5763 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
5767 static void Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const vec3_t point)
5769 const bih_leaf_t *leaf;
5770 const bih_node_t *node;
5771 const colbrushf_t *brush;
5773 while (nodenum >= 0)
5775 node = model->collision_bih.nodes + nodenum;
5776 axis = node->type - BIH_SPLITX;
5777 if (point[axis] <= node->backmax)
5779 if (point[axis] >= node->frontmin)
5780 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, node->front, point);
5781 nodenum = node->back;
5783 else if (point[axis] >= node->frontmin)
5784 nodenum = node->front;
5785 else // no overlap with either child? just return
5788 if (!model->collision_bih.leafs)
5790 leaf = model->collision_bih.leafs + (-1-nodenum);
5794 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5795 Collision_TracePointBrushFloat(trace, point, brush);
5797 case BIH_COLLISIONTRIANGLE:
5798 // collision triangle - skipped because they have no volume
5800 case BIH_RENDERTRIANGLE:
5801 // render triangle - skipped because they have no volume
5806 static void Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const vec3_t start, const vec3_t end, const vec3_t linestart, const vec3_t lineend)
5808 const bih_leaf_t *leaf;
5809 const bih_node_t *node;
5810 const colbrushf_t *brush;
5812 const texture_t *texture;
5823 vec3_t clipped, newstart, newend;
5827 segmentmins[0] = min(start[0], end[0]);
5828 segmentmins[1] = min(start[1], end[1]);
5829 segmentmins[2] = min(start[2], end[2]);
5830 segmentmaxs[0] = max(start[0], end[0]);
5831 segmentmaxs[1] = max(start[1], end[1]);
5832 segmentmaxs[2] = max(start[2], end[2]);
5833 while (nodenum >= 0)
5835 node = model->collision_bih.nodes + nodenum;
5837 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
5840 axis = node->type - BIH_SPLITX;
5842 if (segmentmins[axis] <= node->backmax)
5844 if (segmentmaxs[axis] >= node->frontmin)
5845 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5846 nodenum = node->back;
5848 else if (segmentmaxs[axis] >= node->frontmin)
5849 nodenum = node->front;
5851 return; // trace falls between children
5853 frontdist1 = start[axis] - node->frontmin;
5854 frontdist2 = end[axis] - node->frontmin;
5855 backdist1 = start[axis] - node->backmax;
5856 backdist2 = end[axis] - node->backmax;
5869 if ((sideflags & 3) != 3)
5870 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5871 nodenum = node->back;
5873 else if ((sideflags & 3) != 3)
5874 nodenum = node->front;
5876 return; // trace falls between children
5881 // start end START END
5882 nodenum = node->front;
5885 // START end START END
5887 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5888 VectorLerp(start, frontfrac, end, newstart); start = newstart;
5889 segmentmins[0] = min(start[0], end[0]);
5890 segmentmins[1] = min(start[1], end[1]);
5891 segmentmins[2] = min(start[2], end[2]);
5892 segmentmaxs[0] = max(start[0], end[0]);
5893 segmentmaxs[1] = max(start[1], end[1]);
5894 segmentmaxs[2] = max(start[2], end[2]);
5896 nodenum = node->front;
5900 // start END START END
5901 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5902 VectorLerp(start, frontfrac, end, newend); end = newend;
5903 segmentmins[0] = min(start[0], end[0]);
5904 segmentmins[1] = min(start[1], end[1]);
5905 segmentmins[2] = min(start[2], end[2]);
5906 segmentmaxs[0] = max(start[0], end[0]);
5907 segmentmaxs[1] = max(start[1], end[1]);
5908 segmentmaxs[2] = max(start[2], end[2]);
5910 nodenum = node->front;
5913 // START END START END
5914 return; // line falls in gap between children
5916 // start end start END
5917 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5919 backfrac = backdist1 / (backdist1 - backdist2);
5920 VectorLerp(start, backfrac, end, newend); end = newend;
5921 segmentmins[0] = min(start[0], end[0]);
5922 segmentmins[1] = min(start[1], end[1]);
5923 segmentmins[2] = min(start[2], end[2]);
5924 segmentmaxs[0] = max(start[0], end[0]);
5925 segmentmaxs[1] = max(start[1], end[1]);
5926 segmentmaxs[2] = max(start[2], end[2]);
5928 nodenum = node->back;
5931 // START end start END
5933 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5934 VectorLerp(start, frontfrac, end, clipped);
5935 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
5936 backfrac = backdist1 / (backdist1 - backdist2);
5937 VectorLerp(start, backfrac, end, newend); end = newend;
5938 segmentmins[0] = min(start[0], end[0]);
5939 segmentmins[1] = min(start[1], end[1]);
5940 segmentmins[2] = min(start[2], end[2]);
5941 segmentmaxs[0] = max(start[0], end[0]);
5942 segmentmaxs[1] = max(start[1], end[1]);
5943 segmentmaxs[2] = max(start[2], end[2]);
5945 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5947 nodenum = node->back;
5950 // start END start END
5952 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5953 VectorLerp(start, frontfrac, end, clipped);
5954 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
5955 backfrac = backdist1 / (backdist1 - backdist2);
5956 VectorLerp(start, backfrac, end, newend); end = newend;
5957 segmentmins[0] = min(start[0], end[0]);
5958 segmentmins[1] = min(start[1], end[1]);
5959 segmentmins[2] = min(start[2], end[2]);
5960 segmentmaxs[0] = max(start[0], end[0]);
5961 segmentmaxs[1] = max(start[1], end[1]);
5962 segmentmaxs[2] = max(start[2], end[2]);
5964 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5966 nodenum = node->back;
5969 // START END start END
5971 backfrac = backdist1 / (backdist1 - backdist2);
5972 VectorLerp(start, backfrac, end, newend); end = newend;
5973 segmentmins[0] = min(start[0], end[0]);
5974 segmentmins[1] = min(start[1], end[1]);
5975 segmentmins[2] = min(start[2], end[2]);
5976 segmentmaxs[0] = max(start[0], end[0]);
5977 segmentmaxs[1] = max(start[1], end[1]);
5978 segmentmaxs[2] = max(start[2], end[2]);
5980 nodenum = node->back;
5983 // start end START end
5984 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5986 backfrac = backdist1 / (backdist1 - backdist2);
5987 VectorLerp(start, backfrac, end, newstart); start = newstart;
5988 segmentmins[0] = min(start[0], end[0]);
5989 segmentmins[1] = min(start[1], end[1]);
5990 segmentmins[2] = min(start[2], end[2]);
5991 segmentmaxs[0] = max(start[0], end[0]);
5992 segmentmaxs[1] = max(start[1], end[1]);
5993 segmentmaxs[2] = max(start[2], end[2]);
5995 nodenum = node->back;
5998 // START end START end
6000 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6001 VectorLerp(start, frontfrac, end, clipped);
6002 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
6003 backfrac = backdist1 / (backdist1 - backdist2);
6004 VectorLerp(start, backfrac, end, newstart); start = newstart;
6005 segmentmins[0] = min(start[0], end[0]);
6006 segmentmins[1] = min(start[1], end[1]);
6007 segmentmins[2] = min(start[2], end[2]);
6008 segmentmaxs[0] = max(start[0], end[0]);
6009 segmentmaxs[1] = max(start[1], end[1]);
6010 segmentmaxs[2] = max(start[2], end[2]);
6012 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6014 nodenum = node->back;
6017 // start END START end
6019 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6020 VectorLerp(start, frontfrac, end, clipped);
6021 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
6022 backfrac = backdist1 / (backdist1 - backdist2);
6023 VectorLerp(start, backfrac, end, newstart); start = newstart;
6024 segmentmins[0] = min(start[0], end[0]);
6025 segmentmins[1] = min(start[1], end[1]);
6026 segmentmins[2] = min(start[2], end[2]);
6027 segmentmaxs[0] = max(start[0], end[0]);
6028 segmentmaxs[1] = max(start[1], end[1]);
6029 segmentmaxs[2] = max(start[2], end[2]);
6031 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6033 nodenum = node->back;
6036 // START END START end
6038 backfrac = backdist1 / (backdist1 - backdist2);
6039 VectorLerp(start, backfrac, end, newstart); start = newstart;
6040 segmentmins[0] = min(start[0], end[0]);
6041 segmentmins[1] = min(start[1], end[1]);
6042 segmentmins[2] = min(start[2], end[2]);
6043 segmentmaxs[0] = max(start[0], end[0]);
6044 segmentmaxs[1] = max(start[1], end[1]);
6045 segmentmaxs[2] = max(start[2], end[2]);
6047 nodenum = node->back;
6050 // start end start end
6051 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6052 nodenum = node->back;
6055 // START end start end
6057 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6058 VectorLerp(start, frontfrac, end, clipped);
6059 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
6061 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6063 nodenum = node->back;
6066 // start END start end
6068 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6069 VectorLerp(start, frontfrac, end, clipped);
6070 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
6072 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6074 nodenum = node->back;
6077 // START END start end
6078 nodenum = node->back;
6084 if (!model->collision_bih.leafs)
6086 leaf = model->collision_bih.leafs + (-1-nodenum);
6088 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6094 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6095 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6097 case BIH_COLLISIONTRIANGLE:
6098 if (!mod_q3bsp_curves_collisions.integer)
6100 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6101 texture = model->data_textures + leaf->textureindex;
6102 Collision_TraceLineTriangleFloat(trace, linestart, lineend, 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);
6104 case BIH_RENDERTRIANGLE:
6105 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6106 texture = model->data_textures + leaf->textureindex;
6107 Collision_TraceLineTriangleFloat(trace, linestart, lineend, 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);
6112 static void Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, const vec3_t segmentmins, const vec3_t segmentmaxs)
6114 const bih_leaf_t *leaf;
6115 const bih_node_t *node;
6116 const colbrushf_t *brush;
6118 const texture_t *texture;
6120 while (nodenum >= 0)
6122 node = model->collision_bih.nodes + nodenum;
6123 axis = node->type - BIH_SPLITX;
6125 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6129 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6130 nodenum = node->back;
6133 if (segmentmins[axis] <= node->backmax)
6135 if (segmentmaxs[axis] >= node->frontmin)
6136 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6137 nodenum = node->back;
6139 else if (segmentmaxs[axis] >= node->frontmin)
6140 nodenum = node->front;
6142 return; // trace falls between children
6144 if (!model->collision_bih.leafs)
6146 leaf = model->collision_bih.leafs + (-1-nodenum);
6148 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6154 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6155 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6157 case BIH_COLLISIONTRIANGLE:
6158 if (!mod_q3bsp_curves_collisions.integer)
6160 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6161 texture = model->data_textures + leaf->textureindex;
6162 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);
6164 case BIH_RENDERTRIANGLE:
6165 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6166 texture = model->data_textures + leaf->textureindex;
6167 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);
6172 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 memset(trace, 0, sizeof(*trace));
6175 trace->fraction = 1;
6176 trace->realfraction = 1;
6177 trace->hitsupercontentsmask = hitsupercontentsmask;
6178 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6181 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)
6183 if (VectorCompare(start, end))
6185 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6189 memset(trace, 0, sizeof(*trace));
6190 trace->fraction = 1;
6191 trace->realfraction = 1;
6192 trace->hitsupercontentsmask = hitsupercontentsmask;
6193 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6196 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)
6198 float segmentmins[3], segmentmaxs[3];
6199 colboxbrushf_t thisbrush_start, thisbrush_end;
6200 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6202 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6204 vec3_t shiftstart, shiftend;
6205 VectorAdd(start, boxmins, shiftstart);
6206 VectorAdd(end, boxmins, shiftend);
6207 if (VectorCompare(start, end))
6208 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6210 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6214 // box trace, performed as brush trace
6215 memset(trace, 0, sizeof(*trace));
6216 trace->fraction = 1;
6217 trace->realfraction = 1;
6218 trace->hitsupercontentsmask = hitsupercontentsmask;
6219 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6220 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6221 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6222 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6223 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6224 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6225 VectorAdd(start, boxmins, boxstartmins);
6226 VectorAdd(start, boxmaxs, boxstartmaxs);
6227 VectorAdd(end, boxmins, boxendmins);
6228 VectorAdd(end, boxmaxs, boxendmaxs);
6229 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6230 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6231 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6234 void Mod_CollisionBIH_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *start, colbrushf_t *end, int hitsupercontentsmask)
6236 float segmentmins[3], segmentmaxs[3];
6238 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6240 if (VectorCompare(start->mins, end->mins))
6241 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6243 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6247 // box trace, performed as brush trace
6248 memset(trace, 0, sizeof(*trace));
6249 trace->fraction = 1;
6250 trace->realfraction = 1;
6251 trace->hitsupercontentsmask = hitsupercontentsmask;
6252 segmentmins[0] = min(start->mins[0], end->mins[0]);
6253 segmentmins[1] = min(start->mins[1], end->mins[1]);
6254 segmentmins[2] = min(start->mins[2], end->mins[2]);
6255 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6256 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6257 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6258 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, segmentmins, segmentmaxs);
6261 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6264 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6265 return trace.startsupercontents;
6268 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)
6271 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6273 int hitsupercontents;
6274 VectorSet(end, start[0], start[1], model->normalmins[2]);
6276 memset(trace, 0, sizeof(*trace));
6277 trace->fraction = 1;
6278 trace->realfraction = 1;
6279 trace->hitsupercontentsmask = hitsupercontentsmask;
6281 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6282 hitsupercontents = trace->hitsupercontents;
6283 memset(trace, 0, sizeof(*trace));
6284 trace->fraction = 1;
6285 trace->realfraction = 1;
6286 trace->hitsupercontentsmask = hitsupercontentsmask;
6287 trace->startsupercontents = hitsupercontents;
6291 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6294 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6297 VectorSet(end, start[0], start[1], model->normalmins[2]);
6298 memset(&trace, 0, sizeof(trace));
6300 trace.realfraction = 1;
6301 trace.hitsupercontentsmask = 0;
6302 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(&trace, model, model->collision_bih.rootnode, start, end, start, end);
6303 return trace.hitsupercontents;
6309 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6314 // find which leaf the point is in
6316 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6317 // point trace the brushes
6318 leaf = (mleaf_t *)node;
6319 for (i = 0;i < leaf->numleafbrushes;i++)
6321 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6322 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6324 brush->markframe = markframe;
6325 Collision_TracePointBrushFloat(trace, point, brush);
6328 // can't do point traces on curves (they have no thickness)
6331 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)
6333 int i, startside, endside;
6334 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6336 msurface_t *surface;
6339 // walk the tree until we hit a leaf, recursing for any split cases
6343 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6345 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6346 node = node->children[1];
6348 // abort if this part of the bsp tree can not be hit by this trace
6349 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6351 plane = node->plane;
6352 // axial planes are much more common than non-axial, so an optimized
6353 // axial case pays off here
6354 if (plane->type < 3)
6356 dist1 = start[plane->type] - plane->dist;
6357 dist2 = end[plane->type] - plane->dist;
6361 dist1 = DotProduct(start, plane->normal) - plane->dist;
6362 dist2 = DotProduct(end, plane->normal) - plane->dist;
6364 startside = dist1 < 0;
6365 endside = dist2 < 0;
6366 if (startside == endside)
6368 // most of the time the line fragment is on one side of the plane
6369 node = node->children[startside];
6373 // line crosses node plane, split the line
6374 dist1 = PlaneDiff(linestart, plane);
6375 dist2 = PlaneDiff(lineend, plane);
6376 midfrac = dist1 / (dist1 - dist2);
6377 VectorLerp(linestart, midfrac, lineend, mid);
6378 // take the near side first
6379 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6380 // if we found an impact on the front side, don't waste time
6381 // exploring the far side
6382 if (midfrac <= trace->realfraction)
6383 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6388 // abort if this part of the bsp tree can not be hit by this trace
6389 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6392 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6393 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6394 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6395 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6396 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6397 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6398 // line trace the brushes
6399 leaf = (mleaf_t *)node;
6401 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6404 for (i = 0;i < leaf->numleafbrushes;i++)
6406 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6407 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6409 brush->markframe = markframe;
6410 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6413 // can't do point traces on curves (they have no thickness)
6414 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6416 // line trace the curves
6417 for (i = 0;i < leaf->numleafsurfaces;i++)
6419 surface = model->data_surfaces + leaf->firstleafsurface[i];
6420 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6422 surface->deprecatedq3collisionmarkframe = markframe;
6423 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);
6429 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)
6435 msurface_t *surface;
6437 float nodesegmentmins[3], nodesegmentmaxs[3];
6438 // walk the tree until we hit a leaf, recursing for any split cases
6442 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6444 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6445 node = node->children[1];
6447 // abort if this part of the bsp tree can not be hit by this trace
6448 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6450 plane = node->plane;
6451 // axial planes are much more common than non-axial, so an optimized
6452 // axial case pays off here
6453 if (plane->type < 3)
6455 // this is an axial plane, compare bounding box directly to it and
6456 // recurse sides accordingly
6457 // recurse down node sides
6458 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6459 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6460 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6461 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6465 // this is a non-axial plane, so check if the start and end boxes
6466 // are both on one side of the plane to handle 'diagonal' cases
6467 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6471 // segment crosses plane
6472 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6475 // if sides == 0 then the trace itself is bogus (Not A Number values),
6476 // in this case we simply pretend the trace hit nothing
6478 return; // ERROR: NAN bounding box!
6479 // take whichever side the segment box is on
6480 node = node->children[sides - 1];
6483 // abort if this part of the bsp tree can not be hit by this trace
6484 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6486 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6487 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6488 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6489 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6490 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6491 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6493 leaf = (mleaf_t *)node;
6495 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6498 for (i = 0;i < leaf->numleafbrushes;i++)
6500 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6501 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6503 brush->markframe = markframe;
6504 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6507 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6509 for (i = 0;i < leaf->numleafsurfaces;i++)
6511 surface = model->data_surfaces + leaf->firstleafsurface[i];
6512 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6514 surface->deprecatedq3collisionmarkframe = markframe;
6515 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);
6522 static int markframe = 0;
6524 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)
6528 memset(trace, 0, sizeof(*trace));
6529 trace->fraction = 1;
6530 trace->realfraction = 1;
6531 trace->hitsupercontentsmask = hitsupercontentsmask;
6532 if (mod_collision_bih.integer)
6533 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6534 else if (model->brush.submodel)
6536 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6537 if (brush->colbrushf)
6538 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6541 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6544 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)
6547 float segmentmins[3], segmentmaxs[3];
6548 msurface_t *surface;
6551 if (VectorCompare(start, end))
6553 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6557 memset(trace, 0, sizeof(*trace));
6558 trace->fraction = 1;
6559 trace->realfraction = 1;
6560 trace->hitsupercontentsmask = hitsupercontentsmask;
6561 segmentmins[0] = min(start[0], end[0]) - 1;
6562 segmentmins[1] = min(start[1], end[1]) - 1;
6563 segmentmins[2] = min(start[2], end[2]) - 1;
6564 segmentmaxs[0] = max(start[0], end[0]) + 1;
6565 segmentmaxs[1] = max(start[1], end[1]) + 1;
6566 segmentmaxs[2] = max(start[2], end[2]) + 1;
6567 if (mod_collision_bih.integer)
6568 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6569 else if (model->brush.submodel)
6571 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6572 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6573 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6574 if (mod_q3bsp_curves_collisions.integer)
6575 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6576 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6577 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);
6580 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6583 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)
6586 float segmentmins[3], segmentmaxs[3];
6587 msurface_t *surface;
6589 colboxbrushf_t thisbrush_start, thisbrush_end;
6590 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6592 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6594 vec3_t shiftstart, shiftend;
6595 VectorAdd(start, boxmins, shiftstart);
6596 VectorAdd(end, boxmins, shiftend);
6597 if (VectorCompare(start, end))
6598 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6600 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6604 // box trace, performed as brush trace
6605 memset(trace, 0, sizeof(*trace));
6606 trace->fraction = 1;
6607 trace->realfraction = 1;
6608 trace->hitsupercontentsmask = hitsupercontentsmask;
6609 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6610 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6611 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6612 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6613 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6614 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6615 VectorAdd(start, boxmins, boxstartmins);
6616 VectorAdd(start, boxmaxs, boxstartmaxs);
6617 VectorAdd(end, boxmins, boxendmins);
6618 VectorAdd(end, boxmaxs, boxendmaxs);
6619 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6620 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6621 if (mod_collision_bih.integer)
6622 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6623 else if (model->brush.submodel)
6625 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6626 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6627 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, brush->colbrushf, brush->colbrushf);
6628 if (mod_q3bsp_curves_collisions.integer)
6629 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6630 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6631 Collision_TraceBrushTriangleMeshFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, 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);
6634 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, &thisbrush_start.brush, &thisbrush_end.brush, ++markframe, segmentmins, segmentmaxs);
6637 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)
6639 float segmentmins[3], segmentmaxs[3];
6641 msurface_t *surface;
6644 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6646 if (VectorCompare(start->mins, end->mins))
6647 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6649 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6653 // box trace, performed as brush trace
6654 memset(trace, 0, sizeof(*trace));
6655 trace->fraction = 1;
6656 trace->realfraction = 1;
6657 trace->hitsupercontentsmask = hitsupercontentsmask;
6658 segmentmins[0] = min(start->mins[0], end->mins[0]);
6659 segmentmins[1] = min(start->mins[1], end->mins[1]);
6660 segmentmins[2] = min(start->mins[2], end->mins[2]);
6661 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6662 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6663 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6664 if (mod_collision_bih.integer)
6665 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, segmentmins, segmentmaxs);
6666 else if (model->brush.submodel)
6668 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6669 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6670 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6671 if (mod_q3bsp_curves_collisions.integer)
6672 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6673 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6674 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);
6677 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6680 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6683 int supercontents = 0;
6685 if (mod_collision_bih.integer)
6688 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6689 supercontents = trace.startsupercontents;
6691 // test if the point is inside each brush
6692 else if (model->brush.submodel)
6694 // submodels are effectively one leaf
6695 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6696 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6697 supercontents |= brush->colbrushf->supercontents;
6701 mnode_t *node = model->brush.data_nodes;
6703 // find which leaf the point is in
6705 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6706 leaf = (mleaf_t *)node;
6707 // now check the brushes in the leaf
6708 for (i = 0;i < leaf->numleafbrushes;i++)
6710 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6711 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6712 supercontents |= brush->colbrushf->supercontents;
6715 return supercontents;
6718 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6726 int nummodelbrushes = model->nummodelbrushes;
6727 int nummodelsurfaces = model->nummodelsurfaces;
6729 const int *collisionelement3i;
6730 const float *collisionvertex3f;
6731 const int *renderelement3i;
6732 const float *rendervertex3f;
6733 bih_leaf_t *bihleafs;
6734 bih_node_t *bihnodes;
6736 int *temp_leafsortscratch;
6737 const msurface_t *surface;
6738 const q3mbrush_t *brush;
6740 // find out how many BIH leaf nodes we need
6742 if (userendersurfaces)
6744 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6745 bihnumleafs += surface->num_triangles;
6749 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6750 if (brush->colbrushf)
6752 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6754 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6755 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
6757 bihnumleafs += surface->num_collisiontriangles;
6764 // allocate the memory for the BIH leaf nodes
6765 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6767 // now populate the BIH leaf nodes
6770 // add render surfaces
6771 renderelement3i = model->surfmesh.data_element3i;
6772 rendervertex3f = model->surfmesh.data_vertex3f;
6773 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6775 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6777 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6779 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6780 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6781 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6782 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6783 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6784 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6785 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6786 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6787 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6788 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6793 if (!userendersurfaces)
6795 // add collision brushes
6796 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6798 if (!brush->colbrushf)
6800 bihleafs[bihleafindex].type = BIH_BRUSH;
6801 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6802 bihleafs[bihleafindex].surfaceindex = -1;
6803 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6804 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6805 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6809 // add collision surfaces
6810 collisionelement3i = model->brush.data_collisionelement3i;
6811 collisionvertex3f = model->brush.data_collisionvertex3f;
6812 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6814 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6816 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
6817 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6818 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6819 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6820 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6821 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6822 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6823 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6824 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6825 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6831 // allocate buffers for the produced and temporary data
6832 bihmaxnodes = bihnumleafs - 1;
6833 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6834 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6835 temp_leafsortscratch = temp_leafsort + bihnumleafs;
6838 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6840 // we're done with the temporary data
6841 Mem_Free(temp_leafsort);
6843 // resize the BIH nodes array if it over-allocated
6844 if (out->maxnodes > out->numnodes)
6846 out->maxnodes = out->numnodes;
6847 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
6853 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6855 int supercontents = 0;
6856 if (nativecontents & CONTENTSQ3_SOLID)
6857 supercontents |= SUPERCONTENTS_SOLID;
6858 if (nativecontents & CONTENTSQ3_WATER)
6859 supercontents |= SUPERCONTENTS_WATER;
6860 if (nativecontents & CONTENTSQ3_SLIME)
6861 supercontents |= SUPERCONTENTS_SLIME;
6862 if (nativecontents & CONTENTSQ3_LAVA)
6863 supercontents |= SUPERCONTENTS_LAVA;
6864 if (nativecontents & CONTENTSQ3_BODY)
6865 supercontents |= SUPERCONTENTS_BODY;
6866 if (nativecontents & CONTENTSQ3_CORPSE)
6867 supercontents |= SUPERCONTENTS_CORPSE;
6868 if (nativecontents & CONTENTSQ3_NODROP)
6869 supercontents |= SUPERCONTENTS_NODROP;
6870 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6871 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6872 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6873 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6874 if (nativecontents & CONTENTSQ3_DONOTENTER)
6875 supercontents |= SUPERCONTENTS_DONOTENTER;
6876 if (nativecontents & CONTENTSQ3_BOTCLIP)
6877 supercontents |= SUPERCONTENTS_BOTCLIP;
6878 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6879 supercontents |= SUPERCONTENTS_OPAQUE;
6880 return supercontents;
6883 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6885 int nativecontents = 0;
6886 if (supercontents & SUPERCONTENTS_SOLID)
6887 nativecontents |= CONTENTSQ3_SOLID;
6888 if (supercontents & SUPERCONTENTS_WATER)
6889 nativecontents |= CONTENTSQ3_WATER;
6890 if (supercontents & SUPERCONTENTS_SLIME)
6891 nativecontents |= CONTENTSQ3_SLIME;
6892 if (supercontents & SUPERCONTENTS_LAVA)
6893 nativecontents |= CONTENTSQ3_LAVA;
6894 if (supercontents & SUPERCONTENTS_BODY)
6895 nativecontents |= CONTENTSQ3_BODY;
6896 if (supercontents & SUPERCONTENTS_CORPSE)
6897 nativecontents |= CONTENTSQ3_CORPSE;
6898 if (supercontents & SUPERCONTENTS_NODROP)
6899 nativecontents |= CONTENTSQ3_NODROP;
6900 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6901 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6902 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6903 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6904 if (supercontents & SUPERCONTENTS_DONOTENTER)
6905 nativecontents |= CONTENTSQ3_DONOTENTER;
6906 if (supercontents & SUPERCONTENTS_BOTCLIP)
6907 nativecontents |= CONTENTSQ3_BOTCLIP;
6908 if (!(supercontents & SUPERCONTENTS_OPAQUE))
6909 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6910 return nativecontents;
6913 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6918 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6919 node = node->children[1];
6921 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6922 if (loadmodel->brush.num_leafs < numleafs)
6923 loadmodel->brush.num_leafs = numleafs;
6926 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6929 q3dheader_t *header;
6930 float corner[3], yawradius, modelradius;
6932 mod->modeldatatypestring = "Q3BSP";
6934 mod->type = mod_brushq3;
6935 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6938 header = (q3dheader_t *)buffer;
6939 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6940 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6942 i = LittleLong(header->version);
6943 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
6944 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
6946 mod->soundfromcenter = true;
6947 mod->TraceBox = Mod_Q3BSP_TraceBox;
6948 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
6949 mod->TraceLine = Mod_Q3BSP_TraceLine;
6950 mod->TracePoint = Mod_Q3BSP_TracePoint;
6951 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
6952 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
6953 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
6954 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
6955 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
6956 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
6957 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
6958 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
6959 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
6960 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
6961 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
6962 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
6963 mod->brush.AmbientSoundLevelsForPoint = NULL;
6964 mod->brush.RoundUpToHullSize = NULL;
6965 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
6966 mod->Draw = R_Q1BSP_Draw;
6967 mod->DrawDepth = R_Q1BSP_DrawDepth;
6968 mod->DrawDebug = R_Q1BSP_DrawDebug;
6969 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
6970 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
6971 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
6972 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
6973 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
6974 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
6975 mod->DrawLight = R_Q1BSP_DrawLight;
6977 mod_base = (unsigned char *)header;
6979 // swap all the lumps
6980 header->ident = LittleLong(header->ident);
6981 header->version = LittleLong(header->version);
6982 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
6983 for (i = 0;i < lumps;i++)
6985 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
6986 if((char *) bufferend < (char *) buffer + j)
6987 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
6988 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
6989 if((char *) bufferend < (char *) buffer + j)
6990 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
6993 * NO, do NOT clear them!
6994 * they contain actual data referenced by other stuff.
6995 * Instead, before using the advertisements lump, check header->versio
6997 * Sorry, but otherwise it breaks memory of the first lump.
6998 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7000 header->lumps[i].fileofs = 0;
7001 header->lumps[i].filelen = 0;
7005 mod->brush.qw_md4sum = 0;
7006 mod->brush.qw_md4sum2 = 0;
7007 for (i = 0;i < lumps;i++)
7009 if (i == Q3LUMP_ENTITIES)
7011 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7012 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7014 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7016 // all this checksumming can take a while, so let's send keepalives here too
7017 CL_KeepaliveMessage(false);
7020 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7021 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7022 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7023 if (header->version == Q3BSPVERSION_IG)
7024 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7026 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7027 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7028 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7029 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7030 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7031 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7032 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7033 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7034 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7035 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7036 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7037 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7038 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7039 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7040 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7042 // the MakePortals code works fine on the q3bsp data as well
7043 Mod_Q1BSP_MakePortals();
7045 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7046 loadmodel->brush.supportwateralpha = true;
7048 // make a single combined shadow mesh to allow optimized shadow volume creation
7049 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7051 loadmodel->brush.num_leafs = 0;
7052 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7054 if (loadmodel->brush.numsubmodels)
7055 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7058 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7063 // duplicate the basic information
7064 dpsnprintf(name, sizeof(name), "*%i", i);
7065 mod = Mod_FindName(name, loadmodel->name);
7066 // copy the base model to this one
7068 // rename the clone back to its proper name
7069 strlcpy(mod->name, name, sizeof(mod->name));
7070 mod->brush.parentmodel = loadmodel;
7071 // textures and memory belong to the main model
7072 mod->texturepool = NULL;
7073 mod->mempool = NULL;
7074 mod->brush.GetPVS = NULL;
7075 mod->brush.FatPVS = NULL;
7076 mod->brush.BoxTouchingPVS = NULL;
7077 mod->brush.BoxTouchingLeafPVS = NULL;
7078 mod->brush.BoxTouchingVisibleLeafs = NULL;
7079 mod->brush.FindBoxClusters = NULL;
7080 mod->brush.LightPoint = NULL;
7081 mod->brush.AmbientSoundLevelsForPoint = NULL;
7083 mod->brush.submodel = i;
7084 if (loadmodel->brush.submodels)
7085 loadmodel->brush.submodels[i] = mod;
7087 // make the model surface list (used by shadowing/lighting)
7088 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7089 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7090 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7091 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7092 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7093 Mod_MakeSortedSurfaces(mod);
7095 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7096 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7097 // enlarge the bounding box to enclose all geometry of this model,
7098 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7099 // which can in turn mess up the farclip (as well as culling when
7100 // outside the level - an unimportant concern)
7102 //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]);
7103 for (j = 0;j < mod->nummodelsurfaces;j++)
7105 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7106 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7108 if (!surface->num_vertices)
7110 for (k = 0;k < surface->num_vertices;k++, v += 3)
7112 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7113 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7114 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7115 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7116 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7117 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7120 //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]);
7121 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7122 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7123 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7124 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7125 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7126 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7127 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7128 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7129 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7130 mod->yawmins[2] = mod->normalmins[2];
7131 mod->yawmaxs[2] = mod->normalmaxs[2];
7132 mod->radius = modelradius;
7133 mod->radius2 = modelradius * modelradius;
7135 // this gets altered below if sky or water is used
7136 mod->DrawSky = NULL;
7137 mod->DrawAddWaterPlanes = NULL;
7139 for (j = 0;j < mod->nummodelsurfaces;j++)
7140 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7142 if (j < mod->nummodelsurfaces)
7143 mod->DrawSky = R_Q1BSP_DrawSky;
7145 for (j = 0;j < mod->nummodelsurfaces;j++)
7146 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7148 if (j < mod->nummodelsurfaces)
7149 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7151 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7152 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7154 // generate VBOs and other shared data before cloning submodels
7159 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);
7162 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7164 int i = LittleLong(((int *)buffer)[1]);
7165 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7166 Mod_Q3BSP_Load(mod,buffer, bufferend);
7167 else if (i == Q2BSPVERSION)
7168 Mod_Q2BSP_Load(mod,buffer, bufferend);
7170 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7173 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7175 Host_Error("Mod_MAP_Load: not yet implemented");
7181 typedef struct objvertex_s
7192 static unsigned char nobsp_pvs[1] = {1};
7194 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7196 const char *textbase = (char *)buffer, *text = textbase;
7200 char materialname[MAX_QPATH];
7201 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7202 int index1, index2, index3;
7203 objvertex_t vfirst, vprev, vcurrent;
7206 int numtriangles = 0;
7207 int maxtriangles = 0;
7208 objvertex_t *vertices = NULL;
7210 int maxtextures = 0, numtextures = 0, textureindex = 0;
7211 int maxv = 0, numv = 1;
7212 int maxvt = 0, numvt = 1;
7213 int maxvn = 0, numvn = 1;
7214 char *texturenames = NULL;
7215 float dist, modelradius, modelyawradius, yawradius;
7222 objvertex_t *thisvertex = NULL;
7223 int vertexhashindex;
7224 int *vertexhashtable = NULL;
7225 objvertex_t *vertexhashdata = NULL;
7226 objvertex_t *vdata = NULL;
7227 int vertexhashsize = 0;
7228 int vertexhashcount = 0;
7229 skinfile_t *skinfiles = NULL;
7230 unsigned char *data = NULL;
7231 int *submodelfirstsurface;
7232 msurface_t *surface;
7233 msurface_t *tempsurfaces;
7235 memset(&vfirst, 0, sizeof(vfirst));
7236 memset(&vprev, 0, sizeof(vprev));
7237 memset(&vcurrent, 0, sizeof(vcurrent));
7239 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7241 loadmodel->modeldatatypestring = "OBJ";
7243 loadmodel->type = mod_obj;
7244 loadmodel->soundfromcenter = true;
7245 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7246 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7247 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7248 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7249 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7250 loadmodel->brush.TraceLineOfSight = NULL;
7251 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7252 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7253 loadmodel->brush.GetPVS = NULL;
7254 loadmodel->brush.FatPVS = NULL;
7255 loadmodel->brush.BoxTouchingPVS = NULL;
7256 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7257 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7258 loadmodel->brush.FindBoxClusters = NULL;
7259 loadmodel->brush.LightPoint = NULL;
7260 loadmodel->brush.FindNonSolidLocation = NULL;
7261 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7262 loadmodel->brush.RoundUpToHullSize = NULL;
7263 loadmodel->brush.PointInLeaf = NULL;
7264 loadmodel->Draw = R_Q1BSP_Draw;
7265 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7266 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7267 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7268 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7269 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7270 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7271 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7272 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7273 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7275 skinfiles = Mod_LoadSkinFiles();
7276 if (loadmodel->numskins < 1)
7277 loadmodel->numskins = 1;
7279 // make skinscenes for the skins (no groups)
7280 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7281 for (i = 0;i < loadmodel->numskins;i++)
7283 loadmodel->skinscenes[i].firstframe = i;
7284 loadmodel->skinscenes[i].framecount = 1;
7285 loadmodel->skinscenes[i].loop = true;
7286 loadmodel->skinscenes[i].framerate = 10;
7292 // parse the OBJ text now
7295 static char emptyarg[1] = "";
7300 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7301 line[linelen] = text[linelen];
7303 for (argc = 0;argc < 4;argc++)
7304 argv[argc] = emptyarg;
7307 while (*s == ' ' || *s == '\t')
7317 while (*s == ' ' || *s == '\t')
7327 if (argv[0][0] == '#')
7329 if (!strcmp(argv[0], "v"))
7333 maxv = max(maxv * 2, 1024);
7334 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7336 v[numv*3+0] = atof(argv[1]);
7337 v[numv*3+2] = atof(argv[2]);
7338 v[numv*3+1] = atof(argv[3]);
7341 else if (!strcmp(argv[0], "vt"))
7345 maxvt = max(maxvt * 2, 1024);
7346 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7348 vt[numvt*2+0] = atof(argv[1]);
7349 vt[numvt*2+1] = 1-atof(argv[2]);
7352 else if (!strcmp(argv[0], "vn"))
7356 maxvn = max(maxvn * 2, 1024);
7357 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7359 vn[numvn*3+0] = atof(argv[1]);
7360 vn[numvn*3+2] = atof(argv[2]);
7361 vn[numvn*3+1] = atof(argv[3]);
7364 else if (!strcmp(argv[0], "f"))
7368 if (maxtextures <= numtextures)
7370 maxtextures = max(maxtextures * 2, 256);
7371 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7373 textureindex = numtextures++;
7374 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7376 for (j = 1;j < argc;j++)
7378 index1 = atoi(argv[j]);
7379 while(argv[j][0] && argv[j][0] != '/')
7383 index2 = atoi(argv[j]);
7384 while(argv[j][0] && argv[j][0] != '/')
7388 index3 = atoi(argv[j]);
7389 // negative refers to a recent vertex
7390 // zero means not specified
7391 // positive means an absolute vertex index
7393 index1 = numv - index1;
7395 index2 = numvt - index2;
7397 index3 = numvn - index3;
7398 vcurrent.nextindex = -1;
7399 vcurrent.textureindex = textureindex;
7400 vcurrent.submodelindex = submodelindex;
7401 if (v && index1 >= 0 && index1 < numv)
7402 VectorCopy(v + 3*index1, vcurrent.v);
7403 if (vt && index2 >= 0 && index2 < numvt)
7404 Vector2Copy(vt + 2*index2, vcurrent.vt);
7405 if (vn && index3 >= 0 && index3 < numvn)
7406 VectorCopy(vn + 3*index3, vcurrent.vn);
7407 if (numtriangles == 0)
7409 VectorCopy(vcurrent.v, mins);
7410 VectorCopy(vcurrent.v, maxs);
7414 mins[0] = min(mins[0], vcurrent.v[0]);
7415 mins[1] = min(mins[1], vcurrent.v[1]);
7416 mins[2] = min(mins[2], vcurrent.v[2]);
7417 maxs[0] = max(maxs[0], vcurrent.v[0]);
7418 maxs[1] = max(maxs[1], vcurrent.v[1]);
7419 maxs[2] = max(maxs[2], vcurrent.v[2]);
7425 if (maxtriangles <= numtriangles)
7427 maxtriangles = max(maxtriangles * 2, 32768);
7428 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7430 vertices[numtriangles*3+0] = vfirst;
7431 vertices[numtriangles*3+1] = vprev;
7432 vertices[numtriangles*3+2] = vcurrent;
7438 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7440 submodelindex = atof(argv[1]);
7441 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7443 else if (!strcmp(argv[0], "usemtl"))
7445 for (i = 0;i < numtextures;i++)
7446 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7448 if (i < numtextures)
7452 if (maxtextures <= numtextures)
7454 maxtextures = max(maxtextures * 2, 256);
7455 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7457 textureindex = numtextures++;
7458 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7463 // now that we have the OBJ data loaded as-is, we can convert it
7465 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7466 VectorCopy(mins, loadmodel->normalmins);
7467 VectorCopy(maxs, loadmodel->normalmaxs);
7468 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7469 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7470 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7471 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7472 modelradius = modelyawradius + modelradius * modelradius;
7473 modelyawradius = sqrt(modelyawradius);
7474 modelradius = sqrt(modelradius);
7475 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7476 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7477 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7478 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7479 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7480 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7481 loadmodel->radius = modelradius;
7482 loadmodel->radius2 = modelradius * modelradius;
7484 // allocate storage for triangles
7485 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7486 // allocate vertex hash structures to build an optimal vertex subset
7487 vertexhashsize = numtriangles*2;
7488 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7489 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7490 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7491 vertexhashcount = 0;
7493 // gather surface stats for assigning vertex/triangle ranges
7497 loadmodel->num_surfaces = 0;
7498 // allocate storage for the worst case number of surfaces, later we resize
7499 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7500 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7501 surface = tempsurfaces;
7502 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7504 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7505 for (textureindex = 0;textureindex < numtextures;textureindex++)
7507 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7509 thisvertex = vertices + vertexindex;
7510 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7513 // skip the surface creation if there are no triangles for it
7514 if (vertexindex == numtriangles*3)
7516 // create a surface for these vertices
7517 surfacevertices = 0;
7518 surfaceelements = 0;
7519 // we hack in a texture index in the surface to be fixed up later...
7520 surface->texture = (texture_t *)((size_t)textureindex);
7521 // calculate bounds as we go
7522 VectorCopy(thisvertex->v, surface->mins);
7523 VectorCopy(thisvertex->v, surface->maxs);
7524 for (;vertexindex < numtriangles*3;vertexindex++)
7526 thisvertex = vertices + vertexindex;
7527 if (thisvertex->submodelindex != submodelindex)
7529 if (thisvertex->textureindex != textureindex)
7531 // add vertex to surface bounds
7532 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7533 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7534 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7535 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7536 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7537 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7538 // add the vertex if it is not found in the merged set, and
7539 // get its index (triangle element) for the surface
7540 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7541 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7543 vdata = vertexhashdata + i;
7544 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7549 i = vertexhashcount++;
7550 vdata = vertexhashdata + i;
7551 *vdata = *thisvertex;
7552 vdata->nextindex = vertexhashtable[vertexhashindex];
7553 vertexhashtable[vertexhashindex] = i;
7556 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7559 surfacetriangles = surfaceelements / 3;
7560 surface->num_vertices = surfacevertices;
7561 surface->num_triangles = surfacetriangles;
7562 surface->num_firstvertex = firstvertex;
7563 surface->num_firsttriangle = firsttriangle;
7564 firstvertex += surface->num_vertices;
7565 firsttriangle += surface->num_triangles;
7567 loadmodel->num_surfaces++;
7570 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7571 numvertices = firstvertex;
7572 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7573 tempsurfaces = NULL;
7575 // allocate storage for final mesh data
7576 loadmodel->num_textures = numtextures * loadmodel->numskins;
7577 loadmodel->num_texturesperskin = numtextures;
7578 data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7579 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7580 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7581 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7582 loadmodel->surfmesh.num_vertices = numvertices;
7583 loadmodel->surfmesh.num_triangles = numtriangles;
7584 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7585 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7586 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7587 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7588 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7589 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7590 if (loadmodel->surfmesh.num_vertices <= 65536)
7591 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7593 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7595 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7596 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7597 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7600 // load the textures
7601 for (textureindex = 0;textureindex < numtextures;textureindex++)
7602 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7603 Mod_FreeSkinFiles(skinfiles);
7605 // set the surface textures to their real values now that we loaded them...
7606 for (i = 0;i < loadmodel->num_surfaces;i++)
7607 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7611 Mem_Free(texturenames);
7615 Mem_Free(vertexhashtable);
7616 Mem_Free(vertexhashdata);
7618 // make a single combined shadow mesh to allow optimized shadow volume creation
7619 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7621 // compute all the mesh information that was not loaded from the file
7622 if (loadmodel->surfmesh.data_element3s)
7623 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7624 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7625 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7626 // generate normals if the file did not have them
7627 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7628 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);
7629 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);
7630 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7632 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7633 loadmodel->brush.num_visleafs = 1;
7634 loadmodel->brush.num_leafs = 1;
7635 loadmodel->brush.num_nodes = 0;
7636 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7637 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7638 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7639 loadmodel->brush.num_pvsclusters = 1;
7640 loadmodel->brush.num_pvsclusterbytes = 1;
7641 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7642 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7643 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7644 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7645 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7646 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7647 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7648 loadmodel->brush.data_leafs->clusterindex = 0;
7649 loadmodel->brush.data_leafs->areaindex = 0;
7650 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7651 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7652 loadmodel->brush.data_leafs->numleafbrushes = 0;
7653 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7654 loadmodel->brush.supportwateralpha = true;
7656 if (loadmodel->brush.numsubmodels)
7657 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7660 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7665 // duplicate the basic information
7666 dpsnprintf(name, sizeof(name), "*%i", i);
7667 mod = Mod_FindName(name, loadmodel->name);
7668 // copy the base model to this one
7670 // rename the clone back to its proper name
7671 strlcpy(mod->name, name, sizeof(mod->name));
7672 mod->brush.parentmodel = loadmodel;
7673 // textures and memory belong to the main model
7674 mod->texturepool = NULL;
7675 mod->mempool = NULL;
7676 mod->brush.GetPVS = NULL;
7677 mod->brush.FatPVS = NULL;
7678 mod->brush.BoxTouchingPVS = NULL;
7679 mod->brush.BoxTouchingLeafPVS = NULL;
7680 mod->brush.BoxTouchingVisibleLeafs = NULL;
7681 mod->brush.FindBoxClusters = NULL;
7682 mod->brush.LightPoint = NULL;
7683 mod->brush.AmbientSoundLevelsForPoint = NULL;
7685 mod->brush.submodel = i;
7686 if (loadmodel->brush.submodels)
7687 loadmodel->brush.submodels[i] = mod;
7689 // make the model surface list (used by shadowing/lighting)
7690 mod->firstmodelsurface = submodelfirstsurface[i];
7691 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7692 mod->firstmodelbrush = 0;
7693 mod->nummodelbrushes = 0;
7694 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
7695 Mod_MakeSortedSurfaces(mod);
7697 VectorClear(mod->normalmins);
7698 VectorClear(mod->normalmaxs);
7700 for (j = 0;j < mod->nummodelsurfaces;j++)
7702 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7703 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7705 if (!surface->num_vertices)
7710 VectorCopy(v, mod->normalmins);
7711 VectorCopy(v, mod->normalmaxs);
7713 for (k = 0;k < surface->num_vertices;k++, v += 3)
7715 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7716 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7717 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7718 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7719 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7720 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7723 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7724 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7725 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7726 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7727 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7728 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7729 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7730 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7731 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7732 mod->yawmins[2] = mod->normalmins[2];
7733 mod->yawmaxs[2] = mod->normalmaxs[2];
7734 mod->radius = modelradius;
7735 mod->radius2 = modelradius * modelradius;
7737 // this gets altered below if sky or water is used
7738 mod->DrawSky = NULL;
7739 mod->DrawAddWaterPlanes = NULL;
7741 for (j = 0;j < mod->nummodelsurfaces;j++)
7742 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7744 if (j < mod->nummodelsurfaces)
7745 mod->DrawSky = R_Q1BSP_DrawSky;
7747 for (j = 0;j < mod->nummodelsurfaces;j++)
7748 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7750 if (j < mod->nummodelsurfaces)
7751 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7753 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
7754 mod->render_bih = mod->collision_bih;
7756 // generate VBOs and other shared data before cloning submodels
7761 Mem_Free(submodelfirstsurface);
7763 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);
7778 typedef struct objvertex_s
7786 typedef struct objtriangle_s
7788 objvertex_t vertex[3];
7790 // these fields are used only in conversion to surfaces
7793 int surfacevertexindex[3];
7794 float edgeplane[3][4];
7800 struct objnode_s *children[2];
7801 struct objnode_s *parent;
7802 objtriangle_t *triangles;
7811 objnode_t *Mod_OBJ_BSPNodeForTriangles(objnode_t *parent, objtriangle_t *triangles, int numtriangles, const float *mins, const float *maxs, mem_expandablearray_t *nodesarray, int maxclippedtriangles, objtriangle_t *clippedfronttriangles, objtriangle_t *clippedbacktriangles)
7817 float bestnormal[3];
7822 int numfronttriangles;
7823 int numbacktriangles;
7828 float outfrontpoints[5][3];
7829 float outbackpoints[5][3];
7830 int neededfrontpoints;
7831 int neededbackpoints;
7835 node = (objnode_t *)Mem_ExpandableArray_AllocRecord(array);
7836 node->parent = parent;
7839 VectorCopy(triangles[0].vertex[0].v, mins);
7840 VectorCopy(triangles[0].vertex[0].v, maxs);
7842 else if (parent && parent->children[0] == node)
7844 VectorCopy(parent->mins, mins);
7845 Vectorcopy(parent->maxs, maxs);
7847 else if (parent && parent->children[1] == node)
7849 VectorCopy(parent->mins, mins);
7850 Vectorcopy(parent->maxs, maxs);
7857 for (i = 0;i < numtriangles;i++)
7859 for (j = 0;j < 3;j++)
7861 mins[0] = min(mins[0], triangles[i].vertex[j].v[0]);
7862 mins[1] = min(mins[1], triangles[i].vertex[j].v[1]);
7863 mins[2] = min(mins[2], triangles[i].vertex[j].v[2]);
7864 maxs[0] = max(maxs[0], triangles[i].vertex[j].v[0]);
7865 maxs[1] = max(maxs[1], triangles[i].vertex[j].v[1]);
7866 maxs[2] = max(maxs[2], triangles[i].vertex[j].v[2]);
7869 VectorCopy(mins, node->mins);
7870 VectorCopy(maxs, node->maxs);
7871 if (numtriangles <= mod_obj_leaftriangles.integer)
7874 loadmodel->brush.num_leafs++;
7875 node->triangles = triangles;
7876 node->numtriangles = numtriangles;
7881 loadmodel->brush.num_nodes++;
7882 // pick a splitting plane from the various choices available to us...
7883 // early splits simply halve the interval
7885 VectorClear(bestnormal);
7887 if (numtriangles <= mod_obj_splitterlimit.integer)
7888 limit = numtriangles;
7891 for (i = -3;i < limit;i++)
7895 // first we try 3 axial splits (kdtree-like)
7897 VectorClear(normal);
7899 dist = (mins[j] + maxs[j]) * 0.5f;
7903 // then we try each triangle plane
7904 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7905 VectorNormalize(normal);
7906 dist = DotProduct(normal, triangles[i].vertex[0].v);
7907 // use positive axial values whenever possible
7908 if (normal[0] == -1)
7910 if (normal[1] == -1)
7912 if (normal[2] == -1)
7914 // skip planes that match the current best
7915 if (VectorCompare(normal, bestnormal) && dist == bestdist)
7922 for (j = 0;j < numtriangles;j++)
7924 dists[0] = DotProduct(normal, triangles[j].vertex[0].v) - dist;
7925 dists[1] = DotProduct(normal, triangles[j].vertex[1].v) - dist;
7926 dists[2] = DotProduct(normal, triangles[j].vertex[2].v) - dist;
7927 if (dists[0] < -DIST_EPSILON || dists[1] < -DIST_EPSILON || dists[2] < -DIST_EPSILON)
7929 if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7934 else if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7939 // score is supposed to:
7940 // prefer axial splits
7941 // prefer evenly dividing the input triangles
7942 // prefer triangles on the plane
7943 // avoid triangles crossing the plane
7944 score = count_on*count_on - count_both*count_both + min(count_front, count_back)*(count_front+count_back);
7945 if (normal[0] == 1 || normal[1] == 1 || normal[2] == 1)
7947 if (i == -3 || bestscore < score)
7949 VectorCopy(normal, bestnormal);
7955 // now we have chosen an optimal split plane...
7957 // divide triangles by the splitting plane
7958 numfronttriangles = 0;
7959 numbacktriangles = 0;
7960 for (i = 0;i < numtriangles;i++)
7962 neededfrontpoints = 0;
7963 neededbackpoints = 0;
7965 PolygonF_Divide(3, triangles[i].vertex[0].v, bestnormal[0], bestnormal[1], bestnormal[2], bestdist, DIST_EPSILON, 5, outfrontpoints[0], &neededfrontpoints, 5, outbackpoints[0], &neededbackpoints, &countonpoints);
7966 if (countonpoints > 1)
7968 // triangle lies on plane, assign it to one child only
7969 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7970 if (DotProduct(bestnormal, normal) >= 0)
7972 // assign to front side child
7973 obj_fronttriangles[numfronttriangles++] = triangles[i];
7977 // assign to back side child
7978 obj_backtriangles[numbacktriangles++] = triangles[i];
7983 // convert clipped polygons to triangles
7984 for (j = 0;j < neededfrontpoints-2;j++)
7986 obj_fronttriangles[numfronttriangles] = triangles[i];
7987 VectorCopy(outfrontpoints[0], obj_fronttriangles[numfronttriangles].vertex[0].v);
7988 VectorCopy(outfrontpoints[j+1], obj_fronttriangles[numfronttriangles].vertex[1].v);
7989 VectorCopy(outfrontpoints[j+2], obj_fronttriangles[numfronttriangles].vertex[2].v);
7990 numfronttriangles++;
7992 for (j = 0;j < neededbackpoints-2;j++)
7994 obj_backtriangles[numbacktriangles] = triangles[i];
7995 VectorCopy(outbackpoints[0], obj_backtriangles[numbacktriangles].vertex[0].v);
7996 VectorCopy(outbackpoints[j+1], obj_backtriangles[numbacktriangles].vertex[1].v);
7997 VectorCopy(outbackpoints[j+2], obj_backtriangles[numbacktriangles].vertex[2].v);
8003 // now copy the triangles out of the big buffer
8004 if (numfronttriangles)
8006 fronttriangles = Mem_Alloc(loadmodel->mempool, fronttriangles * sizeof(*fronttriangles));
8007 memcpy(fronttriangles, obj_fronttriangles, numfronttriangles * sizeof(*fronttriangles));
8010 fronttriangles = NULL;
8011 if (numbacktriangles)
8013 backtriangles = Mem_Alloc(loadmodel->mempool, backtriangles * sizeof(*backtriangles));
8014 memcpy(backtriangles, obj_backtriangles, numbacktriangles * sizeof(*backtriangles));
8017 backtriangles = NULL;
8019 // free the original triangles we were given
8021 Mem_Free(triangles);
8025 // now create the children...
8026 node->children[0] = Mod_OBJ_BSPNodeForTriangles(node, fronttriangles, numfronttriangles, frontmins, frontmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8027 node->children[1] = Mod_OBJ_BSPNodeForTriangles(node, backtriangles, numbacktriangles, backmins, backmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8031 void Mod_OBJ_SnapVertex(float *v)
8034 float a = mod_obj_vertexprecision.value;
8036 v[0] -= floor(v[0] * a + 0.5f) * b;
8037 v[1] -= floor(v[1] * a + 0.5f) * b;
8038 v[2] -= floor(v[2] * a + 0.5f) * b;
8041 void Mod_OBJ_ConvertBSPNode(objnode_t *objnode, mnode_t *mnodeparent)
8043 if (objnode->children[0])
8045 // convert to mnode_t
8046 mnode_t *mnode = loadmodel->brush.data_nodes + loadmodel->brush.num_nodes++;
8047 mnode->parent = mnodeparent;
8048 mnode->plane = loadmodel->brush.data_planes + loadmodel->brush.num_planes++;
8049 VectorCopy(objnode->normal, mnode->plane->normal);
8050 mnode->plane->dist = objnode->dist;
8051 PlaneClassify(mnode->plane);
8052 VectorCopy(objnode->mins, mnode->mins);
8053 VectorCopy(objnode->maxs, mnode->maxs);
8054 // push combinedsupercontents up to the parent
8056 mnodeparent->combinedsupercontents |= mnode->combinedsupercontents;
8057 mnode->children[0] = Mod_OBJ_ConvertBSPNode(objnode->children[0], mnode);
8058 mnode->children[1] = Mod_OBJ_ConvertBSPNode(objnode->children[1], mnode);
8062 // convert to mleaf_t
8063 mleaf_t *mleaf = loadmodel->brush.data_leafs + loadmodel->brush.num_leafs++;
8064 mleaf->parent = mnodeparent;
8065 VectorCopy(objnode->mins, mleaf->mins);
8066 VectorCopy(objnode->maxs, mleaf->maxs);
8067 mleaf->clusterindex = loadmodel->brush.num_leafs - 1;
8068 if (objnode->numtriangles)
8070 objtriangle_t *triangles = objnode->triangles;
8071 int numtriangles = objnode->numtriangles;
8075 objvertex_t vertex[3];
8077 maxsurfaces = numtriangles;
8079 // calculate some more data on each triangle for surface gathering
8080 for (i = 0;i < numtriangles;i++)
8082 triangle = triangles + i;
8083 texture = loadmodel->data_textures + triangle->textureindex;
8084 Mod_OBJ_SnapVertex(triangle->vertex[0].v);
8085 Mod_OBJ_SnapVertex(triangle->vertex[1].v);
8086 Mod_OBJ_SnapVertex(triangle->vertex[2].v);
8087 TriangleNormal(triangle->vertex[0].v, triangle->vertex[1].v, triangle->vertex[2].v, normal);
8089 if (fabs(normal[axis]) < fabs(normal[1]))
8091 if (fabs(normal[axis]) < fabs(normal[2]))
8093 VectorClear(normal);
8095 triangle->axis = axis;
8096 VectorSubtract(triangle->vertex[1].v, triangle->vertex[0].v, edge[0]);
8097 VectorSubtract(triangle->vertex[2].v, triangle->vertex[1].v, edge[1]);
8098 VectorSubtract(triangle->vertex[0].v, triangle->vertex[2].v, edge[2]);
8099 CrossProduct(edge[0], normal, triangle->edgeplane[0]);
8100 CrossProduct(edge[1], normal, triangle->edgeplane[1]);
8101 CrossProduct(edge[2], normal, triangle->edgeplane[2]);
8102 VectorNormalize(triangle->edgeplane[0]);
8103 VectorNormalize(triangle->edgeplane[1]);
8104 VectorNormalize(triangle->edgeplane[2]);
8105 triangle->edgeplane[0][3] = DotProduct(triangle->edgeplane[0], triangle->vertex[0].v);
8106 triangle->edgeplane[1][3] = DotProduct(triangle->edgeplane[1], triangle->vertex[1].v);
8107 triangle->edgeplane[2][3] = DotProduct(triangle->edgeplane[2], triangle->vertex[2].v);
8108 triangle->surfaceindex = 0;
8109 // add to the combined supercontents while we're here...
8110 mleaf->combinedsupercontents |= texture->supercontents;
8113 for (i = 0;i < numtriangles;i++)
8115 // skip already-assigned triangles
8116 if (triangles[i].surfaceindex)
8118 texture = loadmodel->data_textures + triangles[i].textureindex;
8119 // assign a new surface to this triangle
8120 triangles[i].surfaceindex = surfaceindex++;
8121 axis = triangles[i].axis;
8123 // find the triangle's neighbors, this can take multiple passes
8128 for (j = i+1;j < numtriangles;j++)
8130 if (triangles[j].surfaceindex || triangles[j].axis != axis || triangles[j].texture != texture)
8132 triangle = triangles + j;
8133 for (k = i;k < j;k++)
8135 if (triangles[k].surfaceindex != surfaceindex)
8137 if (VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[0].v)
8138 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[1].v)
8139 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[2].v)
8140 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[0].v)
8141 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[1].v)
8142 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[2].v)
8143 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[0].v)
8144 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[1].v)
8145 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[2].v))
8147 // shares a vertex position
8151 for (k = 0;k < numvertices;k++)
8152 if (!VectorCompare(vertex[k].v, triangles[j].vertex[0].v) || !VectorCompare(vertex[k].v, triangles[j].vertex[1].v) || !VectorCompare(vertex[k].v, triangles[j].vertex[2].v))
8154 if (k == numvertices)
8155 break; // not a neighbor
8156 // this triangle is a neighbor and has the same axis and texture
8157 // check now if it overlaps in lightmap projection space
8158 triangles[j].surfaceindex;
8162 //triangles[i].surfaceindex = surfaceindex++;
8163 for (surfaceindex = 0;surfaceindex < numsurfaces;surfaceindex++)
8165 if (surfaces[surfaceindex].texture != texture)
8167 // check if any triangles already in this surface overlap in lightmap projection space
8174 // let the collision code simply use the surfaces
8175 mleaf->containscollisionsurfaces = mleaf->combinedsupercontents != 0;
8176 mleaf->numleafsurfaces = ?;
8177 mleaf->firstleafsurface = ?;
8179 // push combinedsupercontents up to the parent
8181 mnodeparent->combinedsupercontents |= mleaf->combinedsupercontents;
8186 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
8189 const char *textbase = (char *)buffer, *text = textbase;
8193 char materialname[MAX_QPATH];
8194 int j, index1, index2, index3, first, prev, index;
8197 int numtriangles = 0;
8198 int maxtriangles = 131072;
8199 objtriangle_t *triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8201 int maxtextures = 256, numtextures = 0, textureindex = 0;
8202 int maxv = 1024, numv = 0;
8203 int maxvt = 1024, numvt = 0;
8204 int maxvn = 1024, numvn = 0;
8205 char **texturenames;
8206 float *v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
8207 float *vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
8208 float *vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
8209 objvertex_t vfirst, vprev, vcurrent;
8214 int maxverthash = 65536, numverthash = 0;
8215 int numhashindex = 65536;
8216 struct objverthash_s
8218 struct objverthash_s *next;
8224 *hash, **verthash = Mem_Alloc(tempmempool, numhashindex * sizeof(*verthash)), *verthashdata = Mem_Alloc(tempmempool, maxverthash * sizeof(*verthashdata)), *oldverthashdata;
8227 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8229 loadmodel->modeldatatypestring = "OBJ";
8231 loadmodel->type = mod_obj;
8232 loadmodel->soundfromcenter = true;
8233 loadmodel->TraceBox = Mod_OBJ_TraceBox;
8234 loadmodel->TraceLine = Mod_OBJ_TraceLine;
8235 loadmodel->TracePoint = Mod_OBJ_TracePoint;
8236 loadmodel->PointSuperContents = Mod_OBJ_PointSuperContents;
8237 loadmodel->brush.TraceLineOfSight = Mod_OBJ_TraceLineOfSight;
8238 loadmodel->brush.SuperContentsFromNativeContents = Mod_OBJ_SuperContentsFromNativeContents;
8239 loadmodel->brush.NativeContentsFromSuperContents = Mod_OBJ_NativeContentsFromSuperContents;
8240 loadmodel->brush.GetPVS = Mod_OBJ_GetPVS;
8241 loadmodel->brush.FatPVS = Mod_OBJ_FatPVS;
8242 loadmodel->brush.BoxTouchingPVS = Mod_OBJ_BoxTouchingPVS;
8243 loadmodel->brush.BoxTouchingLeafPVS = Mod_OBJ_BoxTouchingLeafPVS;
8244 loadmodel->brush.BoxTouchingVisibleLeafs = Mod_OBJ_BoxTouchingVisibleLeafs;
8245 loadmodel->brush.FindBoxClusters = Mod_OBJ_FindBoxClusters;
8246 loadmodel->brush.LightPoint = Mod_OBJ_LightPoint;
8247 loadmodel->brush.FindNonSolidLocation = Mod_OBJ_FindNonSolidLocation;
8248 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8249 loadmodel->brush.RoundUpToHullSize = NULL;
8250 loadmodel->brush.PointInLeaf = Mod_OBJ_PointInLeaf;
8251 loadmodel->Draw = R_Q1BSP_Draw;
8252 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
8253 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
8254 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
8255 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
8256 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
8257 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
8258 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
8259 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
8260 loadmodel->DrawLight = R_Q1BSP_DrawLight;
8265 // parse the OBJ text now
8272 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8273 line[linelen] = text[linelen];
8275 for (argc = 0;argc < (int)(sizeof(argv)/sizeof(argv[0]));argc++)
8279 while (*s == ' ' || *s == '\t')
8289 while (*s == ' ' || *s == '\t')
8294 if (argv[0][0] == '#')
8296 if (!strcmp(argv[0], "v"))
8302 v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
8305 memcpy(v, oldv, numv * sizeof(float[3]));
8309 v[numv*3+0] = atof(argv[1]);
8310 v[numv*3+1] = atof(argv[2]);
8311 v[numv*3+2] = atof(argv[3]);
8314 else if (!strcmp(argv[0], "vt"))
8320 vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
8323 memcpy(vt, oldvt, numvt * sizeof(float[2]));
8327 vt[numvt*2+0] = atof(argv[1]);
8328 vt[numvt*2+1] = atof(argv[2]);
8331 else if (!strcmp(argv[0], "vn"))
8337 vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
8340 memcpy(vn, oldvn, numvn * sizeof(float[3]));
8344 vn[numvn*3+0] = atof(argv[1]);
8345 vn[numvn*3+1] = atof(argv[2]);
8346 vn[numvn*3+2] = atof(argv[3]);
8349 else if (!strcmp(argv[0], "f"))
8351 for (j = 1;j < argc;j++)
8353 index1 = atoi(argv[j]);
8354 while(argv[j][0] && argv[j][0] != '/')
8358 index2 = atoi(argv[j]);
8359 while(argv[j][0] && argv[j][0] != '/')
8363 index3 = atoi(argv[j]);
8364 // negative refers to a recent vertex
8365 // zero means not specified
8366 // positive means an absolute vertex index
8368 index1 = numv - index1;
8370 index2 = numvt - index2;
8372 index3 = numvn - index3;
8373 VectorCopy(v + 3*index1, vcurrent.v);
8374 Vector2Copy(vt + 2*index2, vcurrent.vt);
8375 VectorCopy(vn + 3*index3, vcurrent.vn);
8376 if (numtriangles == 0)
8378 VectorCopy(vcurrent.v, mins);
8379 VectorCopy(vcurrent.v, maxs);
8383 mins[0] = min(mins[0], vcurrent.v[0]);
8384 mins[1] = min(mins[1], vcurrent.v[1]);
8385 mins[2] = min(mins[2], vcurrent.v[2]);
8386 maxs[0] = max(maxs[0], vcurrent.v[0]);
8387 maxs[1] = max(maxs[1], vcurrent.v[1]);
8388 maxs[2] = max(maxs[2], vcurrent.v[2]);
8394 if (maxtriangles <= numtriangles)
8396 objtriangle_t *oldtriangles = triangles;
8398 triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8401 memcpy(triangles, oldtriangles, maxtriangles * sizeof(*triangles));
8402 Mem_Free(oldtriangles);
8405 triangles[numtriangles].textureindex = textureindex;
8406 triangles[numtriangles].vertex[0] = vfirst;
8407 triangles[numtriangles].vertex[1] = vprev;
8408 triangles[numtriangles].vertex[2] = vcurrent;
8415 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8417 else if (!!strcmp(argv[0], "usemtl"))
8419 for (i = 0;i < numtextures;i++)
8420 if (!strcmp(texturenames[numtextures], argv[1]))
8422 if (i < numtextures)
8423 texture = textures + i;
8426 if (maxtextures <= numtextures)
8428 texture_t *oldtextures = textures;
8430 textures = Mem_Alloc(tempmempool, maxtextures * sizeof(*textures));
8433 memcpy(textures, oldtextures, numtextures * sizeof(*textures));
8434 Mem_Free(oldtextures);
8437 textureindex = numtextures++;
8438 texturenames[textureindex] = Mem_Alloc(tempmempool, strlen(argv[1]) + 1);
8439 memcpy(texturenames[textureindex], argv[1], strlen(argv[1]) + 1);
8449 // now that we have the OBJ data loaded as-is, we can convert it
8451 // load the textures
8452 loadmodel->num_textures = numtextures;
8453 loadmodel->data_textures = Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
8454 for (i = 0;i < numtextures;i++)
8455 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, texturenames[i], true, true, TEXF_MIPMAP | TEXF_ALPHA | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
8457 // free the texturenames array since we are now done with it
8458 for (i = 0;i < numtextures;i++)
8460 Mem_Free(texturenames[i]);
8461 texturenames[i] = NULL;
8463 Mem_Free(texturenames);
8464 texturenames = NULL;
8466 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8467 VectorCopy(mins, loadmodel->normalmins);
8468 VectorCopy(maxs, loadmodel->normalmaxs);
8469 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8470 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8471 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8472 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8473 modelradius = modelyawradius + modelradius * modelradius;
8474 modelyawradius = sqrt(modelyawradius);
8475 modelradius = sqrt(modelradius);
8476 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8477 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8478 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8479 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8480 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8481 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8482 loadmodel->radius = modelradius;
8483 loadmodel->radius2 = modelradius * modelradius;
8485 // make sure the temp triangle buffer is big enough for BSP building
8486 maxclippedtriangles = numtriangles*4;
8487 if (numtriangles > 0)
8489 clippedfronttriangles = Mem_Alloc(loadmodel->mempool, maxclippedtriangles * 2 * sizeof(objtriangle_t));
8490 clippedbacktriangles = clippedfronttriangles + maxclippedtriangles;
8493 // generate a rough BSP tree from triangle data, we don't have to be too careful here, it only has to define the basic areas of the map
8494 loadmodel->brush.num_leafs = 0;
8495 loadmodel->brush.num_nodes = 0;
8496 Mem_ExpandableArray_NewArray(&nodesarray, loadmodel->mempool, sizeof(objnode_t), 1024);
8497 rootnode = Mod_OBJ_BSPNodeForTriangles(triangles, numtriangles, mins, maxs, &nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8499 // convert the BSP tree to mnode_t and mleaf_t structures and convert the triangles to msurface_t...
8500 loadmodel->brush.data_leafs = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8501 loadmodel->brush.data_nodes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mnode_t));
8502 loadmodel->brush.data_planes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mplane_t));
8503 loadmodel->brush.num_leafs = 0;
8504 loadmodel->brush.num_nodes = 0;
8505 loadmodel->brush.num_planes = 0;
8506 Mod_OBJ_ConvertAndFreeBSPNode(rootnode);
8508 if (clippedfronttriangles)
8509 Mem_Free(clippedfronttriangles);
8510 maxclippedtriangles = 0;
8511 clippedfronttriangles = NULL;
8512 clippedbacktriangles = NULL;
8514 --- NOTHING DONE PAST THIS POINT ---
8516 loadmodel->numskins = LittleLong(pinmodel->num_skins);
8517 numxyz = LittleLong(pinmodel->num_xyz);
8518 numst = LittleLong(pinmodel->num_st);
8519 loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->num_tris);
8520 loadmodel->numframes = LittleLong(pinmodel->num_frames);
8521 loadmodel->surfmesh.num_morphframes = loadmodel->numframes;
8522 loadmodel->num_poses = loadmodel->surfmesh.num_morphframes;
8523 skinwidth = LittleLong(pinmodel->skinwidth);
8524 skinheight = LittleLong(pinmodel->skinheight);
8525 iskinwidth = 1.0f / skinwidth;
8526 iskinheight = 1.0f / skinheight;
8528 loadmodel->num_surfaces = 1;
8529 loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
8530 data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->numframes * sizeof(animscene_t) + loadmodel->numframes * sizeof(float[6]) + loadmodel->surfmesh.num_triangles * sizeof(int[3]) + loadmodel->surfmesh.num_triangles * sizeof(int[3]));
8531 loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
8532 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8533 loadmodel->sortedmodelsurfaces[0] = 0;
8534 loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
8535 loadmodel->surfmesh.data_morphmd2framesize6f = (float *)data;data += loadmodel->numframes * sizeof(float[6]);
8536 loadmodel->surfmesh.data_element3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8537 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8539 loadmodel->synctype = ST_RAND;
8542 inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
8543 skinfiles = Mod_LoadSkinFiles();
8546 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8547 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8548 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8549 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
8550 Mod_FreeSkinFiles(skinfiles);
8552 else if (loadmodel->numskins)
8554 // skins found (most likely not a player model)
8555 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8556 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8557 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8558 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
8559 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i * loadmodel->num_surfaces, inskin, true, true, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP | TEXF_COMPRESS);
8563 // no skins (most likely a player model)
8564 loadmodel->numskins = 1;
8565 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8566 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8567 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8568 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
8571 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8572 for (i = 0;i < loadmodel->numskins;i++)
8574 loadmodel->skinscenes[i].firstframe = i;
8575 loadmodel->skinscenes[i].framecount = 1;
8576 loadmodel->skinscenes[i].loop = true;
8577 loadmodel->skinscenes[i].framerate = 10;
8580 // load the triangles and stvert data
8581 inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
8582 intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
8583 md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 65536 * sizeof(hash));
8584 md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->surfmesh.num_triangles * 3 * sizeof(*hash));
8585 // swap the triangle list
8586 loadmodel->surfmesh.num_vertices = 0;
8587 for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
8589 for (j = 0;j < 3;j++)
8591 xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
8592 st = (unsigned short) LittleShort (intri[i].index_st[j]);
8595 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
8600 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
8603 hashindex = (xyz * 256 + st) & 65535;
8604 for (hash = md2verthash[hashindex];hash;hash = hash->next)
8605 if (hash->xyz == xyz && hash->st == st)
8609 hash = md2verthashdata + loadmodel->surfmesh.num_vertices++;
8612 hash->next = md2verthash[hashindex];
8613 md2verthash[hashindex] = hash;
8615 loadmodel->surfmesh.data_element3i[i*3+j] = (hash - md2verthashdata);
8619 vertremap = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(int));
8620 data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(float[2]) + loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t));
8621 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
8622 loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)data;data += loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t);
8623 for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
8626 hash = md2verthashdata + i;
8627 vertremap[i] = hash->xyz;
8628 sts = LittleShort(inst[hash->st*2+0]);
8629 stt = LittleShort(inst[hash->st*2+1]);
8630 if (sts < 0 || sts >= skinwidth || stt < 0 || stt >= skinheight)
8632 Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, sts, stt, i);
8636 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = sts * iskinwidth;
8637 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = stt * iskinheight;
8640 Mem_Free(md2verthash);
8641 Mem_Free(md2verthashdata);
8643 // generate ushort elements array if possible
8644 if (loadmodel->surfmesh.num_vertices <= 65536)
8645 loadmodel->surfmesh.data_element3s = (unsigned short *)Mem_Alloc(loadmodel->mempool, sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles);
8648 datapointer = (base + LittleLong(pinmodel->ofs_frames));
8649 for (i = 0;i < loadmodel->surfmesh.num_morphframes;i++)
8654 pinframe = (md2frame_t *)datapointer;
8655 datapointer += sizeof(md2frame_t);
8656 // store the frame scale/translate into the appropriate array
8657 for (j = 0;j < 3;j++)
8659 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+j] = LittleFloat(pinframe->scale[j]);
8660 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+3+j] = LittleFloat(pinframe->translate[j]);
8662 // convert the vertices
8663 v = (trivertx_t *)datapointer;
8664 out = loadmodel->surfmesh.data_morphmdlvertex + i * loadmodel->surfmesh.num_vertices;
8665 for (k = 0;k < loadmodel->surfmesh.num_vertices;k++)
8666 out[k] = v[vertremap[k]];
8667 datapointer += numxyz * sizeof(trivertx_t);
8669 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
8670 loadmodel->animscenes[i].firstframe = i;
8671 loadmodel->animscenes[i].framecount = 1;
8672 loadmodel->animscenes[i].framerate = 10;
8673 loadmodel->animscenes[i].loop = true;
8676 Mem_Free(vertremap);
8678 Mod_MakeSortedSurfaces(loadmodel);
8679 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8680 Mod_Alias_CalculateBoundingBox();
8681 Mod_Alias_MorphMesh_CompileFrames();
8683 surface = loadmodel->data_surfaces;
8684 surface->texture = loadmodel->data_textures;
8685 surface->num_firsttriangle = 0;
8686 surface->num_triangles = loadmodel->surfmesh.num_triangles;
8687 surface->num_firstvertex = 0;
8688 surface->num_vertices = loadmodel->surfmesh.num_vertices;
8690 loadmodel->surfmesh.isanimated = false;
8692 if (loadmodel->surfmesh.data_element3s)
8693 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8694 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8697 #endif // !OBJASMODEL
8699 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
8701 // we already have done PVS culling at this point...
8702 // so we don't need to do it again.
8705 vec3_t testorigin, mins, maxs;
8707 testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
8708 testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
8709 testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
8711 if(model->brush.TraceLineOfSight(model, eye, testorigin))
8714 // expand the box a little
8715 mins[0] = (t+1) * minsX[0] - t * maxsX[0];
8716 maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
8717 mins[1] = (t+1) * minsX[1] - t * maxsX[1];
8718 maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
8719 mins[2] = (t+1) * minsX[2] - t * maxsX[2];
8720 maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
8722 for(i = 0; i != numsamples; ++i)
8724 testorigin[0] = lhrandom(mins[0], maxs[0]);
8725 testorigin[1] = lhrandom(mins[1], maxs[1]);
8726 testorigin[2] = lhrandom(mins[2], maxs[2]);
8728 if(model->brush.TraceLineOfSight(model, eye, testorigin))