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"};
50 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)"};
51 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"};
52 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"};
54 static texture_t mod_q1bsp_texture_solid;
55 static texture_t mod_q1bsp_texture_sky;
56 static texture_t mod_q1bsp_texture_lava;
57 static texture_t mod_q1bsp_texture_slime;
58 static texture_t mod_q1bsp_texture_water;
60 void Mod_BrushInit(void)
62 // Cvar_RegisterVariable(&r_subdivide_size);
63 Cvar_RegisterVariable(&r_novis);
64 Cvar_RegisterVariable(&r_nosurftextures);
65 Cvar_RegisterVariable(&r_subdivisions_tolerance);
66 Cvar_RegisterVariable(&r_subdivisions_mintess);
67 Cvar_RegisterVariable(&r_subdivisions_maxtess);
68 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
69 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
70 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
71 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
72 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
73 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
74 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
75 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
76 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
77 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
78 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
79 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
80 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
81 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
82 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
83 Cvar_RegisterVariable(&mod_collision_bih);
84 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
86 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
87 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
88 mod_q1bsp_texture_solid.surfaceflags = 0;
89 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
91 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
92 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
93 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
94 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
96 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
97 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
98 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
99 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
101 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
102 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
103 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
104 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
106 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
107 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
108 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
109 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
112 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
119 // LordHavoc: modified to start at first clip node,
120 // in other words: first node of the (sub)model
121 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
123 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
125 return (mleaf_t *)node;
128 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
132 leaf = Mod_Q1BSP_PointInLeaf(model, p);
135 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
138 memcpy(out, leaf->ambient_sound_level, i);
144 memset(out, 0, outsize);
147 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
150 int nodestackindex = 0;
151 mnode_t *node, *nodestack[1024];
152 if (!model->brush.num_pvsclusters)
154 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
160 // node - recurse down the BSP tree
161 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
165 return -1; // ERROR: NAN bounding box!
166 // box is on one side of plane, take that path
167 node = node->children[sides-1];
171 // box crosses plane, take one path and remember the other
172 if (nodestackindex < 1024)
173 nodestack[nodestackindex++] = node->children[0];
174 node = node->children[1];
180 // leaf - add clusterindex to list
181 if (numclusters < maxclusters)
182 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
186 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
190 if (nodestackindex < 1024)
191 nodestack[nodestackindex++] = node->children[0];
192 node = node->children[1];
197 // leaf - add clusterindex to list
198 if (numclusters < maxclusters)
199 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
204 // try another path we didn't take earlier
205 if (nodestackindex == 0)
207 node = nodestack[--nodestackindex];
209 // return number of clusters found (even if more than the maxclusters)
213 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
215 int nodestackindex = 0;
216 mnode_t *node, *nodestack[1024];
217 if (!model->brush.num_pvsclusters)
219 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
225 // node - recurse down the BSP tree
226 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
230 return -1; // ERROR: NAN bounding box!
231 // box is on one side of plane, take that path
232 node = node->children[sides-1];
236 // box crosses plane, take one path and remember the other
237 if (nodestackindex < 1024)
238 nodestack[nodestackindex++] = node->children[0];
239 node = node->children[1];
245 // leaf - check cluster bit
246 int clusterindex = ((mleaf_t *)node)->clusterindex;
247 if (CHECKPVSBIT(pvs, clusterindex))
249 // it is visible, return immediately with the news
254 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
258 if (nodestackindex < 1024)
259 nodestack[nodestackindex++] = node->children[0];
260 node = node->children[1];
265 // leaf - check cluster bit
266 int clusterindex = ((mleaf_t *)node)->clusterindex;
267 if (CHECKPVSBIT(pvs, clusterindex))
269 // it is visible, return immediately with the news
275 // nothing to see here, try another path we didn't take earlier
276 if (nodestackindex == 0)
278 node = nodestack[--nodestackindex];
284 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
286 int nodestackindex = 0;
287 mnode_t *node, *nodestack[1024];
288 if (!model->brush.num_leafs)
290 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
296 // node - recurse down the BSP tree
297 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
301 return -1; // ERROR: NAN bounding box!
302 // box is on one side of plane, take that path
303 node = node->children[sides-1];
307 // box crosses plane, take one path and remember the other
308 if (nodestackindex < 1024)
309 nodestack[nodestackindex++] = node->children[0];
310 node = node->children[1];
316 // leaf - check cluster bit
317 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
318 if (CHECKPVSBIT(pvs, clusterindex))
320 // it is visible, return immediately with the news
325 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
329 if (nodestackindex < 1024)
330 nodestack[nodestackindex++] = node->children[0];
331 node = node->children[1];
336 // leaf - check cluster bit
337 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
338 if (CHECKPVSBIT(pvs, clusterindex))
340 // it is visible, return immediately with the news
346 // nothing to see here, try another path we didn't take earlier
347 if (nodestackindex == 0)
349 node = nodestack[--nodestackindex];
355 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
357 int nodestackindex = 0;
358 mnode_t *node, *nodestack[1024];
359 if (!model->brush.num_leafs)
361 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
367 // node - recurse down the BSP tree
368 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
372 return -1; // ERROR: NAN bounding box!
373 // box is on one side of plane, take that path
374 node = node->children[sides-1];
378 // box crosses plane, take one path and remember the other
379 if (nodestackindex < 1024)
380 nodestack[nodestackindex++] = node->children[0];
381 node = node->children[1];
387 // leaf - check if it is visible
388 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
390 // it is visible, return immediately with the news
395 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
399 if (nodestackindex < 1024)
400 nodestack[nodestackindex++] = node->children[0];
401 node = node->children[1];
406 // leaf - check if it is visible
407 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
409 // it is visible, return immediately with the news
415 // nothing to see here, try another path we didn't take earlier
416 if (nodestackindex == 0)
418 node = nodestack[--nodestackindex];
424 typedef struct findnonsolidlocationinfo_s
427 vec3_t absmin, absmax;
433 findnonsolidlocationinfo_t;
435 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
438 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
440 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
441 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
442 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
443 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
444 VectorSubtract(vert[1], vert[0], edge[0]);
445 VectorSubtract(vert[2], vert[1], edge[1]);
446 CrossProduct(edge[1], edge[0], facenormal);
447 if (facenormal[0] || facenormal[1] || facenormal[2])
449 VectorNormalize(facenormal);
450 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
451 if (f <= info->bestdist && f >= -info->bestdist)
453 VectorSubtract(vert[0], vert[2], edge[2]);
454 VectorNormalize(edge[0]);
455 VectorNormalize(edge[1]);
456 VectorNormalize(edge[2]);
457 CrossProduct(facenormal, edge[0], edgenormal[0]);
458 CrossProduct(facenormal, edge[1], edgenormal[1]);
459 CrossProduct(facenormal, edge[2], edgenormal[2]);
461 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
462 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
463 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
465 // we got lucky, the center is within the face
466 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
470 if (info->bestdist > dist)
472 info->bestdist = dist;
473 VectorScale(facenormal, (info->radius - -dist), info->nudge);
478 if (info->bestdist > dist)
480 info->bestdist = dist;
481 VectorScale(facenormal, (info->radius - dist), info->nudge);
487 // check which edge or vertex the center is nearest
488 for (i = 0;i < 3;i++)
490 f = DotProduct(info->center, edge[i]);
491 if (f >= DotProduct(vert[0], edge[i])
492 && f <= DotProduct(vert[1], edge[i]))
495 VectorMA(info->center, -f, edge[i], point);
496 dist = sqrt(DotProduct(point, point));
497 if (info->bestdist > dist)
499 info->bestdist = dist;
500 VectorScale(point, (info->radius / dist), info->nudge);
502 // skip both vertex checks
503 // (both are further away than this edge)
508 // not on edge, check first vertex of edge
509 VectorSubtract(info->center, vert[i], point);
510 dist = sqrt(DotProduct(point, point));
511 if (info->bestdist > dist)
513 info->bestdist = dist;
514 VectorScale(point, (info->radius / dist), info->nudge);
523 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
525 int surfacenum, k, *mark;
527 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
529 surface = info->model->data_surfaces + *mark;
530 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
532 if(surface->deprecatedq3num_bboxstride > 0)
535 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
536 for(i = 0; i < cnt; ++i)
538 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
540 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
542 tri = i * surface->deprecatedq3num_bboxstride + k;
543 if(tri >= surface->num_triangles)
545 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
552 for (k = 0;k < surface->num_triangles;k++)
554 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
561 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
565 float f = PlaneDiff(info->center, node->plane);
566 if (f >= -info->bestdist)
567 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
568 if (f <= info->bestdist)
569 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
573 if (((mleaf_t *)node)->numleafsurfaces)
574 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
578 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
581 findnonsolidlocationinfo_t info;
587 VectorCopy(in, info.center);
588 info.radius = radius;
593 VectorClear(info.nudge);
594 info.bestdist = radius;
595 VectorCopy(info.center, info.absmin);
596 VectorCopy(info.center, info.absmax);
597 info.absmin[0] -= info.radius + 1;
598 info.absmin[1] -= info.radius + 1;
599 info.absmin[2] -= info.radius + 1;
600 info.absmax[0] += info.radius + 1;
601 info.absmax[1] += info.radius + 1;
602 info.absmax[2] += info.radius + 1;
603 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
604 VectorAdd(info.center, info.nudge, info.center);
606 while (info.bestdist < radius && ++i < 10);
607 VectorCopy(info.center, out);
610 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
612 switch(nativecontents)
617 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
619 return SUPERCONTENTS_WATER;
621 return SUPERCONTENTS_SLIME;
623 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
625 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
630 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
632 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
633 return CONTENTS_SOLID;
634 if (supercontents & SUPERCONTENTS_SKY)
636 if (supercontents & SUPERCONTENTS_LAVA)
637 return CONTENTS_LAVA;
638 if (supercontents & SUPERCONTENTS_SLIME)
639 return CONTENTS_SLIME;
640 if (supercontents & SUPERCONTENTS_WATER)
641 return CONTENTS_WATER;
642 return CONTENTS_EMPTY;
645 typedef struct RecursiveHullCheckTraceInfo_s
647 // the hull we're tracing through
650 // the trace structure to fill in
653 // start, end, and end - start (in model space)
658 RecursiveHullCheckTraceInfo_t;
660 // 1/32 epsilon to keep floating point happy
661 #define DIST_EPSILON (0.03125)
663 #define HULLCHECKSTATE_EMPTY 0
664 #define HULLCHECKSTATE_SOLID 1
665 #define HULLCHECKSTATE_DONE 2
667 extern cvar_t collision_prefernudgedfraction;
668 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
670 // status variables, these don't need to be saved on the stack when
671 // recursing... but are because this should be thread-safe
672 // (note: tracing against a bbox is not thread-safe, yet)
677 // variables that need to be stored on the stack when recursing
682 // LordHavoc: a goto! everyone flee in terror... :)
687 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
688 if (!t->trace->startfound)
690 t->trace->startfound = true;
691 t->trace->startsupercontents |= num;
693 if (num & SUPERCONTENTS_LIQUIDSMASK)
694 t->trace->inwater = true;
696 t->trace->inopen = true;
697 if (num & SUPERCONTENTS_SOLID)
698 t->trace->hittexture = &mod_q1bsp_texture_solid;
699 else if (num & SUPERCONTENTS_SKY)
700 t->trace->hittexture = &mod_q1bsp_texture_sky;
701 else if (num & SUPERCONTENTS_LAVA)
702 t->trace->hittexture = &mod_q1bsp_texture_lava;
703 else if (num & SUPERCONTENTS_SLIME)
704 t->trace->hittexture = &mod_q1bsp_texture_slime;
706 t->trace->hittexture = &mod_q1bsp_texture_water;
707 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
708 t->trace->hitsupercontents = num;
709 if (num & t->trace->hitsupercontentsmask)
711 // if the first leaf is solid, set startsolid
712 if (t->trace->allsolid)
713 t->trace->startsolid = true;
714 #if COLLISIONPARANOID >= 3
717 return HULLCHECKSTATE_SOLID;
721 t->trace->allsolid = false;
722 #if COLLISIONPARANOID >= 3
725 return HULLCHECKSTATE_EMPTY;
729 // find the point distances
730 node = t->hull->clipnodes + num;
732 plane = t->hull->planes + node->planenum;
735 t1 = p1[plane->type] - plane->dist;
736 t2 = p2[plane->type] - plane->dist;
740 t1 = DotProduct (plane->normal, p1) - plane->dist;
741 t2 = DotProduct (plane->normal, p2) - plane->dist;
748 #if COLLISIONPARANOID >= 3
751 num = node->children[1];
760 #if COLLISIONPARANOID >= 3
763 num = node->children[0];
769 // the line intersects, find intersection point
770 // LordHavoc: this uses the original trace for maximum accuracy
771 #if COLLISIONPARANOID >= 3
776 t1 = t->start[plane->type] - plane->dist;
777 t2 = t->end[plane->type] - plane->dist;
781 t1 = DotProduct (plane->normal, t->start) - plane->dist;
782 t2 = DotProduct (plane->normal, t->end) - plane->dist;
785 midf = t1 / (t1 - t2);
786 midf = bound(p1f, midf, p2f);
787 VectorMA(t->start, midf, t->dist, mid);
789 // recurse both sides, front side first
790 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
791 // if this side is not empty, return what it is (solid or done)
792 if (ret != HULLCHECKSTATE_EMPTY)
795 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
796 // if other side is not solid, return what it is (empty or done)
797 if (ret != HULLCHECKSTATE_SOLID)
800 // front is air and back is solid, this is the impact point...
803 t->trace->plane.dist = -plane->dist;
804 VectorNegate (plane->normal, t->trace->plane.normal);
808 t->trace->plane.dist = plane->dist;
809 VectorCopy (plane->normal, t->trace->plane.normal);
812 // calculate the true fraction
813 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
814 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
815 midf = t1 / (t1 - t2);
816 t->trace->realfraction = bound(0, midf, 1);
818 // calculate the return fraction which is nudged off the surface a bit
819 midf = (t1 - DIST_EPSILON) / (t1 - t2);
820 t->trace->fraction = bound(0, midf, 1);
822 if (collision_prefernudgedfraction.integer)
823 t->trace->realfraction = t->trace->fraction;
825 #if COLLISIONPARANOID >= 3
828 return HULLCHECKSTATE_DONE;
831 //#if COLLISIONPARANOID < 2
832 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
835 mclipnode_t *nodes = t->hull->clipnodes;
836 mplane_t *planes = t->hull->planes;
838 VectorCopy(t->start, point);
841 plane = planes + nodes[num].planenum;
842 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
844 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
845 t->trace->startsupercontents |= num;
846 if (num & SUPERCONTENTS_LIQUIDSMASK)
847 t->trace->inwater = true;
849 t->trace->inopen = true;
850 if (num & t->trace->hitsupercontentsmask)
852 t->trace->allsolid = t->trace->startsolid = true;
853 return HULLCHECKSTATE_SOLID;
857 t->trace->allsolid = t->trace->startsolid = false;
858 return HULLCHECKSTATE_EMPTY;
863 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)
865 RecursiveHullCheckTraceInfo_t rhc;
867 memset(&rhc, 0, sizeof(rhc));
868 memset(trace, 0, sizeof(trace_t));
870 rhc.trace->fraction = 1;
871 rhc.trace->realfraction = 1;
872 rhc.trace->allsolid = true;
873 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
874 VectorCopy(start, rhc.start);
875 VectorCopy(start, rhc.end);
876 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
879 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)
881 RecursiveHullCheckTraceInfo_t rhc;
883 if (VectorCompare(start, end))
885 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
889 memset(&rhc, 0, sizeof(rhc));
890 memset(trace, 0, sizeof(trace_t));
892 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
893 rhc.trace->fraction = 1;
894 rhc.trace->realfraction = 1;
895 rhc.trace->allsolid = true;
896 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
897 VectorCopy(start, rhc.start);
898 VectorCopy(end, rhc.end);
899 VectorSubtract(rhc.end, rhc.start, rhc.dist);
900 #if COLLISIONPARANOID >= 2
901 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]);
902 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
907 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
908 memset(&testtrace, 0, sizeof(trace_t));
909 rhc.trace = &testtrace;
910 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
911 rhc.trace->fraction = 1;
912 rhc.trace->realfraction = 1;
913 rhc.trace->allsolid = true;
914 VectorCopy(test, rhc.start);
915 VectorCopy(test, rhc.end);
916 VectorClear(rhc.dist);
917 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
918 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
919 if (!trace->startsolid && testtrace.startsolid)
920 Con_Printf(" - ended in solid!\n");
924 if (VectorLength2(rhc.dist))
925 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
927 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
931 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)
933 // this function currently only supports same size start and end
935 RecursiveHullCheckTraceInfo_t rhc;
937 if (VectorCompare(boxmins, boxmaxs))
939 if (VectorCompare(start, end))
940 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
942 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
946 memset(&rhc, 0, sizeof(rhc));
947 memset(trace, 0, sizeof(trace_t));
949 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
950 rhc.trace->fraction = 1;
951 rhc.trace->realfraction = 1;
952 rhc.trace->allsolid = true;
953 VectorSubtract(boxmaxs, boxmins, boxsize);
955 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
956 else if (model->brush.ishlbsp)
958 // LordHavoc: this has to have a minor tolerance (the .1) because of
959 // minor float precision errors from the box being transformed around
960 if (boxsize[0] < 32.1)
962 if (boxsize[2] < 54) // pick the nearest of 36 or 72
963 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
965 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
968 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
972 // LordHavoc: this has to have a minor tolerance (the .1) because of
973 // minor float precision errors from the box being transformed around
974 if (boxsize[0] < 32.1)
975 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
977 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
979 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
980 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
981 VectorSubtract(rhc.end, rhc.start, rhc.dist);
982 #if COLLISIONPARANOID >= 2
983 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]);
984 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
989 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
990 memset(&testtrace, 0, sizeof(trace_t));
991 rhc.trace = &testtrace;
992 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
993 rhc.trace->fraction = 1;
994 rhc.trace->realfraction = 1;
995 rhc.trace->allsolid = true;
996 VectorCopy(test, rhc.start);
997 VectorCopy(test, rhc.end);
998 VectorClear(rhc.dist);
999 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1000 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1001 if (!trace->startsolid && testtrace.startsolid)
1002 Con_Printf(" - ended in solid!\n");
1006 if (VectorLength2(rhc.dist))
1007 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1009 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1013 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1015 int num = model->brushq1.hulls[0].firstclipnode;
1017 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1018 mplane_t *planes = model->brushq1.hulls[0].planes;
1021 plane = planes + nodes[num].planenum;
1022 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1024 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1027 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)
1031 colplanef_t cbox_planes[6];
1033 cbox.hasaabbplanes = true;
1034 cbox.supercontents = boxsupercontents;
1037 cbox.numtriangles = 0;
1038 cbox.planes = cbox_planes;
1040 cbox.elements = NULL;
1048 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];
1049 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];
1050 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];
1051 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];
1052 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];
1053 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];
1054 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1055 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1056 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1057 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1058 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1059 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1060 memset(trace, 0, sizeof(trace_t));
1061 trace->hitsupercontentsmask = hitsupercontentsmask;
1062 trace->fraction = 1;
1063 trace->realfraction = 1;
1064 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1066 RecursiveHullCheckTraceInfo_t rhc;
1067 static hull_t box_hull;
1068 static mclipnode_t box_clipnodes[6];
1069 static mplane_t box_planes[6];
1070 // fill in a default trace
1071 memset(&rhc, 0, sizeof(rhc));
1072 memset(trace, 0, sizeof(trace_t));
1073 //To keep everything totally uniform, bounding boxes are turned into small
1074 //BSP trees instead of being compared directly.
1075 // create a temp hull from bounding box sizes
1076 box_planes[0].dist = cmaxs[0] - mins[0];
1077 box_planes[1].dist = cmins[0] - maxs[0];
1078 box_planes[2].dist = cmaxs[1] - mins[1];
1079 box_planes[3].dist = cmins[1] - maxs[1];
1080 box_planes[4].dist = cmaxs[2] - mins[2];
1081 box_planes[5].dist = cmins[2] - maxs[2];
1082 #if COLLISIONPARANOID >= 3
1083 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]);
1086 if (box_hull.clipnodes == NULL)
1090 //Set up the planes and clipnodes so that the six floats of a bounding box
1091 //can just be stored out and get a proper hull_t structure.
1093 box_hull.clipnodes = box_clipnodes;
1094 box_hull.planes = box_planes;
1095 box_hull.firstclipnode = 0;
1096 box_hull.lastclipnode = 5;
1098 for (i = 0;i < 6;i++)
1100 box_clipnodes[i].planenum = i;
1104 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1106 box_clipnodes[i].children[side^1] = i + 1;
1108 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1110 box_planes[i].type = i>>1;
1111 box_planes[i].normal[i>>1] = 1;
1115 // trace a line through the generated clipping hull
1116 //rhc.boxsupercontents = boxsupercontents;
1117 rhc.hull = &box_hull;
1119 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1120 rhc.trace->fraction = 1;
1121 rhc.trace->realfraction = 1;
1122 rhc.trace->allsolid = true;
1123 VectorCopy(start, rhc.start);
1124 VectorCopy(end, rhc.end);
1125 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1126 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1127 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1128 if (rhc.trace->startsupercontents)
1129 rhc.trace->startsupercontents = boxsupercontents;
1133 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)
1135 memset(trace, 0, sizeof(trace_t));
1136 trace->fraction = 1;
1137 trace->realfraction = 1;
1138 if (BoxesOverlap(start, start, cmins, cmaxs))
1140 trace->startsupercontents |= boxsupercontents;
1141 if (hitsupercontentsmask & boxsupercontents)
1143 trace->startsolid = true;
1144 trace->allsolid = true;
1149 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1152 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1153 return trace.fraction == 1;
1156 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)
1160 float mid, distz = endz - startz;
1164 return false; // didn't hit anything
1166 switch (node->plane->type)
1169 node = node->children[x < node->plane->dist];
1172 node = node->children[y < node->plane->dist];
1175 side = startz < node->plane->dist;
1176 if ((endz < node->plane->dist) == side)
1178 node = node->children[side];
1181 // found an intersection
1182 mid = node->plane->dist;
1185 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1186 front += startz * node->plane->normal[2];
1187 back += endz * node->plane->normal[2];
1188 side = front < node->plane->dist;
1189 if ((back < node->plane->dist) == side)
1191 node = node->children[side];
1194 // found an intersection
1195 mid = startz + distz * (front - node->plane->dist) / (front - back);
1199 // go down front side
1200 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1201 return true; // hit something
1204 // check for impact on this node
1205 if (node->numsurfaces)
1207 int i, dsi, dti, lmwidth, lmheight;
1209 msurface_t *surface;
1210 unsigned char *lightmap;
1211 int maps, line3, size3;
1214 float scale, w, w00, w01, w10, w11;
1216 surface = model->data_surfaces + node->firstsurface;
1217 for (i = 0;i < node->numsurfaces;i++, surface++)
1219 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1220 continue; // no lightmaps
1222 // location we want to sample in the lightmap
1223 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;
1224 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;
1229 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1230 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1233 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1235 // calculate bilinear interpolation factors
1236 // and also multiply by fixedpoint conversion factors
1239 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1240 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1241 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1242 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1244 // values for pointer math
1245 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1246 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1248 // look up the pixel
1249 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1251 // bilinear filter each lightmap style, and sum them
1252 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1254 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1255 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1256 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1257 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1258 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1262 return true; // success
1267 // go down back side
1268 node = node->children[side ^ 1];
1270 distz = endz - startz;
1275 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1277 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1278 VectorSet(diffusenormal, 0, 0, 1);
1280 if (!model->brushq1.lightdata)
1282 VectorSet(ambientcolor, 1, 1, 1);
1283 VectorSet(diffusecolor, 0, 0, 0);
1287 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);
1290 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1293 unsigned char *outstart = out;
1294 while (out < outend)
1298 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));
1308 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));
1311 for (c = *in++;c > 0;c--)
1315 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));
1326 R_Q1BSP_LoadSplitSky
1328 A sky texture is 256*128, with the right side being a masked overlay
1331 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1336 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1337 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1339 // allocate a texture pool if we need it
1340 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1341 loadmodel->texturepool = R_AllocTexturePool();
1343 if (bytesperpixel == 4)
1345 for (y = 0;y < h;y++)
1347 for (x = 0;x < w;x++)
1349 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1350 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1356 // make an average value for the back to avoid
1357 // a fringe on the top level
1366 for (y = 0;y < h;y++)
1368 for (x = 0;x < w;x++)
1370 p = src[x*width+y+w];
1371 r += palette_rgb[p][0];
1372 g += palette_rgb[p][1];
1373 b += palette_rgb[p][2];
1376 bgra.b[2] = r/(w*h);
1377 bgra.b[1] = g/(w*h);
1378 bgra.b[0] = b/(w*h);
1380 for (y = 0;y < h;y++)
1382 for (x = 0;x < w;x++)
1384 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1386 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1391 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h);
1392 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h);
1393 Mem_Free(solidpixels);
1394 Mem_Free(alphapixels);
1397 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1399 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1400 skinframe_t *skinframe;
1402 texture_t *tx, *tx2, *anims[10], *altanims[10];
1404 unsigned char *data, *mtdata;
1406 char mapname[MAX_QPATH], name[MAX_QPATH];
1407 unsigned char zero[4];
1409 memset(zero, 0, sizeof(zero));
1411 loadmodel->data_textures = NULL;
1413 // add two slots for notexture walls and notexture liquids
1416 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1417 m->nummiptex = LittleLong (m->nummiptex);
1418 loadmodel->num_textures = m->nummiptex + 2;
1419 loadmodel->num_texturesperskin = loadmodel->num_textures;
1424 loadmodel->num_textures = 2;
1425 loadmodel->num_texturesperskin = loadmodel->num_textures;
1428 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1430 // fill out all slots with notexture
1431 if (cls.state != ca_dedicated)
1432 skinframe = R_SkinFrame_LoadMissing();
1435 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1437 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1440 if (cls.state != ca_dedicated)
1442 tx->numskinframes = 1;
1443 tx->skinframerate = 1;
1444 tx->skinframes[0] = skinframe;
1445 tx->currentskinframe = tx->skinframes[0];
1447 tx->basematerialflags = MATERIALFLAG_WALL;
1448 if (i == loadmodel->num_textures - 1)
1450 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1451 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1452 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1456 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1457 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1459 tx->currentframe = tx;
1461 // clear water settings
1464 tx->refractfactor = 1;
1465 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1466 tx->reflectfactor = 1;
1467 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1468 tx->r_water_wateralpha = 1;
1469 tx->offsetmapping = OFFSETMAPPING_OFF;
1470 tx->offsetscale = 1;
1471 tx->specularscalemod = 1;
1472 tx->specularpowermod = 1;
1477 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1481 s = loadmodel->name;
1482 if (!strncasecmp(s, "maps/", 5))
1484 FS_StripExtension(s, mapname, sizeof(mapname));
1486 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1488 // LordHavoc: mostly rewritten map texture loader
1489 for (i = 0;i < m->nummiptex;i++)
1491 dofs[i] = LittleLong(dofs[i]);
1492 if (r_nosurftextures.integer)
1496 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1499 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1501 // copy name, but only up to 16 characters
1502 // (the output buffer can hold more than this, but the input buffer is
1504 for (j = 0;j < 16 && dmiptex->name[j];j++)
1505 name[j] = dmiptex->name[j];
1510 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1511 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1514 mtwidth = LittleLong(dmiptex->width);
1515 mtheight = LittleLong(dmiptex->height);
1517 j = LittleLong(dmiptex->offsets[0]);
1521 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1523 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1526 mtdata = (unsigned char *)dmiptex + j;
1529 if ((mtwidth & 15) || (mtheight & 15))
1530 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1532 // LordHavoc: force all names to lowercase
1533 for (j = 0;name[j];j++)
1534 if (name[j] >= 'A' && name[j] <= 'Z')
1535 name[j] += 'a' - 'A';
1537 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1540 tx = loadmodel->data_textures + i;
1541 strlcpy(tx->name, name, sizeof(tx->name));
1542 tx->width = mtwidth;
1543 tx->height = mtheight;
1545 if (tx->name[0] == '*')
1547 if (!strncmp(tx->name, "*lava", 5))
1549 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1550 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1552 else if (!strncmp(tx->name, "*slime", 6))
1554 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1555 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1559 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1560 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1563 else if (!strncmp(tx->name, "sky", 3))
1565 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1566 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1570 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1571 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1574 if (cls.state != ca_dedicated)
1576 // LordHavoc: HL sky textures are entirely different than quake
1577 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1579 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), false, false, r_texture_convertsRGB_skin.integer != 0, NULL);
1581 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), false, false, r_texture_convertsRGB_skin.integer != 0, NULL);
1582 if (data && image_width == image_height * 2)
1584 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1587 else if (mtdata != NULL)
1588 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1592 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);
1594 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);
1597 // did not find external texture, load it from the bsp or wad3
1598 if (loadmodel->brush.ishlbsp)
1600 // internal texture overrides wad
1601 unsigned char *pixels, *freepixels;
1602 pixels = freepixels = NULL;
1604 pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1606 pixels = freepixels = W_GetTextureBGRA(tx->name);
1609 tx->width = image_width;
1610 tx->height = image_height;
1611 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height);
1614 Mem_Free(freepixels);
1616 else if (mtdata) // texture included
1617 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1619 // if skinframe is still NULL the "missing" texture will be used
1621 tx->skinframes[0] = skinframe;
1624 tx->basematerialflags = MATERIALFLAG_WALL;
1625 if (tx->name[0] == '*')
1627 // LordHavoc: some turbulent textures should not be affected by wateralpha
1628 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1630 // replace the texture with transparent black
1631 Vector4Set(zero, 128, 128, 128, 128);
1632 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zero, 1, 1);
1633 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1635 else if (!strncmp(tx->name,"*lava",5)
1636 || !strncmp(tx->name,"*teleport",9)
1637 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1638 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1640 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1641 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1642 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1644 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1646 // replace the texture with black
1647 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zero, 1, 1);
1648 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1650 else if (!strncmp(tx->name, "sky", 3))
1651 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1652 else if (!strcmp(tx->name, "caulk"))
1653 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1654 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1655 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1657 // start out with no animation
1658 tx->currentframe = tx;
1659 tx->currentskinframe = tx->skinframes[0];
1663 // sequence the animations
1664 for (i = 0;i < m->nummiptex;i++)
1666 tx = loadmodel->data_textures + i;
1667 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1669 if (tx->anim_total[0] || tx->anim_total[1])
1670 continue; // already sequenced
1672 // find the number of frames in the animation
1673 memset(anims, 0, sizeof(anims));
1674 memset(altanims, 0, sizeof(altanims));
1676 for (j = i;j < m->nummiptex;j++)
1678 tx2 = loadmodel->data_textures + j;
1679 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1683 if (num >= '0' && num <= '9')
1684 anims[num - '0'] = tx2;
1685 else if (num >= 'a' && num <= 'j')
1686 altanims[num - 'a'] = tx2;
1688 Con_Printf("Bad animating texture %s\n", tx->name);
1692 for (j = 0;j < 10;j++)
1699 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1702 for (j = 0;j < max;j++)
1706 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1710 for (j = 0;j < altmax;j++)
1714 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1723 // if there is no alternate animation, duplicate the primary
1724 // animation into the alternate
1726 for (k = 0;k < 10;k++)
1727 altanims[k] = anims[k];
1730 // link together the primary animation
1731 for (j = 0;j < max;j++)
1734 tx2->animated = true;
1735 tx2->anim_total[0] = max;
1736 tx2->anim_total[1] = altmax;
1737 for (k = 0;k < 10;k++)
1739 tx2->anim_frames[0][k] = anims[k];
1740 tx2->anim_frames[1][k] = altanims[k];
1744 // if there really is an alternate anim...
1745 if (anims[0] != altanims[0])
1747 // link together the alternate animation
1748 for (j = 0;j < altmax;j++)
1751 tx2->animated = true;
1752 // the primary/alternate are reversed here
1753 tx2->anim_total[0] = altmax;
1754 tx2->anim_total[1] = max;
1755 for (k = 0;k < 10;k++)
1757 tx2->anim_frames[0][k] = altanims[k];
1758 tx2->anim_frames[1][k] = anims[k];
1765 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1768 unsigned char *in, *out, *data, d;
1769 char litfilename[MAX_QPATH];
1770 char dlitfilename[MAX_QPATH];
1771 fs_offset_t filesize;
1772 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1774 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1775 for (i=0; i<l->filelen; i++)
1776 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1778 else // LordHavoc: bsp version 29 (normal white lighting)
1780 // LordHavoc: hope is not lost yet, check for a .lit file to load
1781 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1782 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1783 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1784 strlcat (litfilename, ".lit", sizeof (litfilename));
1785 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1786 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1789 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1791 i = LittleLong(((int *)data)[1]);
1794 if (developer_loading.integer)
1795 Con_Printf("loaded %s\n", litfilename);
1796 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1797 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1799 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1802 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1804 i = LittleLong(((int *)data)[1]);
1807 if (developer_loading.integer)
1808 Con_Printf("loaded %s\n", dlitfilename);
1809 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1810 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
1811 loadmodel->brushq3.deluxemapping_modelspace = false;
1812 loadmodel->brushq3.deluxemapping = true;
1821 Con_Printf("Unknown .lit file version (%d)\n", i);
1823 else if (filesize == 8)
1824 Con_Print("Empty .lit file, ignoring\n");
1826 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
1833 // LordHavoc: oh well, expand the white lighting data
1836 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1837 in = mod_base + l->fileofs;
1838 out = loadmodel->brushq1.lightdata;
1839 for (i = 0;i < l->filelen;i++)
1849 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1851 loadmodel->brushq1.num_compressedpvs = 0;
1852 loadmodel->brushq1.data_compressedpvs = NULL;
1855 loadmodel->brushq1.num_compressedpvs = l->filelen;
1856 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1857 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1860 // used only for HalfLife maps
1861 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1863 char key[128], value[4096];
1867 if (!COM_ParseToken_Simple(&data, false, false))
1869 if (com_token[0] != '{')
1873 if (!COM_ParseToken_Simple(&data, false, false))
1875 if (com_token[0] == '}')
1876 break; // end of worldspawn
1877 if (com_token[0] == '_')
1878 strlcpy(key, com_token + 1, sizeof(key));
1880 strlcpy(key, com_token, sizeof(key));
1881 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1882 key[strlen(key)-1] = 0;
1883 if (!COM_ParseToken_Simple(&data, false, false))
1885 dpsnprintf(value, sizeof(value), "%s", com_token);
1886 if (!strcmp("wad", key)) // for HalfLife maps
1888 if (loadmodel->brush.ishlbsp)
1891 for (i = 0;i < (int)sizeof(value);i++)
1892 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1896 for (;i < (int)sizeof(value);i++)
1898 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1899 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1901 else if (value[i] == ';' || value[i] == 0)
1905 W_LoadTextureWadFile(&value[j], false);
1917 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1919 loadmodel->brush.entities = NULL;
1922 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
1923 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1924 loadmodel->brush.entities[l->filelen] = 0;
1925 if (loadmodel->brush.ishlbsp)
1926 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1930 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1936 in = (dvertex_t *)(mod_base + l->fileofs);
1937 if (l->filelen % sizeof(*in))
1938 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1939 count = l->filelen / sizeof(*in);
1940 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1942 loadmodel->brushq1.vertexes = out;
1943 loadmodel->brushq1.numvertexes = count;
1945 for ( i=0 ; i<count ; i++, in++, out++)
1947 out->position[0] = LittleFloat(in->point[0]);
1948 out->position[1] = LittleFloat(in->point[1]);
1949 out->position[2] = LittleFloat(in->point[2]);
1953 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1954 // can be used for this
1956 int SB_ReadInt (unsigned char **buffer)
1959 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1965 float SB_ReadFloat (unsigned char **buffer)
1973 u.i = SB_ReadInt (buffer);
1977 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1979 unsigned char *index;
1983 index = (unsigned char *)(mod_base + l->fileofs);
1984 if (l->filelen % (48+4*hullinfo->filehulls))
1985 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1987 count = l->filelen / (48+4*hullinfo->filehulls);
1988 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1990 loadmodel->brushq1.submodels = out;
1991 loadmodel->brush.numsubmodels = count;
1993 for (i = 0; i < count; i++, out++)
1995 // spread out the mins / maxs by a pixel
1996 out->mins[0] = SB_ReadFloat (&index) - 1;
1997 out->mins[1] = SB_ReadFloat (&index) - 1;
1998 out->mins[2] = SB_ReadFloat (&index) - 1;
1999 out->maxs[0] = SB_ReadFloat (&index) + 1;
2000 out->maxs[1] = SB_ReadFloat (&index) + 1;
2001 out->maxs[2] = SB_ReadFloat (&index) + 1;
2002 out->origin[0] = SB_ReadFloat (&index);
2003 out->origin[1] = SB_ReadFloat (&index);
2004 out->origin[2] = SB_ReadFloat (&index);
2005 for (j = 0; j < hullinfo->filehulls; j++)
2006 out->headnode[j] = SB_ReadInt (&index);
2007 out->visleafs = SB_ReadInt (&index);
2008 out->firstface = SB_ReadInt (&index);
2009 out->numfaces = SB_ReadInt (&index);
2013 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2019 in = (dedge_t *)(mod_base + l->fileofs);
2020 if (l->filelen % sizeof(*in))
2021 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2022 count = l->filelen / sizeof(*in);
2023 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2025 loadmodel->brushq1.edges = out;
2026 loadmodel->brushq1.numedges = count;
2028 for ( i=0 ; i<count ; i++, in++, out++)
2030 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2031 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2032 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2034 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);
2035 if(!loadmodel->brushq1.numvertexes)
2036 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2044 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2048 int i, j, k, count, miptex;
2050 in = (texinfo_t *)(mod_base + l->fileofs);
2051 if (l->filelen % sizeof(*in))
2052 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2053 count = l->filelen / sizeof(*in);
2054 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2056 loadmodel->brushq1.texinfo = out;
2057 loadmodel->brushq1.numtexinfo = count;
2059 for (i = 0;i < count;i++, in++, out++)
2061 for (k = 0;k < 2;k++)
2062 for (j = 0;j < 4;j++)
2063 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2065 miptex = LittleLong(in->miptex);
2066 out->flags = LittleLong(in->flags);
2068 out->texture = NULL;
2069 if (loadmodel->data_textures)
2071 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2072 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2074 out->texture = loadmodel->data_textures + miptex;
2076 if (out->flags & TEX_SPECIAL)
2078 // if texture chosen is NULL or the shader needs a lightmap,
2079 // force to notexture water shader
2080 if (out->texture == NULL)
2081 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2085 // if texture chosen is NULL, force to notexture
2086 if (out->texture == NULL)
2087 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2093 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2098 mins[0] = mins[1] = mins[2] = 9999;
2099 maxs[0] = maxs[1] = maxs[2] = -9999;
2101 for (i = 0;i < numverts;i++)
2103 for (j = 0;j < 3;j++, v++)
2113 #define MAX_SUBDIVPOLYTRIANGLES 4096
2114 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2116 static int subdivpolyverts, subdivpolytriangles;
2117 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2118 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2120 static int subdivpolylookupvert(vec3_t v)
2123 for (i = 0;i < subdivpolyverts;i++)
2124 if (subdivpolyvert[i][0] == v[0]
2125 && subdivpolyvert[i][1] == v[1]
2126 && subdivpolyvert[i][2] == v[2])
2128 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2129 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2130 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2131 return subdivpolyverts++;
2134 static void SubdividePolygon(int numverts, float *verts)
2136 int i, i1, i2, i3, f, b, c, p;
2137 vec3_t mins, maxs, front[256], back[256];
2138 float m, *pv, *cv, dist[256], frac;
2141 Host_Error("SubdividePolygon: ran out of verts in buffer");
2143 BoundPoly(numverts, verts, mins, maxs);
2145 for (i = 0;i < 3;i++)
2147 m = (mins[i] + maxs[i]) * 0.5;
2148 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2149 if (maxs[i] - m < 8)
2151 if (m - mins[i] < 8)
2155 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2156 dist[c] = cv[i] - m;
2159 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2163 VectorCopy(pv, front[f]);
2168 VectorCopy(pv, back[b]);
2171 if (dist[p] == 0 || dist[c] == 0)
2173 if ((dist[p] > 0) != (dist[c] > 0) )
2176 frac = dist[p] / (dist[p] - dist[c]);
2177 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2178 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2179 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2185 SubdividePolygon(f, front[0]);
2186 SubdividePolygon(b, back[0]);
2190 i1 = subdivpolylookupvert(verts);
2191 i2 = subdivpolylookupvert(verts + 3);
2192 for (i = 2;i < numverts;i++)
2194 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2196 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2200 i3 = subdivpolylookupvert(verts + i * 3);
2201 subdivpolyindex[subdivpolytriangles][0] = i1;
2202 subdivpolyindex[subdivpolytriangles][1] = i2;
2203 subdivpolyindex[subdivpolytriangles][2] = i3;
2205 subdivpolytriangles++;
2209 //Breaks a polygon up along axial 64 unit
2210 //boundaries so that turbulent and sky warps
2211 //can be done reasonably.
2212 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2218 subdivpolytriangles = 0;
2219 subdivpolyverts = 0;
2220 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2221 if (subdivpolytriangles < 1)
2222 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2224 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2225 mesh->num_vertices = subdivpolyverts;
2226 mesh->num_triangles = subdivpolytriangles;
2227 mesh->vertex = (surfvertex_t *)(mesh + 1);
2228 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2229 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2231 for (i = 0;i < mesh->num_triangles;i++)
2232 for (j = 0;j < 3;j++)
2233 mesh->index[i*3+j] = subdivpolyindex[i][j];
2235 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2237 VectorCopy(subdivpolyvert[i], v->v);
2238 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2239 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2244 extern cvar_t gl_max_lightmapsize;
2245 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2248 msurface_t *surface;
2249 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2250 float texmins[2], texmaxs[2], val;
2251 rtexture_t *lightmaptexture, *deluxemaptexture;
2253 in = (dface_t *)(mod_base + l->fileofs);
2254 if (l->filelen % sizeof(*in))
2255 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2256 count = l->filelen / sizeof(*in);
2257 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2258 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2260 loadmodel->num_surfaces = count;
2262 loadmodel->brushq1.firstrender = true;
2263 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2267 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2269 numedges = (unsigned short)LittleShort(in->numedges);
2270 totalverts += numedges;
2271 totaltris += numedges - 2;
2274 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2276 lightmaptexture = NULL;
2277 deluxemaptexture = r_texture_blanknormalmap;
2279 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2280 totallightmapsamples = 0;
2284 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2286 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2288 // FIXME: validate edges, texinfo, etc?
2289 firstedge = LittleLong(in->firstedge);
2290 numedges = (unsigned short)LittleShort(in->numedges);
2291 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)
2292 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2293 i = (unsigned short)LittleShort(in->texinfo);
2294 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2295 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2296 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2297 surface->texture = surface->lightmapinfo->texinfo->texture;
2299 planenum = (unsigned short)LittleShort(in->planenum);
2300 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2301 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2303 //surface->flags = surface->texture->flags;
2304 //if (LittleShort(in->side))
2305 // surface->flags |= SURF_PLANEBACK;
2306 //surface->plane = loadmodel->brush.data_planes + planenum;
2308 surface->num_firstvertex = totalverts;
2309 surface->num_vertices = numedges;
2310 surface->num_firsttriangle = totaltris;
2311 surface->num_triangles = numedges - 2;
2312 totalverts += numedges;
2313 totaltris += numedges - 2;
2315 // convert edges back to a normal polygon
2316 for (i = 0;i < surface->num_vertices;i++)
2318 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2320 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2322 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2324 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2325 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2326 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2327 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2328 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2329 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2330 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2331 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2334 for (i = 0;i < surface->num_triangles;i++)
2336 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2337 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2338 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2341 // compile additional data about the surface geometry
2342 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, true);
2343 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, true);
2344 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2346 // generate surface extents information
2347 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2348 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2349 for (i = 1;i < surface->num_vertices;i++)
2351 for (j = 0;j < 2;j++)
2353 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2354 texmins[j] = min(texmins[j], val);
2355 texmaxs[j] = max(texmaxs[j], val);
2358 for (i = 0;i < 2;i++)
2360 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2361 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2364 smax = surface->lightmapinfo->extents[0] >> 4;
2365 tmax = surface->lightmapinfo->extents[1] >> 4;
2366 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2367 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2370 for (i = 0;i < MAXLIGHTMAPS;i++)
2371 surface->lightmapinfo->styles[i] = in->styles[i];
2372 surface->lightmaptexture = NULL;
2373 surface->deluxemaptexture = r_texture_blanknormalmap;
2374 i = LittleLong(in->lightofs);
2377 surface->lightmapinfo->samples = NULL;
2379 // give non-lightmapped water a 1x white lightmap
2380 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2382 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2383 surface->lightmapinfo->styles[0] = 0;
2384 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2388 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2389 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2390 else // LordHavoc: white lighting (bsp version 29)
2392 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2393 if (loadmodel->brushq1.nmaplightdata)
2394 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2397 // check if we should apply a lightmap to this
2398 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2400 if (ssize > 256 || tsize > 256)
2401 Host_Error("Bad surface extents");
2403 if (lightmapsize < ssize)
2404 lightmapsize = ssize;
2405 if (lightmapsize < tsize)
2406 lightmapsize = tsize;
2408 totallightmapsamples += ssize*tsize;
2410 // force lightmap upload on first time seeing the surface
2412 // additionally this is used by the later code to see if a
2413 // lightmap is needed on this surface (rather than duplicating the
2415 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2416 loadmodel->lit = true;
2420 // small maps (such as ammo boxes especially) don't need big lightmap
2421 // textures, so this code tries to guess a good size based on
2422 // totallightmapsamples (size of the lightmaps lump basically), as well as
2423 // trying to max out the size if there is a lot of lightmap data to store
2424 // additionally, never choose a lightmapsize that is smaller than the
2425 // largest surface encountered (as it would fail)
2427 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2430 // now that we've decided the lightmap texture size, we can do the rest
2431 if (cls.state != ca_dedicated)
2433 int stainmapsize = 0;
2434 mod_alloclightmap_state_t allocState;
2436 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2437 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2439 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2440 float u, v, ubase, vbase, uscale, vscale;
2442 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2445 smax = surface->lightmapinfo->extents[0] >> 4;
2446 tmax = surface->lightmapinfo->extents[1] >> 4;
2447 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2448 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2449 stainmapsize += ssize * tsize * 3;
2451 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2453 // allocate a texture pool if we need it
2454 if (loadmodel->texturepool == NULL)
2455 loadmodel->texturepool = R_AllocTexturePool();
2456 // could not find room, make a new lightmap
2457 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2458 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2459 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2460 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);
2461 if (loadmodel->brushq1.nmaplightdata)
2462 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);
2464 Mod_AllocLightmap_Reset(&allocState);
2465 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2467 surface->lightmaptexture = lightmaptexture;
2468 surface->deluxemaptexture = deluxemaptexture;
2469 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2470 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2472 uscale = 1.0f / (float)lightmapsize;
2473 vscale = 1.0f / (float)lightmapsize;
2474 ubase = lightmapx * uscale;
2475 vbase = lightmapy * vscale;
2477 for (i = 0;i < surface->num_vertices;i++)
2479 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);
2480 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);
2481 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2482 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2483 // LordHavoc: calc lightmap data offset for vertex lighting to use
2486 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2490 if (cl_stainmaps.integer)
2492 // allocate stainmaps for permanent marks on walls and clear white
2493 unsigned char *stainsamples = NULL;
2494 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2495 memset(stainsamples, 255, stainmapsize);
2497 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2499 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2501 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2502 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2503 surface->lightmapinfo->stainsamples = stainsamples;
2504 stainsamples += ssize * tsize * 3;
2509 // generate ushort elements array if possible
2510 if (loadmodel->surfmesh.data_element3s)
2511 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2512 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2515 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2518 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2519 node->parent = parent;
2522 // this is a node, recurse to children
2523 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2524 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2525 // combine supercontents of children
2526 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2531 mleaf_t *leaf = (mleaf_t *)node;
2532 // if this is a leaf, calculate supercontents mask from all collidable
2533 // primitives in the leaf (brushes and collision surfaces)
2534 // also flag if the leaf contains any collision surfaces
2535 leaf->combinedsupercontents = 0;
2536 // combine the supercontents values of all brushes in this leaf
2537 for (j = 0;j < leaf->numleafbrushes;j++)
2538 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2539 // check if this leaf contains any collision surfaces (q3 patches)
2540 for (j = 0;j < leaf->numleafsurfaces;j++)
2542 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2543 if (surface->num_collisiontriangles)
2545 leaf->containscollisionsurfaces = true;
2546 leaf->combinedsupercontents |= surface->texture->supercontents;
2552 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2558 in = (dnode_t *)(mod_base + l->fileofs);
2559 if (l->filelen % sizeof(*in))
2560 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2561 count = l->filelen / sizeof(*in);
2562 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2564 loadmodel->brush.data_nodes = out;
2565 loadmodel->brush.num_nodes = count;
2567 for ( i=0 ; i<count ; i++, in++, out++)
2569 for (j=0 ; j<3 ; j++)
2571 out->mins[j] = LittleShort(in->mins[j]);
2572 out->maxs[j] = LittleShort(in->maxs[j]);
2575 p = LittleLong(in->planenum);
2576 out->plane = loadmodel->brush.data_planes + p;
2578 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2579 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2581 for (j=0 ; j<2 ; j++)
2583 // LordHavoc: this code supports broken bsp files produced by
2584 // arguire qbsp which can produce more than 32768 nodes, any value
2585 // below count is assumed to be a node number, any other value is
2586 // assumed to be a leaf number
2587 p = (unsigned short)LittleShort(in->children[j]);
2590 if (p < loadmodel->brush.num_nodes)
2591 out->children[j] = loadmodel->brush.data_nodes + p;
2594 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2595 // map it to the solid leaf
2596 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2601 // note this uses 65535 intentionally, -1 is leaf 0
2603 if (p < loadmodel->brush.num_leafs)
2604 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2607 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2608 // map it to the solid leaf
2609 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2615 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2618 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2624 in = (dleaf_t *)(mod_base + l->fileofs);
2625 if (l->filelen % sizeof(*in))
2626 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2627 count = l->filelen / sizeof(*in);
2628 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2630 loadmodel->brush.data_leafs = out;
2631 loadmodel->brush.num_leafs = count;
2632 // get visleafs from the submodel data
2633 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2634 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2635 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2636 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2638 for ( i=0 ; i<count ; i++, in++, out++)
2640 for (j=0 ; j<3 ; j++)
2642 out->mins[j] = LittleShort(in->mins[j]);
2643 out->maxs[j] = LittleShort(in->maxs[j]);
2646 // FIXME: this function could really benefit from some error checking
2648 out->contents = LittleLong(in->contents);
2650 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2651 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2652 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2654 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);
2655 out->firstleafsurface = NULL;
2656 out->numleafsurfaces = 0;
2659 out->clusterindex = i - 1;
2660 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2661 out->clusterindex = -1;
2663 p = LittleLong(in->visofs);
2664 // ignore visofs errors on leaf 0 (solid)
2665 if (p >= 0 && out->clusterindex >= 0)
2667 if (p >= loadmodel->brushq1.num_compressedpvs)
2668 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2670 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);
2673 for (j = 0;j < 4;j++)
2674 out->ambient_sound_level[j] = in->ambient_level[j];
2676 // FIXME: Insert caustics here
2680 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2684 const unsigned char *pvs;
2685 // if there's no vis data, assume supported (because everything is visible all the time)
2686 if (!loadmodel->brush.data_pvsclusters)
2688 // check all liquid leafs to see if they can see into empty leafs, if any
2689 // can we can assume this map supports r_wateralpha
2690 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2692 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2694 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2695 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2696 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2703 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2710 in = (dclipnode_t *)(mod_base + l->fileofs);
2711 if (l->filelen % sizeof(*in))
2712 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2713 count = l->filelen / sizeof(*in);
2714 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2716 loadmodel->brushq1.clipnodes = out;
2717 loadmodel->brushq1.numclipnodes = count;
2719 for (i = 1; i < MAX_MAP_HULLS; i++)
2721 hull = &loadmodel->brushq1.hulls[i];
2722 hull->clipnodes = out;
2723 hull->firstclipnode = 0;
2724 hull->lastclipnode = count-1;
2725 hull->planes = loadmodel->brush.data_planes;
2726 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2727 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2728 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2729 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2730 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2731 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2732 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2735 for (i=0 ; i<count ; i++, out++, in++)
2737 out->planenum = LittleLong(in->planenum);
2738 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2739 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2740 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2741 if (out->children[0] >= count)
2742 out->children[0] -= 65536;
2743 if (out->children[1] >= count)
2744 out->children[1] -= 65536;
2745 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2746 Host_Error("Corrupt clipping hull(out of range planenum)");
2750 //Duplicate the drawing hull structure as a clipping hull
2751 static void Mod_Q1BSP_MakeHull0(void)
2758 hull = &loadmodel->brushq1.hulls[0];
2760 in = loadmodel->brush.data_nodes;
2761 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2763 hull->clipnodes = out;
2764 hull->firstclipnode = 0;
2765 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2766 hull->planes = loadmodel->brush.data_planes;
2768 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2770 out->planenum = in->plane - loadmodel->brush.data_planes;
2771 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2772 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2776 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2781 in = (short *)(mod_base + l->fileofs);
2782 if (l->filelen % sizeof(*in))
2783 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2784 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2785 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2787 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2789 j = (unsigned short) LittleShort(in[i]);
2790 if (j >= loadmodel->num_surfaces)
2791 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2792 loadmodel->brush.data_leafsurfaces[i] = j;
2796 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2801 in = (int *)(mod_base + l->fileofs);
2802 if (l->filelen % sizeof(*in))
2803 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2804 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2805 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2807 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2808 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2812 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2818 in = (dplane_t *)(mod_base + l->fileofs);
2819 if (l->filelen % sizeof(*in))
2820 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2822 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2823 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2825 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2827 out->normal[0] = LittleFloat(in->normal[0]);
2828 out->normal[1] = LittleFloat(in->normal[1]);
2829 out->normal[2] = LittleFloat(in->normal[2]);
2830 out->dist = LittleFloat(in->dist);
2836 static void Mod_Q1BSP_LoadMapBrushes(void)
2840 int submodel, numbrushes;
2841 qboolean firstbrush;
2842 char *text, *maptext;
2843 char mapfilename[MAX_QPATH];
2844 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2845 strlcat (mapfilename, ".map", sizeof (mapfilename));
2846 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
2850 if (!COM_ParseToken_Simple(&data, false, false))
2855 if (!COM_ParseToken_Simple(&data, false, false))
2857 if (com_token[0] != '{')
2863 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2866 if (!COM_ParseToken_Simple(&data, false, false))
2868 if (com_token[0] == '}')
2869 break; // end of entity
2870 if (com_token[0] == '{')
2877 if (submodel > loadmodel->brush.numsubmodels)
2879 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2883 model = loadmodel->brush.submodels[submodel];
2890 if (!COM_ParseToken_Simple(&data, false, false))
2892 if (com_token[0] == '}')
2893 break; // end of brush
2894 // each brush face should be this format:
2895 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2896 // FIXME: support hl .map format
2897 for (pointnum = 0;pointnum < 3;pointnum++)
2899 COM_ParseToken_Simple(&data, false, false);
2900 for (componentnum = 0;componentnum < 3;componentnum++)
2902 COM_ParseToken_Simple(&data, false, false);
2903 point[pointnum][componentnum] = atof(com_token);
2905 COM_ParseToken_Simple(&data, false, false);
2907 COM_ParseToken_Simple(&data, false, false);
2908 strlcpy(facetexture, com_token, sizeof(facetexture));
2909 COM_ParseToken_Simple(&data, false, false);
2910 //scroll_s = atof(com_token);
2911 COM_ParseToken_Simple(&data, false, false);
2912 //scroll_t = atof(com_token);
2913 COM_ParseToken_Simple(&data, false, false);
2914 //rotate = atof(com_token);
2915 COM_ParseToken_Simple(&data, false, false);
2916 //scale_s = atof(com_token);
2917 COM_ParseToken_Simple(&data, false, false);
2918 //scale_t = atof(com_token);
2919 TriangleNormal(point[0], point[1], point[2], planenormal);
2920 VectorNormalizeDouble(planenormal);
2921 planedist = DotProduct(point[0], planenormal);
2922 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2932 #define MAX_PORTALPOINTS 64
2934 typedef struct portal_s
2937 mnode_t *nodes[2]; // [0] = front side of plane
2938 struct portal_s *next[2];
2940 double points[3*MAX_PORTALPOINTS];
2941 struct portal_s *chain; // all portals are linked into a list
2945 static memexpandablearray_t portalarray;
2947 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2949 // process only nodes (leafs already had their box calculated)
2953 // calculate children first
2954 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2955 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2957 // make combined bounding box from children
2958 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2959 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2960 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2961 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2962 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2963 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2966 static void Mod_Q1BSP_FinalizePortals(void)
2968 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
2972 mleaf_t *leaf, *endleaf;
2974 // tally up portal and point counts and recalculate bounding boxes for all
2975 // leafs (because qbsp is very sloppy)
2976 leaf = loadmodel->brush.data_leafs;
2977 endleaf = leaf + loadmodel->brush.num_leafs;
2978 if (mod_recalculatenodeboxes.integer)
2980 for (;leaf < endleaf;leaf++)
2982 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
2983 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2988 for (portalindex = 0;portalindex < portalrange;portalindex++)
2990 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
2993 // note: this check must match the one below or it will usually corrupt memory
2994 // 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
2995 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2998 numpoints += p->numpoints * 2;
3001 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3002 loadmodel->brush.num_portals = numportals;
3003 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3004 loadmodel->brush.num_portalpoints = numpoints;
3005 // clear all leaf portal chains
3006 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3007 loadmodel->brush.data_leafs[i].portals = NULL;
3008 // process all portals in the global portal chain, while freeing them
3009 portal = loadmodel->brush.data_portals;
3010 point = loadmodel->brush.data_portalpoints;
3011 for (portalindex = 0;portalindex < portalrange;portalindex++)
3013 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3016 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3018 // note: this check must match the one above or it will usually corrupt memory
3019 // 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
3020 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3022 // first make the back to front portal(forward portal)
3023 portal->points = point;
3024 portal->numpoints = p->numpoints;
3025 portal->plane.dist = p->plane.dist;
3026 VectorCopy(p->plane.normal, portal->plane.normal);
3027 portal->here = (mleaf_t *)p->nodes[1];
3028 portal->past = (mleaf_t *)p->nodes[0];
3030 for (j = 0;j < portal->numpoints;j++)
3032 VectorCopy(p->points + j*3, point->position);
3035 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3036 PlaneClassify(&portal->plane);
3038 // link into leaf's portal chain
3039 portal->next = portal->here->portals;
3040 portal->here->portals = portal;
3042 // advance to next portal
3045 // then make the front to back portal(backward portal)
3046 portal->points = point;
3047 portal->numpoints = p->numpoints;
3048 portal->plane.dist = -p->plane.dist;
3049 VectorNegate(p->plane.normal, portal->plane.normal);
3050 portal->here = (mleaf_t *)p->nodes[0];
3051 portal->past = (mleaf_t *)p->nodes[1];
3053 for (j = portal->numpoints - 1;j >= 0;j--)
3055 VectorCopy(p->points + j*3, point->position);
3058 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3059 PlaneClassify(&portal->plane);
3061 // link into leaf's portal chain
3062 portal->next = portal->here->portals;
3063 portal->here->portals = portal;
3065 // advance to next portal
3068 // add the portal's polygon points to the leaf bounding boxes
3069 if (mod_recalculatenodeboxes.integer)
3071 for (i = 0;i < 2;i++)
3073 leaf = (mleaf_t *)p->nodes[i];
3074 for (j = 0;j < p->numpoints;j++)
3076 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3077 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3078 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3079 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3080 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3081 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3087 // now recalculate the node bounding boxes from the leafs
3088 if (mod_recalculatenodeboxes.integer)
3089 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3097 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3100 Host_Error("AddPortalToNodes: NULL front node");
3102 Host_Error("AddPortalToNodes: NULL back node");
3103 if (p->nodes[0] || p->nodes[1])
3104 Host_Error("AddPortalToNodes: already included");
3105 // 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
3107 p->nodes[0] = front;
3108 p->next[0] = (portal_t *)front->portals;
3109 front->portals = (mportal_t *)p;
3112 p->next[1] = (portal_t *)back->portals;
3113 back->portals = (mportal_t *)p;
3118 RemovePortalFromNode
3121 static void RemovePortalFromNodes(portal_t *portal)
3125 void **portalpointer;
3127 for (i = 0;i < 2;i++)
3129 node = portal->nodes[i];
3131 portalpointer = (void **) &node->portals;
3134 t = (portal_t *)*portalpointer;
3136 Host_Error("RemovePortalFromNodes: portal not in leaf");
3140 if (portal->nodes[0] == node)
3142 *portalpointer = portal->next[0];
3143 portal->nodes[0] = NULL;
3145 else if (portal->nodes[1] == node)
3147 *portalpointer = portal->next[1];
3148 portal->nodes[1] = NULL;
3151 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3155 if (t->nodes[0] == node)
3156 portalpointer = (void **) &t->next[0];
3157 else if (t->nodes[1] == node)
3158 portalpointer = (void **) &t->next[1];
3160 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3165 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3166 static double *portalpointsbuffer;
3167 static int portalpointsbufferoffset;
3168 static int portalpointsbuffersize;
3169 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3172 mnode_t *front, *back, *other_node;
3173 mplane_t clipplane, *plane;
3174 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3175 int numfrontpoints, numbackpoints;
3176 double *frontpoints, *backpoints;
3178 // if a leaf, we're done
3182 // get some space for our clipping operations to use
3183 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3185 portalpointsbuffersize = portalpointsbufferoffset * 2;
3186 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3188 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3189 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3190 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3191 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3193 plane = node->plane;
3195 front = node->children[0];
3196 back = node->children[1];
3198 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3200 // create the new portal by generating a polygon for the node plane,
3201 // and clipping it by all of the other portals(which came from nodes above this one)
3202 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3203 nodeportal->plane = *plane;
3205 // 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)
3206 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);
3207 nodeportal->numpoints = 4;
3208 side = 0; // shut up compiler warning
3209 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3211 clipplane = portal->plane;
3212 if (portal->nodes[0] == portal->nodes[1])
3213 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3214 if (portal->nodes[0] == node)
3216 else if (portal->nodes[1] == node)
3218 clipplane.dist = -clipplane.dist;
3219 VectorNegate(clipplane.normal, clipplane.normal);
3223 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3225 for (i = 0;i < nodeportal->numpoints*3;i++)
3226 frontpoints[i] = nodeportal->points[i];
3227 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);
3228 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3232 if (nodeportal->numpoints < 3)
3234 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3235 nodeportal->numpoints = 0;
3237 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3239 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3240 nodeportal->numpoints = 0;
3243 AddPortalToNodes(nodeportal, front, back);
3245 // split the portals of this node along this node's plane and assign them to the children of this node
3246 // (migrating the portals downward through the tree)
3247 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3249 if (portal->nodes[0] == portal->nodes[1])
3250 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3251 if (portal->nodes[0] == node)
3253 else if (portal->nodes[1] == node)
3256 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3257 nextportal = portal->next[side];
3258 if (!portal->numpoints)
3261 other_node = portal->nodes[!side];
3262 RemovePortalFromNodes(portal);
3264 // cut the portal into two portals, one on each side of the node plane
3265 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);
3267 if (!numfrontpoints)
3270 AddPortalToNodes(portal, back, other_node);
3272 AddPortalToNodes(portal, other_node, back);
3278 AddPortalToNodes(portal, front, other_node);
3280 AddPortalToNodes(portal, other_node, front);
3284 // the portal is split
3285 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3286 temp = splitportal->chain;
3287 *splitportal = *portal;
3288 splitportal->chain = temp;
3289 for (i = 0;i < numbackpoints*3;i++)
3290 splitportal->points[i] = backpoints[i];
3291 splitportal->numpoints = numbackpoints;
3292 for (i = 0;i < numfrontpoints*3;i++)
3293 portal->points[i] = frontpoints[i];
3294 portal->numpoints = numfrontpoints;
3298 AddPortalToNodes(portal, front, other_node);
3299 AddPortalToNodes(splitportal, back, other_node);
3303 AddPortalToNodes(portal, other_node, front);
3304 AddPortalToNodes(splitportal, other_node, back);
3308 Mod_Q1BSP_RecursiveNodePortals(front);
3309 Mod_Q1BSP_RecursiveNodePortals(back);
3311 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3314 static void Mod_Q1BSP_MakePortals(void)
3316 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3317 portalpointsbufferoffset = 0;
3318 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3319 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3320 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3321 Mem_Free(portalpointsbuffer);
3322 portalpointsbuffer = NULL;
3323 portalpointsbufferoffset = 0;
3324 portalpointsbuffersize = 0;
3325 Mod_Q1BSP_FinalizePortals();
3326 Mem_ExpandableArray_FreeArray(&portalarray);
3329 //Returns PVS data for a given point
3330 //(note: can return NULL)
3331 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3334 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3336 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3337 if (((mleaf_t *)node)->clusterindex >= 0)
3338 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3343 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)
3347 float d = PlaneDiff(org, node->plane);
3349 node = node->children[0];
3350 else if (d < -radius)
3351 node = node->children[1];
3354 // go down both sides
3355 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3356 node = node->children[1];
3359 // if this leaf is in a cluster, accumulate the pvs bits
3360 if (((mleaf_t *)node)->clusterindex >= 0)
3363 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3364 for (i = 0;i < pvsbytes;i++)
3365 pvsbuffer[i] |= pvs[i];
3369 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3370 //of the given point.
3371 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3373 int bytes = model->brush.num_pvsclusterbytes;
3374 bytes = min(bytes, pvsbufferlength);
3375 if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3377 memset(pvsbuffer, 0xFF, bytes);
3381 memset(pvsbuffer, 0, bytes);
3382 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3386 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3391 VectorSubtract(inmaxs, inmins, size);
3392 if (cmodel->brush.ishlbsp)
3395 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3396 else if (size[0] <= 32)
3398 if (size[2] < 54) // pick the nearest of 36 or 72
3399 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3401 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3404 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3409 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3410 else if (size[0] <= 32)
3411 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3413 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3415 VectorCopy(inmins, outmins);
3416 VectorAdd(inmins, hull->clip_size, outmaxs);
3419 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3422 int numshadowmeshtriangles = 0;
3423 msurface_t *surface;
3424 if (cls.state == ca_dedicated)
3426 // make a single combined shadow mesh to allow optimized shadow volume creation
3428 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3430 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3431 numshadowmeshtriangles += surface->num_triangles;
3433 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3434 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3435 if (surface->num_triangles > 0)
3436 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));
3437 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, true, false);
3438 if (mod->brush.shadowmesh)
3439 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3441 return numshadowmeshtriangles;
3444 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3449 float dist, modelyawradius, modelradius;
3450 msurface_t *surface;
3451 hullinfo_t hullinfo;
3452 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3453 model_brush_lightstyleinfo_t styleinfo[256];
3454 unsigned char *datapointer;
3456 mod->modeldatatypestring = "Q1BSP";
3458 mod->type = mod_brushq1;
3460 header = (dheader_t *)buffer;
3462 i = LittleLong(header->version);
3463 if (i != BSPVERSION && i != 30)
3464 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3465 mod->brush.ishlbsp = i == 30;
3467 // fill in hull info
3468 VectorClear (hullinfo.hullsizes[0][0]);
3469 VectorClear (hullinfo.hullsizes[0][1]);
3470 if (mod->brush.ishlbsp)
3472 mod->modeldatatypestring = "HLBSP";
3474 hullinfo.filehulls = 4;
3475 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3476 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3477 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3478 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3479 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3480 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3484 hullinfo.filehulls = 4;
3485 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3486 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3487 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3488 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3492 mod_base = (unsigned char*)buffer;
3493 for (i = 0; i < HEADER_LUMPS; i++)
3495 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3496 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3499 mod->soundfromcenter = true;
3500 mod->TraceBox = Mod_Q1BSP_TraceBox;
3501 mod->TraceLine = Mod_Q1BSP_TraceLine;
3502 mod->TracePoint = Mod_Q1BSP_TracePoint;
3503 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3504 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3505 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3506 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3507 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3508 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3509 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3510 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3511 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3512 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3513 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3514 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3515 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3516 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3517 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3518 mod->Draw = R_Q1BSP_Draw;
3519 mod->DrawDepth = R_Q1BSP_DrawDepth;
3520 mod->DrawDebug = R_Q1BSP_DrawDebug;
3521 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3522 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3523 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3524 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3525 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3526 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3527 mod->DrawLight = R_Q1BSP_DrawLight;
3531 mod->brush.qw_md4sum = 0;
3532 mod->brush.qw_md4sum2 = 0;
3533 for (i = 0;i < HEADER_LUMPS;i++)
3536 if (i == LUMP_ENTITIES)
3538 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3539 mod->brush.qw_md4sum ^= LittleLong(temp);
3540 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3542 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3543 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3546 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3547 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3548 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3549 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3550 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3551 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3552 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3553 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3554 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3555 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3556 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3557 // load submodels before leafs because they contain the number of vis leafs
3558 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3559 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3560 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3561 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3563 // check if the map supports transparent water rendering
3564 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3566 if (mod->brushq1.data_compressedpvs)
3567 Mem_Free(mod->brushq1.data_compressedpvs);
3568 mod->brushq1.data_compressedpvs = NULL;
3569 mod->brushq1.num_compressedpvs = 0;
3571 Mod_Q1BSP_MakeHull0();
3572 Mod_Q1BSP_MakePortals();
3574 mod->numframes = 2; // regular and alternate animation
3577 // make a single combined shadow mesh to allow optimized shadow volume creation
3578 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3580 if (loadmodel->brush.numsubmodels)
3581 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3583 // LordHavoc: to clear the fog around the original quake submodel code, I
3585 // first of all, some background info on the submodels:
3586 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3587 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3588 // now the weird for loop itself:
3589 // the loop functions in an odd way, on each iteration it sets up the
3590 // current 'mod' model (which despite the confusing code IS the model of
3591 // the number i), at the end of the loop it duplicates the model to become
3592 // the next submodel, and loops back to set up the new submodel.
3594 // LordHavoc: now the explanation of my sane way (which works identically):
3595 // set up the world model, then on each submodel copy from the world model
3596 // and set up the submodel with the respective model info.
3597 totalstylesurfaces = 0;
3599 for (i = 0;i < mod->brush.numsubmodels;i++)
3601 memset(stylecounts, 0, sizeof(stylecounts));
3602 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3604 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3605 for (j = 0;j < MAXLIGHTMAPS;j++)
3606 stylecounts[surface->lightmapinfo->styles[j]]++;
3608 for (k = 0;k < 255;k++)
3612 totalstylesurfaces += stylecounts[k];
3615 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3616 for (i = 0;i < mod->brush.numsubmodels;i++)
3618 // LordHavoc: this code was originally at the end of this loop, but
3619 // has been transformed to something more readable at the start here.
3624 // duplicate the basic information
3625 dpsnprintf(name, sizeof(name), "*%i", i);
3626 mod = Mod_FindName(name, loadmodel->name);
3627 // copy the base model to this one
3629 // rename the clone back to its proper name
3630 strlcpy(mod->name, name, sizeof(mod->name));
3631 mod->brush.parentmodel = loadmodel;
3632 // textures and memory belong to the main model
3633 mod->texturepool = NULL;
3634 mod->mempool = NULL;
3635 mod->brush.GetPVS = NULL;
3636 mod->brush.FatPVS = NULL;
3637 mod->brush.BoxTouchingPVS = NULL;
3638 mod->brush.BoxTouchingLeafPVS = NULL;
3639 mod->brush.BoxTouchingVisibleLeafs = NULL;
3640 mod->brush.FindBoxClusters = NULL;
3641 mod->brush.LightPoint = NULL;
3642 mod->brush.AmbientSoundLevelsForPoint = NULL;
3645 mod->brush.submodel = i;
3647 if (loadmodel->brush.submodels)
3648 loadmodel->brush.submodels[i] = mod;
3650 bm = &mod->brushq1.submodels[i];
3652 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3653 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3655 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3656 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3659 mod->firstmodelsurface = bm->firstface;
3660 mod->nummodelsurfaces = bm->numfaces;
3662 // set node/leaf parents for this submodel
3663 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3665 // make the model surface list (used by shadowing/lighting)
3666 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3667 Mod_MakeSortedSurfaces(mod);
3669 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3670 // (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)
3671 VectorCopy(bm->mins, mod->normalmins);
3672 VectorCopy(bm->maxs, mod->normalmaxs);
3673 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3674 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3675 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3676 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3677 modelradius = modelyawradius + modelradius * modelradius;
3678 modelyawradius = sqrt(modelyawradius);
3679 modelradius = sqrt(modelradius);
3680 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3681 mod->yawmins[2] = mod->normalmins[2];
3682 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3683 mod->yawmaxs[2] = mod->normalmaxs[2];
3684 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3685 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3686 mod->radius = modelradius;
3687 mod->radius2 = modelradius * modelradius;
3689 // this gets altered below if sky or water is used
3690 mod->DrawSky = NULL;
3691 mod->DrawAddWaterPlanes = NULL;
3693 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3694 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3695 if (mod->nummodelsurfaces)
3697 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3698 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3700 if (j < mod->nummodelsurfaces)
3701 mod->DrawSky = R_Q1BSP_DrawSky;
3703 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3704 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
3706 if (j < mod->nummodelsurfaces)
3707 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3709 // build lightstyle update chains
3710 // (used to rapidly mark lightmapupdateflags on many surfaces
3711 // when d_lightstylevalue changes)
3712 memset(stylecounts, 0, sizeof(stylecounts));
3713 for (k = 0;k < mod->nummodelsurfaces;k++)
3715 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3716 for (j = 0;j < MAXLIGHTMAPS;j++)
3717 stylecounts[surface->lightmapinfo->styles[j]]++;
3719 mod->brushq1.num_lightstyles = 0;
3720 for (k = 0;k < 255;k++)
3724 styleinfo[mod->brushq1.num_lightstyles].style = k;
3725 styleinfo[mod->brushq1.num_lightstyles].value = 0;
3726 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3727 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3728 remapstyles[k] = mod->brushq1.num_lightstyles;
3729 mod->brushq1.num_lightstyles++;
3732 for (k = 0;k < mod->nummodelsurfaces;k++)
3734 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3735 for (j = 0;j < MAXLIGHTMAPS;j++)
3737 if (surface->lightmapinfo->styles[j] != 255)
3739 int r = remapstyles[surface->lightmapinfo->styles[j]];
3740 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3744 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3745 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3749 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3750 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3752 //mod->brushq1.num_visleafs = bm->visleafs;
3754 if (mod_q1bsp_polygoncollisions.integer)
3756 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
3757 // point traces and contents checks still use the bsp tree
3758 mod->TraceLine = Mod_CollisionBIH_TraceLine;
3759 mod->TraceBox = Mod_CollisionBIH_TraceBox;
3760 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
3763 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
3765 // generate VBOs and other shared data before cloning submodels
3769 Mod_Q1BSP_LoadMapBrushes();
3770 //Mod_Q1BSP_ProcessLightList();
3774 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);
3777 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3781 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3788 in = (void *)(mod_base + l->fileofs);
3789 if (l->filelen % sizeof(*in))
3790 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3791 count = l->filelen / sizeof(*in);
3792 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3795 loadmodel->num = count;
3797 for (i = 0;i < count;i++, in++, out++)
3803 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3810 in = (void *)(mod_base + l->fileofs);
3811 if (l->filelen % sizeof(*in))
3812 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3813 count = l->filelen / sizeof(*in);
3814 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3817 loadmodel->num = count;
3819 for (i = 0;i < count;i++, in++, out++)
3825 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3832 in = (void *)(mod_base + l->fileofs);
3833 if (l->filelen % sizeof(*in))
3834 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3835 count = l->filelen / sizeof(*in);
3836 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3839 loadmodel->num = count;
3841 for (i = 0;i < count;i++, in++, out++)
3847 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3854 in = (void *)(mod_base + l->fileofs);
3855 if (l->filelen % sizeof(*in))
3856 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3857 count = l->filelen / sizeof(*in);
3858 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3861 loadmodel->num = count;
3863 for (i = 0;i < count;i++, in++, out++)
3869 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3876 in = (void *)(mod_base + l->fileofs);
3877 if (l->filelen % sizeof(*in))
3878 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3879 count = l->filelen / sizeof(*in);
3880 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3883 loadmodel->num = count;
3885 for (i = 0;i < count;i++, in++, out++)
3891 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3898 in = (void *)(mod_base + l->fileofs);
3899 if (l->filelen % sizeof(*in))
3900 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3901 count = l->filelen / sizeof(*in);
3902 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3905 loadmodel->num = count;
3907 for (i = 0;i < count;i++, in++, out++)
3913 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3920 in = (void *)(mod_base + l->fileofs);
3921 if (l->filelen % sizeof(*in))
3922 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3923 count = l->filelen / sizeof(*in);
3924 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3927 loadmodel->num = count;
3929 for (i = 0;i < count;i++, in++, out++)
3935 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3942 in = (void *)(mod_base + l->fileofs);
3943 if (l->filelen % sizeof(*in))
3944 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3945 count = l->filelen / sizeof(*in);
3946 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3949 loadmodel->num = count;
3951 for (i = 0;i < count;i++, in++, out++)
3957 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3964 in = (void *)(mod_base + l->fileofs);
3965 if (l->filelen % sizeof(*in))
3966 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3967 count = l->filelen / sizeof(*in);
3968 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3971 loadmodel->num = count;
3973 for (i = 0;i < count;i++, in++, out++)
3979 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3986 in = (void *)(mod_base + l->fileofs);
3987 if (l->filelen % sizeof(*in))
3988 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3989 count = l->filelen / sizeof(*in);
3990 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3993 loadmodel->num = count;
3995 for (i = 0;i < count;i++, in++, out++)
4001 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4008 in = (void *)(mod_base + l->fileofs);
4009 if (l->filelen % sizeof(*in))
4010 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4011 count = l->filelen / sizeof(*in);
4012 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4015 loadmodel->num = count;
4017 for (i = 0;i < count;i++, in++, out++)
4023 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4030 in = (void *)(mod_base + l->fileofs);
4031 if (l->filelen % sizeof(*in))
4032 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4033 count = l->filelen / sizeof(*in);
4034 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4037 loadmodel->num = count;
4039 for (i = 0;i < count;i++, in++, out++)
4045 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4052 in = (void *)(mod_base + l->fileofs);
4053 if (l->filelen % sizeof(*in))
4054 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4055 count = l->filelen / sizeof(*in);
4056 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4059 loadmodel->num = count;
4061 for (i = 0;i < count;i++, in++, out++)
4067 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4074 in = (void *)(mod_base + l->fileofs);
4075 if (l->filelen % sizeof(*in))
4076 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4077 count = l->filelen / sizeof(*in);
4078 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4081 loadmodel->num = count;
4083 for (i = 0;i < count;i++, in++, out++)
4089 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4096 in = (void *)(mod_base + l->fileofs);
4097 if (l->filelen % sizeof(*in))
4098 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4099 count = l->filelen / sizeof(*in);
4100 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4103 loadmodel->num = count;
4105 for (i = 0;i < count;i++, in++, out++)
4111 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4118 in = (void *)(mod_base + l->fileofs);
4119 if (l->filelen % sizeof(*in))
4120 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4121 count = l->filelen / sizeof(*in);
4122 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4125 loadmodel->num = count;
4127 for (i = 0;i < count;i++, in++, out++)
4133 static void Mod_Q2BSP_LoadModels(lump_t *l)
4140 in = (void *)(mod_base + l->fileofs);
4141 if (l->filelen % sizeof(*in))
4142 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4143 count = l->filelen / sizeof(*in);
4144 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4147 loadmodel->num = count;
4149 for (i = 0;i < count;i++, in++, out++)
4155 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4158 q2dheader_t *header;
4160 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4162 mod->modeldatatypestring = "Q2BSP";
4164 mod->type = mod_brushq2;
4166 header = (q2dheader_t *)buffer;
4168 i = LittleLong(header->version);
4169 if (i != Q2BSPVERSION)
4170 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4172 mod_base = (unsigned char *)header;
4174 // swap all the lumps
4175 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4176 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4178 mod->brush.qw_md4sum = 0;
4179 mod->brush.qw_md4sum2 = 0;
4180 for (i = 0;i < Q2HEADER_LUMPS;i++)
4182 if (i == Q2LUMP_ENTITIES)
4184 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4185 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4187 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4190 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4191 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4192 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4193 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4194 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4195 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4196 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4197 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4198 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4199 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4200 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4201 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4202 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4203 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4204 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4205 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4206 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4207 // LordHavoc: must go last because this makes the submodels
4208 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4211 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4212 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4214 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4217 char key[128], value[MAX_INPUTLINE];
4219 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4220 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4221 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4224 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4225 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4226 loadmodel->brush.entities[l->filelen] = 0;
4227 data = loadmodel->brush.entities;
4228 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4229 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4230 loadmodel->brushq3.deluxemapping = false;
4231 if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4235 if (!COM_ParseToken_Simple(&data, false, false))
4237 if (com_token[0] == '}')
4238 break; // end of worldspawn
4239 if (com_token[0] == '_')
4240 strlcpy(key, com_token + 1, sizeof(key));
4242 strlcpy(key, com_token, sizeof(key));
4243 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4244 key[strlen(key)-1] = 0;
4245 if (!COM_ParseToken_Simple(&data, false, false))
4247 strlcpy(value, com_token, sizeof(value));
4248 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4250 #if _MSC_VER >= 1400
4251 #define sscanf sscanf_s
4254 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4255 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4257 VectorSet(v, 64, 64, 128);
4258 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4259 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]);
4260 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4261 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4264 else if (!strcmp("deluxeMaps", key))
4266 if (!strcmp(com_token, "1"))
4268 loadmodel->brushq3.deluxemapping = true;
4269 loadmodel->brushq3.deluxemapping_modelspace = true;
4271 else if (!strcmp(com_token, "2"))
4273 loadmodel->brushq3.deluxemapping = true;
4274 loadmodel->brushq3.deluxemapping_modelspace = false;
4281 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4287 in = (q3dtexture_t *)(mod_base + l->fileofs);
4288 if (l->filelen % sizeof(*in))
4289 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4290 count = l->filelen / sizeof(*in);
4291 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4293 loadmodel->data_textures = out;
4294 loadmodel->num_textures = count;
4295 loadmodel->num_texturesperskin = loadmodel->num_textures;
4297 for (i = 0;i < count;i++)
4299 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4300 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4301 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4302 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4303 // restore the surfaceflags and supercontents
4304 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4305 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4309 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4315 in = (q3dplane_t *)(mod_base + l->fileofs);
4316 if (l->filelen % sizeof(*in))
4317 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4318 count = l->filelen / sizeof(*in);
4319 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4321 loadmodel->brush.data_planes = out;
4322 loadmodel->brush.num_planes = count;
4324 for (i = 0;i < count;i++, in++, out++)
4326 out->normal[0] = LittleFloat(in->normal[0]);
4327 out->normal[1] = LittleFloat(in->normal[1]);
4328 out->normal[2] = LittleFloat(in->normal[2]);
4329 out->dist = LittleFloat(in->dist);
4334 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4337 q3mbrushside_t *out;
4340 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4341 if (l->filelen % sizeof(*in))
4342 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4343 count = l->filelen / sizeof(*in);
4344 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4346 loadmodel->brush.data_brushsides = out;
4347 loadmodel->brush.num_brushsides = count;
4349 for (i = 0;i < count;i++, in++, out++)
4351 n = LittleLong(in->planeindex);
4352 if (n < 0 || n >= loadmodel->brush.num_planes)
4353 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4354 out->plane = loadmodel->brush.data_planes + n;
4355 n = LittleLong(in->textureindex);
4356 if (n < 0 || n >= loadmodel->num_textures)
4357 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4358 out->texture = loadmodel->data_textures + n;
4362 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4364 q3dbrushside_ig_t *in;
4365 q3mbrushside_t *out;
4368 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4369 if (l->filelen % sizeof(*in))
4370 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4371 count = l->filelen / sizeof(*in);
4372 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4374 loadmodel->brush.data_brushsides = out;
4375 loadmodel->brush.num_brushsides = count;
4377 for (i = 0;i < count;i++, in++, out++)
4379 n = LittleLong(in->planeindex);
4380 if (n < 0 || n >= loadmodel->brush.num_planes)
4381 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4382 out->plane = loadmodel->brush.data_planes + n;
4383 n = LittleLong(in->textureindex);
4384 if (n < 0 || n >= loadmodel->num_textures)
4385 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4386 out->texture = loadmodel->data_textures + n;
4390 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4394 int i, j, n, c, count, maxplanes, q3surfaceflags;
4395 colplanef_t *planes;
4397 in = (q3dbrush_t *)(mod_base + l->fileofs);
4398 if (l->filelen % sizeof(*in))
4399 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4400 count = l->filelen / sizeof(*in);
4401 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4403 loadmodel->brush.data_brushes = out;
4404 loadmodel->brush.num_brushes = count;
4409 for (i = 0;i < count;i++, in++, out++)
4411 n = LittleLong(in->firstbrushside);
4412 c = LittleLong(in->numbrushsides);
4413 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4414 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4415 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4416 out->numbrushsides = c;
4417 n = LittleLong(in->textureindex);
4418 if (n < 0 || n >= loadmodel->num_textures)
4419 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4420 out->texture = loadmodel->data_textures + n;
4422 // make a list of mplane_t structs to construct a colbrush from
4423 if (maxplanes < out->numbrushsides)
4425 maxplanes = out->numbrushsides;
4428 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4431 for (j = 0;j < out->numbrushsides;j++)
4433 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4434 planes[j].dist = out->firstbrushside[j].plane->dist;
4435 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4436 planes[j].texture = out->firstbrushside[j].texture;
4437 q3surfaceflags |= planes[j].q3surfaceflags;
4439 // make the colbrush from the planes
4440 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4442 // this whole loop can take a while (e.g. on redstarrepublic4)
4443 CL_KeepaliveMessage(false);
4449 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4455 in = (q3deffect_t *)(mod_base + l->fileofs);
4456 if (l->filelen % sizeof(*in))
4457 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4458 count = l->filelen / sizeof(*in);
4459 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4461 loadmodel->brushq3.data_effects = out;
4462 loadmodel->brushq3.num_effects = count;
4464 for (i = 0;i < count;i++, in++, out++)
4466 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4467 n = LittleLong(in->brushindex);
4468 if (n >= loadmodel->brush.num_brushes)
4470 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4473 out->brushindex = n;
4474 out->unknown = LittleLong(in->unknown);
4478 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4483 in = (q3dvertex_t *)(mod_base + l->fileofs);
4484 if (l->filelen % sizeof(*in))
4485 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4486 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4487 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4488 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4489 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4490 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4491 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4493 for (i = 0;i < count;i++, in++)
4495 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4496 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4497 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4498 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4499 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4500 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4501 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4502 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4503 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4504 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4505 // svector/tvector are calculated later in face loading
4506 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4507 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4508 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4509 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4510 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4511 loadmodel->lit = true;
4515 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4521 in = (int *)(mod_base + l->fileofs);
4522 if (l->filelen % sizeof(int[3]))
4523 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4524 count = l->filelen / sizeof(*in);
4526 if(!loadmodel->brushq3.num_vertices)
4529 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4530 loadmodel->brushq3.num_triangles = 0;
4534 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4535 loadmodel->brushq3.num_triangles = count / 3;
4536 loadmodel->brushq3.data_element3i = out;
4538 for (i = 0;i < count;i++, in++, out++)
4540 *out = LittleLong(*in);
4541 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4543 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4549 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4551 q3dlightmap_t *input_pointer;
4569 int mergedrowsxcolumns;
4574 unsigned char *mergedpixels;
4575 unsigned char *mergeddeluxepixels;
4576 unsigned char *mergebuf;
4577 char mapname[MAX_QPATH];
4579 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4581 // defaults for q3bsp
4588 loadmodel->brushq3.lightmapsize = 128;
4590 if (cls.state == ca_dedicated)
4593 if(mod_q3bsp_nolightmaps.integer)
4599 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4600 if (developer_loading.integer)
4601 Con_Printf("Using internal lightmaps\n");
4602 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4603 if (l->filelen % sizeof(*input_pointer))
4604 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4605 count = l->filelen / sizeof(*input_pointer);
4606 for(i = 0; i < count; ++i)
4607 inpixels[i] = input_pointer[i].rgb;
4611 // no internal lightmaps
4612 // try external lightmaps
4613 if (developer_loading.integer)
4614 Con_Printf("Using external lightmaps\n");
4615 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4616 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false, NULL);
4620 // using EXTERNAL lightmaps instead
4621 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4623 Mem_Free(inpixels[0]);
4624 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4634 for(count = 1; ; ++count)
4636 inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false, NULL);
4637 if(!inpixels[count])
4638 break; // we got all of them
4639 if(image_width != size || image_height != size)
4641 Mem_Free(inpixels[count]);
4642 inpixels[count] = NULL;
4643 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);
4649 loadmodel->brushq3.lightmapsize = size;
4650 loadmodel->brushq3.num_originallightmaps = count;
4652 // now check the surfaces to see if any of them index an odd numbered
4653 // lightmap, if so this is not a deluxemapped bsp file
4655 // also check what lightmaps are actually used, because q3map2 sometimes
4656 // (always?) makes an unused one at the end, which
4657 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4658 // reason when only one lightmap is used, which can throw off the
4659 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4660 // to see if the second lightmap is blank, if so it is not deluxemapped.
4661 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4662 // in Mod_Q3BSP_LoadEntities was failed
4663 if (!loadmodel->brushq3.deluxemapping)
4665 loadmodel->brushq3.deluxemapping = !(count & 1);
4666 loadmodel->brushq3.deluxemapping_modelspace = true;
4668 if (loadmodel->brushq3.deluxemapping)
4670 int facecount = faceslump->filelen / sizeof(q3dface_t);
4671 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4672 for (i = 0;i < facecount;i++)
4674 j = LittleLong(faces[i].lightmapindex);
4677 endlightmap = max(endlightmap, j + 1);
4678 if ((j & 1) || j + 1 >= count)
4680 loadmodel->brushq3.deluxemapping = false;
4687 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4688 // reason when only one lightmap is used, which can throw off the
4689 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4690 // to see if the second lightmap is blank, if so it is not deluxemapped.
4692 // further research has shown q3map2 sometimes creates a deluxemap and two
4693 // blank lightmaps, which must be handled properly as well
4694 if (endlightmap == 1 && count > 1)
4697 for (i = 0;i < size*size;i++)
4699 if (c[bytesperpixel*i + rgbmap[0]])
4701 if (c[bytesperpixel*i + rgbmap[1]])
4703 if (c[bytesperpixel*i + rgbmap[2]])
4708 // all pixels in the unused lightmap were black...
4709 loadmodel->brushq3.deluxemapping = false;
4714 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4716 // figure out what the most reasonable merge power is within limits
4718 // find the appropriate NxN dimensions to merge to, to avoid wasted space
4719 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
4721 // figure out how big the merged texture has to be
4722 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
4723 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
4724 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
4726 mergedwidth = mergegoal;
4727 mergedheight = mergegoal;
4728 // choose non-square size (2x1 aspect) if only half the space is used;
4729 // this really only happens when the entire set fits in one texture, if
4730 // there are multiple textures, we don't worry about shrinking the last
4731 // one to fit, because the driver prefers the same texture size on
4732 // consecutive draw calls...
4733 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
4736 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
4737 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
4738 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
4739 loadmodel->brushq3.num_lightmapmergedwidthpower++;
4740 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
4741 loadmodel->brushq3.num_lightmapmergedheightpower++;
4742 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
4744 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
4745 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
4746 powerxy = powerx+powery;
4747 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
4749 mergedcolumns = 1 << powerx;
4750 mergedrows = 1 << powery;
4751 mergedrowsxcolumns = 1 << powerxy;
4753 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
4754 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4755 if (loadmodel->brushq3.deluxemapping)
4756 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4758 // allocate a texture pool if we need it
4759 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4760 loadmodel->texturepool = R_AllocTexturePool();
4762 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
4763 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
4764 for (i = 0;i < count;i++)
4766 // figure out which merged lightmap texture this fits into
4767 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
4768 lightmapindex = i >> powerdxy;
4770 // choose the destination address
4771 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
4772 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
4773 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
4774 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);
4776 // convert pixels from RGB or BGRA while copying them into the destination rectangle
4777 for (j = 0;j < size;j++)
4778 for (k = 0;k < size;k++)
4780 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
4781 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
4782 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
4783 mergebuf[(j*mergedwidth+k)*4+3] = 255;
4786 // upload texture if this was the last tile being written to the texture
4787 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
4789 if (loadmodel->brushq3.deluxemapping && (i & 1))
4790 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);
4792 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);
4796 if (mergeddeluxepixels)
4797 Mem_Free(mergeddeluxepixels);
4798 Mem_Free(mergedpixels);
4801 for(i = 0; i < count; ++i)
4802 Mem_Free(inpixels[i]);
4806 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
4811 *collisionstride = stride;
4814 cnt = (num_triangles + stride - 1) / stride;
4815 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
4816 for(j = 0; j < cnt; ++j)
4818 mins = &((*collisionbbox6f)[6 * j + 0]);
4819 maxs = &((*collisionbbox6f)[6 * j + 3]);
4820 for(k = 0; k < stride; ++k)
4822 tri = j * stride + k;
4823 if(tri >= num_triangles)
4825 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
4826 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
4827 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
4828 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
4829 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
4830 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
4831 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
4832 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
4833 if(vert[0] < mins[0]) mins[0] = vert[0];
4834 if(vert[1] < mins[1]) mins[1] = vert[1];
4835 if(vert[2] < mins[2]) mins[2] = vert[2];
4836 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4837 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4838 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4839 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
4840 if(vert[0] < mins[0]) mins[0] = vert[0];
4841 if(vert[1] < mins[1]) mins[1] = vert[1];
4842 if(vert[2] < mins[2]) mins[2] = vert[2];
4843 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4844 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4845 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4850 *collisionbbox6f = NULL;
4853 typedef struct patchtess_s
4857 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
4860 float *originalvertex3f;
4863 #define PATCHTESS_SAME_LODGROUP(a,b) \
4865 (a).lodgroup[0] == (b).lodgroup[0] && \
4866 (a).lodgroup[1] == (b).lodgroup[1] && \
4867 (a).lodgroup[2] == (b).lodgroup[2] && \
4868 (a).lodgroup[3] == (b).lodgroup[3] && \
4869 (a).lodgroup[4] == (b).lodgroup[4] && \
4870 (a).lodgroup[5] == (b).lodgroup[5] \
4873 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4875 q3dface_t *in, *oldin;
4876 msurface_t *out, *oldout;
4877 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;
4878 float lightmaptcbase[2], lightmaptcscale[2];
4879 //int *originalelement3i;
4880 //int *originalneighbor3i;
4881 float *originalvertex3f;
4882 //float *originalsvector3f;
4883 //float *originaltvector3f;
4884 float *originalnormal3f;
4885 float *originalcolor4f;
4886 float *originaltexcoordtexture2f;
4887 float *originaltexcoordlightmap2f;
4888 float *surfacecollisionvertex3f;
4889 int *surfacecollisionelement3i;
4891 patchtess_t *patchtess = NULL;
4892 int patchtesscount = 0;
4895 in = (q3dface_t *)(mod_base + l->fileofs);
4896 if (l->filelen % sizeof(*in))
4897 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4898 count = l->filelen / sizeof(*in);
4899 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4901 loadmodel->data_surfaces = out;
4902 loadmodel->num_surfaces = count;
4905 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
4913 for (;i < count;i++, in++, out++)
4915 // check face type first
4916 type = LittleLong(in->type);
4917 if (type != Q3FACETYPE_FLAT
4918 && type != Q3FACETYPE_PATCH
4919 && type != Q3FACETYPE_MESH
4920 && type != Q3FACETYPE_FLARE)
4922 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4926 n = LittleLong(in->textureindex);
4927 if (n < 0 || n >= loadmodel->num_textures)
4929 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4932 out->texture = loadmodel->data_textures + n;
4933 n = LittleLong(in->effectindex);
4934 if (n < -1 || n >= loadmodel->brushq3.num_effects)
4936 if (developer_extra.integer)
4937 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4943 out->effect = loadmodel->brushq3.data_effects + n;
4945 if (cls.state != ca_dedicated)
4947 out->lightmaptexture = NULL;
4948 out->deluxemaptexture = r_texture_blanknormalmap;
4949 n = LittleLong(in->lightmapindex);
4952 else if (n >= loadmodel->brushq3.num_originallightmaps)
4954 if(loadmodel->brushq3.num_originallightmaps != 0)
4955 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
4960 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
4961 if (loadmodel->brushq3.deluxemapping)
4962 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
4963 loadmodel->lit = true;
4967 firstvertex = LittleLong(in->firstvertex);
4968 numvertices = LittleLong(in->numvertices);
4969 firstelement = LittleLong(in->firstelement);
4970 numtriangles = LittleLong(in->numelements) / 3;
4971 if (numtriangles * 3 != LittleLong(in->numelements))
4973 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));
4976 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4978 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);
4981 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4983 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);
4988 case Q3FACETYPE_FLAT:
4989 case Q3FACETYPE_MESH:
4990 // no processing necessary
4992 case Q3FACETYPE_PATCH:
4993 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4994 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4995 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))
4997 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5000 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5002 // convert patch to Q3FACETYPE_MESH
5003 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5004 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5005 // bound to user settings
5006 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5007 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5008 // bound to sanity settings
5009 xtess = bound(0, xtess, 1024);
5010 ytess = bound(0, ytess, 1024);
5012 // lower quality collision patches! Same procedure as before, but different cvars
5013 // convert patch to Q3FACETYPE_MESH
5014 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5015 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5016 // bound to user settings
5017 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5018 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5019 // bound to sanity settings
5020 cxtess = bound(0, cxtess, 1024);
5021 cytess = bound(0, cytess, 1024);
5023 // store it for the LOD grouping step
5024 patchtess[patchtesscount].info.xsize = patchsize[0];
5025 patchtess[patchtesscount].info.ysize = patchsize[1];
5026 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5027 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5028 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5029 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5031 patchtess[patchtesscount].surface_id = i;
5032 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5033 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5034 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5035 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5036 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5037 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5038 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5041 case Q3FACETYPE_FLARE:
5042 if (developer_extra.integer)
5043 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5047 out->num_vertices = numvertices;
5048 out->num_triangles = numtriangles;
5049 meshvertices += out->num_vertices;
5050 meshtriangles += out->num_triangles;
5053 // Fix patches tesselations so that they make no seams
5057 for(i = 0; i < patchtesscount; ++i)
5059 for(j = i+1; j < patchtesscount; ++j)
5061 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5064 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5071 // Calculate resulting number of triangles
5072 collisionvertices = 0;
5073 collisiontriangles = 0;
5074 for(i = 0; i < patchtesscount; ++i)
5076 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5077 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5078 numvertices = finalwidth * finalheight;
5079 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5081 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5082 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5083 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5084 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5086 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5087 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5088 numvertices = finalwidth * finalheight;
5089 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5091 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5092 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5093 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5094 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5100 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5101 if (collisiontriangles)
5103 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5104 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5108 collisionvertices = 0;
5109 collisiontriangles = 0;
5110 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5112 if (out->num_vertices < 3 || out->num_triangles < 1)
5115 type = LittleLong(in->type);
5116 firstvertex = LittleLong(in->firstvertex);
5117 firstelement = LittleLong(in->firstelement);
5118 out->num_firstvertex = meshvertices;
5119 out->num_firsttriangle = meshtriangles;
5120 out->num_firstcollisiontriangle = collisiontriangles;
5123 case Q3FACETYPE_FLAT:
5124 case Q3FACETYPE_MESH:
5125 // no processing necessary, except for lightmap merging
5126 for (j = 0;j < out->num_vertices;j++)
5128 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5129 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5130 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5131 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5132 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5133 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5134 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5135 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5136 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5137 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5138 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5139 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5140 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5141 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5143 for (j = 0;j < out->num_triangles*3;j++)
5144 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5146 case Q3FACETYPE_PATCH:
5147 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5148 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5149 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5150 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5151 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5152 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5153 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5155 xtess = ytess = cxtess = cytess = -1;
5156 for(j = 0; j < patchtesscount; ++j)
5157 if(patchtess[j].surface_id == i)
5159 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5160 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5161 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5162 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5167 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5168 xtess = ytess = cxtess = cytess = 0;
5171 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5172 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5173 finalvertices = finalwidth * finalheight;
5174 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5175 type = Q3FACETYPE_MESH;
5176 // generate geometry
5177 // (note: normals are skipped because they get recalculated)
5178 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5179 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5180 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5181 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5182 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5183 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5185 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);
5187 if (developer_extra.integer)
5189 if (out->num_triangles < finaltriangles)
5190 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);
5192 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);
5194 // q3map does not put in collision brushes for curves... ugh
5195 // build the lower quality collision geometry
5196 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5197 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5198 finalvertices = finalwidth * finalheight;
5199 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5201 // legacy collision geometry implementation
5202 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5203 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5204 out->num_collisionvertices = finalvertices;
5205 out->num_collisiontriangles = finaltriangles;
5206 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5207 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5209 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5210 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5212 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5214 // now optimize the collision mesh by finding triangle bboxes...
5215 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5216 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);
5218 // store collision geometry for BIH collision tree
5219 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5220 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5221 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5222 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5223 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5225 // remove this once the legacy code is removed
5227 int nc = out->num_collisiontriangles;
5229 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5231 if(nc != out->num_collisiontriangles)
5233 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5238 if (developer_extra.integer)
5239 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);
5241 collisionvertices += finalvertices;
5242 collisiontriangles += out->num_collisiontriangles;
5247 meshvertices += out->num_vertices;
5248 meshtriangles += out->num_triangles;
5249 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5250 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)
5252 if (invalidelements)
5254 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);
5255 for (j = 0;j < out->num_triangles * 3;j++)
5257 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5258 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)
5259 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5263 // calculate a bounding box
5264 VectorClear(out->mins);
5265 VectorClear(out->maxs);
5266 if (out->num_vertices)
5268 if (cls.state != ca_dedicated && out->lightmaptexture)
5270 // figure out which part of the merged lightmap this fits into
5271 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5272 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5273 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5274 lightmapindex &= mergewidth * mergeheight - 1;
5275 lightmaptcscale[0] = 1.0f / mergewidth;
5276 lightmaptcscale[1] = 1.0f / mergeheight;
5277 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5278 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5279 // modify the lightmap texcoords to match this region of the merged lightmap
5280 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5282 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5283 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5286 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5287 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5288 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5290 out->mins[0] = min(out->mins[0], v[0]);
5291 out->maxs[0] = max(out->maxs[0], v[0]);
5292 out->mins[1] = min(out->mins[1], v[1]);
5293 out->maxs[1] = max(out->maxs[1], v[1]);
5294 out->mins[2] = min(out->mins[2], v[2]);
5295 out->maxs[2] = max(out->maxs[2], v[2]);
5297 out->mins[0] -= 1.0f;
5298 out->mins[1] -= 1.0f;
5299 out->mins[2] -= 1.0f;
5300 out->maxs[0] += 1.0f;
5301 out->maxs[1] += 1.0f;
5302 out->maxs[2] += 1.0f;
5304 // set lightmap styles for consistency with q1bsp
5305 //out->lightmapinfo->styles[0] = 0;
5306 //out->lightmapinfo->styles[1] = 255;
5307 //out->lightmapinfo->styles[2] = 255;
5308 //out->lightmapinfo->styles[3] = 255;
5313 for (;i < count;i++, out++)
5315 if(out->num_vertices && out->num_triangles)
5317 if(out->num_vertices == 0)
5318 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d has no vertices, ignoring\n", i);
5319 if(out->num_triangles == 0)
5320 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d has no triangles, ignoring\n", i);
5323 // for per pixel lighting
5324 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, true);
5326 // generate ushort elements array if possible
5327 if (loadmodel->surfmesh.data_element3s)
5328 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5329 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5331 // free the no longer needed vertex data
5332 loadmodel->brushq3.num_vertices = 0;
5333 if (loadmodel->brushq3.data_vertex3f)
5334 Mem_Free(loadmodel->brushq3.data_vertex3f);
5335 loadmodel->brushq3.data_vertex3f = NULL;
5336 loadmodel->brushq3.data_normal3f = NULL;
5337 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5338 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5339 loadmodel->brushq3.data_color4f = NULL;
5340 // free the no longer needed triangle data
5341 loadmodel->brushq3.num_triangles = 0;
5342 if (loadmodel->brushq3.data_element3i)
5343 Mem_Free(loadmodel->brushq3.data_element3i);
5344 loadmodel->brushq3.data_element3i = NULL;
5347 Mem_Free(patchtess);
5350 static void Mod_Q3BSP_LoadModels(lump_t *l)
5354 int i, j, n, c, count;
5356 in = (q3dmodel_t *)(mod_base + l->fileofs);
5357 if (l->filelen % sizeof(*in))
5358 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5359 count = l->filelen / sizeof(*in);
5360 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5362 loadmodel->brushq3.data_models = out;
5363 loadmodel->brushq3.num_models = count;
5365 for (i = 0;i < count;i++, in++, out++)
5367 for (j = 0;j < 3;j++)
5369 out->mins[j] = LittleFloat(in->mins[j]);
5370 out->maxs[j] = LittleFloat(in->maxs[j]);
5372 n = LittleLong(in->firstface);
5373 c = LittleLong(in->numfaces);
5374 if (n < 0 || n + c > loadmodel->num_surfaces)
5375 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5378 n = LittleLong(in->firstbrush);
5379 c = LittleLong(in->numbrushes);
5380 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5381 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5382 out->firstbrush = n;
5383 out->numbrushes = c;
5387 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5393 in = (int *)(mod_base + l->fileofs);
5394 if (l->filelen % sizeof(*in))
5395 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5396 count = l->filelen / sizeof(*in);
5397 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5399 loadmodel->brush.data_leafbrushes = out;
5400 loadmodel->brush.num_leafbrushes = count;
5402 for (i = 0;i < count;i++, in++, out++)
5404 n = LittleLong(*in);
5405 if (n < 0 || n >= loadmodel->brush.num_brushes)
5406 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5411 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5417 in = (int *)(mod_base + l->fileofs);
5418 if (l->filelen % sizeof(*in))
5419 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5420 count = l->filelen / sizeof(*in);
5421 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5423 loadmodel->brush.data_leafsurfaces = out;
5424 loadmodel->brush.num_leafsurfaces = count;
5426 for (i = 0;i < count;i++, in++, out++)
5428 n = LittleLong(*in);
5429 if (n < 0 || n >= loadmodel->num_surfaces)
5430 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5435 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5439 int i, j, n, c, count;
5441 in = (q3dleaf_t *)(mod_base + l->fileofs);
5442 if (l->filelen % sizeof(*in))
5443 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5444 count = l->filelen / sizeof(*in);
5445 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5447 loadmodel->brush.data_leafs = out;
5448 loadmodel->brush.num_leafs = count;
5450 for (i = 0;i < count;i++, in++, out++)
5454 out->clusterindex = LittleLong(in->clusterindex);
5455 out->areaindex = LittleLong(in->areaindex);
5456 for (j = 0;j < 3;j++)
5458 // yes the mins/maxs are ints
5459 out->mins[j] = LittleLong(in->mins[j]) - 1;
5460 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5462 n = LittleLong(in->firstleafface);
5463 c = LittleLong(in->numleaffaces);
5464 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5465 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5466 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5467 out->numleafsurfaces = c;
5468 n = LittleLong(in->firstleafbrush);
5469 c = LittleLong(in->numleafbrushes);
5470 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5471 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5472 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5473 out->numleafbrushes = c;
5477 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5483 in = (q3dnode_t *)(mod_base + l->fileofs);
5484 if (l->filelen % sizeof(*in))
5485 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5486 count = l->filelen / sizeof(*in);
5487 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5489 loadmodel->brush.data_nodes = out;
5490 loadmodel->brush.num_nodes = count;
5492 for (i = 0;i < count;i++, in++, out++)
5495 n = LittleLong(in->planeindex);
5496 if (n < 0 || n >= loadmodel->brush.num_planes)
5497 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5498 out->plane = loadmodel->brush.data_planes + n;
5499 for (j = 0;j < 2;j++)
5501 n = LittleLong(in->childrenindex[j]);
5504 if (n >= loadmodel->brush.num_nodes)
5505 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5506 out->children[j] = loadmodel->brush.data_nodes + n;
5511 if (n >= loadmodel->brush.num_leafs)
5512 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5513 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5516 for (j = 0;j < 3;j++)
5518 // yes the mins/maxs are ints
5519 out->mins[j] = LittleLong(in->mins[j]) - 1;
5520 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5524 // set the parent pointers
5525 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5528 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5531 q3dlightgrid_t *out;
5534 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5535 if (l->filelen % sizeof(*in))
5536 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5537 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5538 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5539 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5540 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5541 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5542 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5543 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5544 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5545 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5546 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5547 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5548 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5549 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5550 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]);
5551 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]);
5553 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5556 if (l->filelen < count * (int)sizeof(*in))
5558 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]);
5559 return; // ignore the grid if we cannot understand it
5561 if (l->filelen != count * (int)sizeof(*in))
5562 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5563 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5564 loadmodel->brushq3.data_lightgrid = out;
5565 loadmodel->brushq3.num_lightgrid = count;
5566 // no swapping or validation necessary
5567 memcpy(out, in, count * (int)sizeof(*out));
5571 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5576 if (l->filelen == 0)
5579 // unvised maps often have cluster indices even without pvs, so check
5580 // leafs to find real number of clusters
5581 loadmodel->brush.num_pvsclusters = 1;
5582 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5583 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5586 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5587 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5588 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5589 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5593 in = (q3dpvs_t *)(mod_base + l->fileofs);
5595 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5597 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5598 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5599 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5600 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5601 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5602 if (l->filelen < totalchains + (int)sizeof(*in))
5603 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);
5605 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5606 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5609 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5611 int i, j, k, index[3];
5612 float transformed[3], blend1, blend2, blend, stylescale;
5613 q3dlightgrid_t *a, *s;
5615 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5616 stylescale = r_refdef.scene.rtlightstylevalue[0];
5618 if (!model->brushq3.num_lightgrid)
5620 ambientcolor[0] = stylescale;
5621 ambientcolor[1] = stylescale;
5622 ambientcolor[2] = stylescale;
5626 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5627 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5628 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5629 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5630 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5631 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5632 index[0] = (int)floor(transformed[0]);
5633 index[1] = (int)floor(transformed[1]);
5634 index[2] = (int)floor(transformed[2]);
5635 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5637 // now lerp the values
5638 VectorClear(diffusenormal);
5639 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5640 for (k = 0;k < 2;k++)
5642 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5643 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5645 for (j = 0;j < 2;j++)
5647 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5648 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5650 for (i = 0;i < 2;i++)
5652 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5653 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5655 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5656 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5657 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5658 // this uses the mod_md3_sin table because the values are
5659 // already in the 0-255 range, the 64+ bias fetches a cosine
5660 // instead of a sine value
5661 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5662 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5663 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5664 //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)));
5669 // normalize the light direction before turning
5670 VectorNormalize(diffusenormal);
5671 //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]);
5674 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5677 double midf, mid[3];
5683 // find the point distances
5684 mplane_t *plane = node->plane;
5685 if (plane->type < 3)
5687 t1 = p1[plane->type] - plane->dist;
5688 t2 = p2[plane->type] - plane->dist;
5692 t1 = DotProduct (plane->normal, p1) - plane->dist;
5693 t2 = DotProduct (plane->normal, p2) - plane->dist;
5700 node = node->children[1];
5709 node = node->children[0];
5715 midf = t1 / (t1 - t2);
5716 VectorLerp(p1, midf, p2, mid);
5718 // recurse both sides, front side first
5719 // return 2 if empty is followed by solid (hit something)
5720 // do not return 2 if both are solid or both empty,
5721 // or if start is solid and end is empty
5722 // as these degenerate cases usually indicate the eye is in solid and
5723 // should see the target point anyway
5724 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
5727 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5732 return ((mleaf_t *)node)->clusterindex < 0;
5735 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5737 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
5740 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
5741 return trace.fraction == 1;
5745 double tracestart[3], traceend[3];
5746 VectorCopy(start, tracestart);
5747 VectorCopy(end, traceend);
5748 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
5752 static void Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const vec3_t point)
5754 const bih_leaf_t *leaf;
5755 const bih_node_t *node;
5756 const colbrushf_t *brush;
5758 while (nodenum >= 0)
5760 node = model->collision_bih.nodes + nodenum;
5761 axis = node->type - BIH_SPLITX;
5762 if (point[axis] <= node->backmax)
5764 if (point[axis] >= node->frontmin)
5765 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, node->front, point);
5766 nodenum = node->back;
5768 else if (point[axis] >= node->frontmin)
5769 nodenum = node->front;
5770 else // no overlap with either child? just return
5773 if (!model->collision_bih.leafs)
5775 leaf = model->collision_bih.leafs + (-1-nodenum);
5779 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5780 Collision_TracePointBrushFloat(trace, point, brush);
5782 case BIH_COLLISIONTRIANGLE:
5783 // collision triangle - skipped because they have no volume
5785 case BIH_RENDERTRIANGLE:
5786 // render triangle - skipped because they have no volume
5791 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)
5793 const bih_leaf_t *leaf;
5794 const bih_node_t *node;
5795 const colbrushf_t *brush;
5797 const texture_t *texture;
5808 vec3_t clipped, newstart, newend;
5812 segmentmins[0] = min(start[0], end[0]);
5813 segmentmins[1] = min(start[1], end[1]);
5814 segmentmins[2] = min(start[2], end[2]);
5815 segmentmaxs[0] = max(start[0], end[0]);
5816 segmentmaxs[1] = max(start[1], end[1]);
5817 segmentmaxs[2] = max(start[2], end[2]);
5818 while (nodenum >= 0)
5820 node = model->collision_bih.nodes + nodenum;
5822 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
5825 axis = node->type - BIH_SPLITX;
5827 if (segmentmins[axis] <= node->backmax)
5829 if (segmentmaxs[axis] >= node->frontmin)
5830 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5831 nodenum = node->back;
5833 else if (segmentmaxs[axis] >= node->frontmin)
5834 nodenum = node->front;
5836 return; // trace falls between children
5838 frontdist1 = start[axis] - node->frontmin;
5839 frontdist2 = end[axis] - node->frontmin;
5840 backdist1 = start[axis] - node->backmax;
5841 backdist2 = end[axis] - node->backmax;
5854 if ((sideflags & 3) != 3)
5855 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5856 nodenum = node->back;
5858 else if ((sideflags & 3) != 3)
5859 nodenum = node->front;
5861 return; // trace falls between children
5866 // start end START END
5867 nodenum = node->front;
5870 // START end START END
5872 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5873 VectorLerp(start, frontfrac, end, newstart); start = newstart;
5874 segmentmins[0] = min(start[0], end[0]);
5875 segmentmins[1] = min(start[1], end[1]);
5876 segmentmins[2] = min(start[2], end[2]);
5877 segmentmaxs[0] = max(start[0], end[0]);
5878 segmentmaxs[1] = max(start[1], end[1]);
5879 segmentmaxs[2] = max(start[2], end[2]);
5881 nodenum = node->front;
5885 // start END START END
5886 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5887 VectorLerp(start, frontfrac, end, newend); end = newend;
5888 segmentmins[0] = min(start[0], end[0]);
5889 segmentmins[1] = min(start[1], end[1]);
5890 segmentmins[2] = min(start[2], end[2]);
5891 segmentmaxs[0] = max(start[0], end[0]);
5892 segmentmaxs[1] = max(start[1], end[1]);
5893 segmentmaxs[2] = max(start[2], end[2]);
5895 nodenum = node->front;
5898 // START END START END
5899 return; // line falls in gap between children
5901 // start end start END
5902 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5904 backfrac = backdist1 / (backdist1 - backdist2);
5905 VectorLerp(start, backfrac, end, newend); end = newend;
5906 segmentmins[0] = min(start[0], end[0]);
5907 segmentmins[1] = min(start[1], end[1]);
5908 segmentmins[2] = min(start[2], end[2]);
5909 segmentmaxs[0] = max(start[0], end[0]);
5910 segmentmaxs[1] = max(start[1], end[1]);
5911 segmentmaxs[2] = max(start[2], end[2]);
5913 nodenum = node->back;
5916 // START end start END
5918 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5919 VectorLerp(start, frontfrac, end, clipped);
5920 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
5921 backfrac = backdist1 / (backdist1 - backdist2);
5922 VectorLerp(start, backfrac, end, newend); end = newend;
5923 segmentmins[0] = min(start[0], end[0]);
5924 segmentmins[1] = min(start[1], end[1]);
5925 segmentmins[2] = min(start[2], end[2]);
5926 segmentmaxs[0] = max(start[0], end[0]);
5927 segmentmaxs[1] = max(start[1], end[1]);
5928 segmentmaxs[2] = max(start[2], end[2]);
5930 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5932 nodenum = node->back;
5935 // start END start END
5937 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5938 VectorLerp(start, frontfrac, end, clipped);
5939 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
5940 backfrac = backdist1 / (backdist1 - backdist2);
5941 VectorLerp(start, backfrac, end, newend); end = newend;
5942 segmentmins[0] = min(start[0], end[0]);
5943 segmentmins[1] = min(start[1], end[1]);
5944 segmentmins[2] = min(start[2], end[2]);
5945 segmentmaxs[0] = max(start[0], end[0]);
5946 segmentmaxs[1] = max(start[1], end[1]);
5947 segmentmaxs[2] = max(start[2], end[2]);
5949 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5951 nodenum = node->back;
5954 // START END start END
5956 backfrac = backdist1 / (backdist1 - backdist2);
5957 VectorLerp(start, backfrac, end, newend); end = newend;
5958 segmentmins[0] = min(start[0], end[0]);
5959 segmentmins[1] = min(start[1], end[1]);
5960 segmentmins[2] = min(start[2], end[2]);
5961 segmentmaxs[0] = max(start[0], end[0]);
5962 segmentmaxs[1] = max(start[1], end[1]);
5963 segmentmaxs[2] = max(start[2], end[2]);
5965 nodenum = node->back;
5968 // start end START end
5969 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5971 backfrac = backdist1 / (backdist1 - backdist2);
5972 VectorLerp(start, backfrac, end, newstart); start = newstart;
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
5985 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5986 VectorLerp(start, frontfrac, end, clipped);
5987 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
5988 backfrac = backdist1 / (backdist1 - backdist2);
5989 VectorLerp(start, backfrac, end, newstart); start = newstart;
5990 segmentmins[0] = min(start[0], end[0]);
5991 segmentmins[1] = min(start[1], end[1]);
5992 segmentmins[2] = min(start[2], end[2]);
5993 segmentmaxs[0] = max(start[0], end[0]);
5994 segmentmaxs[1] = max(start[1], end[1]);
5995 segmentmaxs[2] = max(start[2], end[2]);
5997 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5999 nodenum = node->back;
6002 // start END START end
6004 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6005 VectorLerp(start, frontfrac, end, clipped);
6006 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
6007 backfrac = backdist1 / (backdist1 - backdist2);
6008 VectorLerp(start, backfrac, end, newstart); start = newstart;
6009 segmentmins[0] = min(start[0], end[0]);
6010 segmentmins[1] = min(start[1], end[1]);
6011 segmentmins[2] = min(start[2], end[2]);
6012 segmentmaxs[0] = max(start[0], end[0]);
6013 segmentmaxs[1] = max(start[1], end[1]);
6014 segmentmaxs[2] = max(start[2], end[2]);
6016 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6018 nodenum = node->back;
6021 // START END START end
6023 backfrac = backdist1 / (backdist1 - backdist2);
6024 VectorLerp(start, backfrac, end, newstart); start = newstart;
6025 segmentmins[0] = min(start[0], end[0]);
6026 segmentmins[1] = min(start[1], end[1]);
6027 segmentmins[2] = min(start[2], end[2]);
6028 segmentmaxs[0] = max(start[0], end[0]);
6029 segmentmaxs[1] = max(start[1], end[1]);
6030 segmentmaxs[2] = max(start[2], end[2]);
6032 nodenum = node->back;
6035 // start end start end
6036 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6037 nodenum = node->back;
6040 // START end start end
6042 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6043 VectorLerp(start, frontfrac, end, clipped);
6044 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
6046 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6048 nodenum = node->back;
6051 // start END start end
6053 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6054 VectorLerp(start, frontfrac, end, clipped);
6055 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
6057 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6059 nodenum = node->back;
6062 // START END start end
6063 nodenum = node->back;
6069 if (!model->collision_bih.leafs)
6071 leaf = model->collision_bih.leafs + (-1-nodenum);
6073 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6079 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6080 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6082 case BIH_COLLISIONTRIANGLE:
6083 if (!mod_q3bsp_curves_collisions.integer)
6085 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6086 texture = model->data_textures + leaf->textureindex;
6087 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);
6089 case BIH_RENDERTRIANGLE:
6090 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6091 texture = model->data_textures + leaf->textureindex;
6092 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);
6097 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)
6099 const bih_leaf_t *leaf;
6100 const bih_node_t *node;
6101 const colbrushf_t *brush;
6103 const texture_t *texture;
6105 while (nodenum >= 0)
6107 node = model->collision_bih.nodes + nodenum;
6108 axis = node->type - BIH_SPLITX;
6110 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6114 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6115 nodenum = node->back;
6118 if (segmentmins[axis] <= node->backmax)
6120 if (segmentmaxs[axis] >= node->frontmin)
6121 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6122 nodenum = node->back;
6124 else if (segmentmaxs[axis] >= node->frontmin)
6125 nodenum = node->front;
6127 return; // trace falls between children
6129 if (!model->collision_bih.leafs)
6131 leaf = model->collision_bih.leafs + (-1-nodenum);
6133 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6139 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6140 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6142 case BIH_COLLISIONTRIANGLE:
6143 if (!mod_q3bsp_curves_collisions.integer)
6145 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6146 texture = model->data_textures + leaf->textureindex;
6147 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);
6149 case BIH_RENDERTRIANGLE:
6150 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6151 texture = model->data_textures + leaf->textureindex;
6152 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);
6157 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)
6159 memset(trace, 0, sizeof(*trace));
6160 trace->fraction = 1;
6161 trace->realfraction = 1;
6162 trace->hitsupercontentsmask = hitsupercontentsmask;
6163 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6166 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)
6168 if (VectorCompare(start, end))
6170 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6174 memset(trace, 0, sizeof(*trace));
6175 trace->fraction = 1;
6176 trace->realfraction = 1;
6177 trace->hitsupercontentsmask = hitsupercontentsmask;
6178 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6181 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)
6183 float segmentmins[3], segmentmaxs[3];
6184 colboxbrushf_t thisbrush_start, thisbrush_end;
6185 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6187 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6189 vec3_t shiftstart, shiftend;
6190 VectorAdd(start, boxmins, shiftstart);
6191 VectorAdd(end, boxmins, shiftend);
6192 if (VectorCompare(start, end))
6193 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6195 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6199 // box trace, performed as brush trace
6200 memset(trace, 0, sizeof(*trace));
6201 trace->fraction = 1;
6202 trace->realfraction = 1;
6203 trace->hitsupercontentsmask = hitsupercontentsmask;
6204 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6205 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6206 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6207 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6208 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6209 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6210 VectorAdd(start, boxmins, boxstartmins);
6211 VectorAdd(start, boxmaxs, boxstartmaxs);
6212 VectorAdd(end, boxmins, boxendmins);
6213 VectorAdd(end, boxmaxs, boxendmaxs);
6214 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6215 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6216 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6219 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)
6221 float segmentmins[3], segmentmaxs[3];
6223 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6225 if (VectorCompare(start->mins, end->mins))
6226 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6228 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6232 // box trace, performed as brush trace
6233 memset(trace, 0, sizeof(*trace));
6234 trace->fraction = 1;
6235 trace->realfraction = 1;
6236 trace->hitsupercontentsmask = hitsupercontentsmask;
6237 segmentmins[0] = min(start->mins[0], end->mins[0]);
6238 segmentmins[1] = min(start->mins[1], end->mins[1]);
6239 segmentmins[2] = min(start->mins[2], end->mins[2]);
6240 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6241 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6242 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6243 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, segmentmins, segmentmaxs);
6246 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6249 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6250 return trace.startsupercontents;
6253 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)
6256 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6258 int hitsupercontents;
6259 VectorSet(end, start[0], start[1], model->normalmins[2]);
6261 memset(trace, 0, sizeof(*trace));
6262 trace->fraction = 1;
6263 trace->realfraction = 1;
6264 trace->hitsupercontentsmask = hitsupercontentsmask;
6266 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6267 hitsupercontents = trace->hitsupercontents;
6268 memset(trace, 0, sizeof(*trace));
6269 trace->fraction = 1;
6270 trace->realfraction = 1;
6271 trace->hitsupercontentsmask = hitsupercontentsmask;
6272 trace->startsupercontents = hitsupercontents;
6276 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6279 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6282 VectorSet(end, start[0], start[1], model->normalmins[2]);
6283 memset(&trace, 0, sizeof(trace));
6285 trace.realfraction = 1;
6286 trace.hitsupercontentsmask = 0;
6287 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(&trace, model, model->collision_bih.rootnode, start, end, start, end);
6288 return trace.hitsupercontents;
6294 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6299 // find which leaf the point is in
6301 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6302 // point trace the brushes
6303 leaf = (mleaf_t *)node;
6304 for (i = 0;i < leaf->numleafbrushes;i++)
6306 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6307 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6309 brush->markframe = markframe;
6310 Collision_TracePointBrushFloat(trace, point, brush);
6313 // can't do point traces on curves (they have no thickness)
6316 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)
6318 int i, startside, endside;
6319 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6321 msurface_t *surface;
6324 // walk the tree until we hit a leaf, recursing for any split cases
6328 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6330 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6331 node = node->children[1];
6333 // abort if this part of the bsp tree can not be hit by this trace
6334 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6336 plane = node->plane;
6337 // axial planes are much more common than non-axial, so an optimized
6338 // axial case pays off here
6339 if (plane->type < 3)
6341 dist1 = start[plane->type] - plane->dist;
6342 dist2 = end[plane->type] - plane->dist;
6346 dist1 = DotProduct(start, plane->normal) - plane->dist;
6347 dist2 = DotProduct(end, plane->normal) - plane->dist;
6349 startside = dist1 < 0;
6350 endside = dist2 < 0;
6351 if (startside == endside)
6353 // most of the time the line fragment is on one side of the plane
6354 node = node->children[startside];
6358 // line crosses node plane, split the line
6359 dist1 = PlaneDiff(linestart, plane);
6360 dist2 = PlaneDiff(lineend, plane);
6361 midfrac = dist1 / (dist1 - dist2);
6362 VectorLerp(linestart, midfrac, lineend, mid);
6363 // take the near side first
6364 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6365 // if we found an impact on the front side, don't waste time
6366 // exploring the far side
6367 if (midfrac <= trace->realfraction)
6368 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6373 // abort if this part of the bsp tree can not be hit by this trace
6374 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6377 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6378 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6379 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6380 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6381 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6382 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6383 // line trace the brushes
6384 leaf = (mleaf_t *)node;
6386 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6389 for (i = 0;i < leaf->numleafbrushes;i++)
6391 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6392 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6394 brush->markframe = markframe;
6395 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6398 // can't do point traces on curves (they have no thickness)
6399 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6401 // line trace the curves
6402 for (i = 0;i < leaf->numleafsurfaces;i++)
6404 surface = model->data_surfaces + leaf->firstleafsurface[i];
6405 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6407 surface->deprecatedq3collisionmarkframe = markframe;
6408 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);
6414 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)
6420 msurface_t *surface;
6422 float nodesegmentmins[3], nodesegmentmaxs[3];
6423 // walk the tree until we hit a leaf, recursing for any split cases
6427 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6429 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6430 node = node->children[1];
6432 // abort if this part of the bsp tree can not be hit by this trace
6433 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6435 plane = node->plane;
6436 // axial planes are much more common than non-axial, so an optimized
6437 // axial case pays off here
6438 if (plane->type < 3)
6440 // this is an axial plane, compare bounding box directly to it and
6441 // recurse sides accordingly
6442 // recurse down node sides
6443 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6444 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6445 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6446 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6450 // this is a non-axial plane, so check if the start and end boxes
6451 // are both on one side of the plane to handle 'diagonal' cases
6452 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6456 // segment crosses plane
6457 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6460 // if sides == 0 then the trace itself is bogus (Not A Number values),
6461 // in this case we simply pretend the trace hit nothing
6463 return; // ERROR: NAN bounding box!
6464 // take whichever side the segment box is on
6465 node = node->children[sides - 1];
6468 // abort if this part of the bsp tree can not be hit by this trace
6469 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6471 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6472 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6473 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6474 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6475 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6476 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6478 leaf = (mleaf_t *)node;
6480 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6483 for (i = 0;i < leaf->numleafbrushes;i++)
6485 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6486 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6488 brush->markframe = markframe;
6489 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6492 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6494 for (i = 0;i < leaf->numleafsurfaces;i++)
6496 surface = model->data_surfaces + leaf->firstleafsurface[i];
6497 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6499 surface->deprecatedq3collisionmarkframe = markframe;
6500 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);
6507 static int markframe = 0;
6509 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)
6513 memset(trace, 0, sizeof(*trace));
6514 trace->fraction = 1;
6515 trace->realfraction = 1;
6516 trace->hitsupercontentsmask = hitsupercontentsmask;
6517 if (mod_collision_bih.integer)
6518 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6519 else if (model->brush.submodel)
6521 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6522 if (brush->colbrushf)
6523 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6526 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6529 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)
6532 float segmentmins[3], segmentmaxs[3];
6533 msurface_t *surface;
6536 if (VectorCompare(start, end))
6538 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6542 memset(trace, 0, sizeof(*trace));
6543 trace->fraction = 1;
6544 trace->realfraction = 1;
6545 trace->hitsupercontentsmask = hitsupercontentsmask;
6546 segmentmins[0] = min(start[0], end[0]) - 1;
6547 segmentmins[1] = min(start[1], end[1]) - 1;
6548 segmentmins[2] = min(start[2], end[2]) - 1;
6549 segmentmaxs[0] = max(start[0], end[0]) + 1;
6550 segmentmaxs[1] = max(start[1], end[1]) + 1;
6551 segmentmaxs[2] = max(start[2], end[2]) + 1;
6552 if (mod_collision_bih.integer)
6553 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6554 else if (model->brush.submodel)
6556 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6557 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6558 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6559 if (mod_q3bsp_curves_collisions.integer)
6560 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6561 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6562 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);
6565 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6568 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)
6571 float segmentmins[3], segmentmaxs[3];
6572 msurface_t *surface;
6574 colboxbrushf_t thisbrush_start, thisbrush_end;
6575 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6577 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6579 vec3_t shiftstart, shiftend;
6580 VectorAdd(start, boxmins, shiftstart);
6581 VectorAdd(end, boxmins, shiftend);
6582 if (VectorCompare(start, end))
6583 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6585 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6589 // box trace, performed as brush trace
6590 memset(trace, 0, sizeof(*trace));
6591 trace->fraction = 1;
6592 trace->realfraction = 1;
6593 trace->hitsupercontentsmask = hitsupercontentsmask;
6594 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6595 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6596 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6597 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6598 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6599 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6600 VectorAdd(start, boxmins, boxstartmins);
6601 VectorAdd(start, boxmaxs, boxstartmaxs);
6602 VectorAdd(end, boxmins, boxendmins);
6603 VectorAdd(end, boxmaxs, boxendmaxs);
6604 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6605 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6606 if (mod_collision_bih.integer)
6607 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6608 else if (model->brush.submodel)
6610 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6611 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6612 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, brush->colbrushf, brush->colbrushf);
6613 if (mod_q3bsp_curves_collisions.integer)
6614 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6615 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6616 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);
6619 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, &thisbrush_start.brush, &thisbrush_end.brush, ++markframe, segmentmins, segmentmaxs);
6622 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)
6624 float segmentmins[3], segmentmaxs[3];
6626 msurface_t *surface;
6629 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6631 if (VectorCompare(start->mins, end->mins))
6632 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6634 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6638 // box trace, performed as brush trace
6639 memset(trace, 0, sizeof(*trace));
6640 trace->fraction = 1;
6641 trace->realfraction = 1;
6642 trace->hitsupercontentsmask = hitsupercontentsmask;
6643 segmentmins[0] = min(start->mins[0], end->mins[0]);
6644 segmentmins[1] = min(start->mins[1], end->mins[1]);
6645 segmentmins[2] = min(start->mins[2], end->mins[2]);
6646 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6647 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6648 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6649 if (mod_collision_bih.integer)
6650 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, segmentmins, segmentmaxs);
6651 else if (model->brush.submodel)
6653 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6654 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6655 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6656 if (mod_q3bsp_curves_collisions.integer)
6657 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6658 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6659 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);
6662 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6665 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6668 int supercontents = 0;
6670 if (mod_collision_bih.integer)
6673 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6674 supercontents = trace.startsupercontents;
6676 // test if the point is inside each brush
6677 else if (model->brush.submodel)
6679 // submodels are effectively one leaf
6680 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6681 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6682 supercontents |= brush->colbrushf->supercontents;
6686 mnode_t *node = model->brush.data_nodes;
6688 // find which leaf the point is in
6690 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6691 leaf = (mleaf_t *)node;
6692 // now check the brushes in the leaf
6693 for (i = 0;i < leaf->numleafbrushes;i++)
6695 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6696 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6697 supercontents |= brush->colbrushf->supercontents;
6700 return supercontents;
6703 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6711 int nummodelbrushes = model->nummodelbrushes;
6712 int nummodelsurfaces = model->nummodelsurfaces;
6714 const int *collisionelement3i;
6715 const float *collisionvertex3f;
6716 const int *renderelement3i;
6717 const float *rendervertex3f;
6718 bih_leaf_t *bihleafs;
6719 bih_node_t *bihnodes;
6721 int *temp_leafsortscratch;
6722 const msurface_t *surface;
6723 const q3mbrush_t *brush;
6725 // find out how many BIH leaf nodes we need
6727 if (userendersurfaces)
6729 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6730 bihnumleafs += surface->num_triangles;
6734 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6735 if (brush->colbrushf)
6737 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6739 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6740 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
6742 bihnumleafs += surface->num_collisiontriangles;
6749 // allocate the memory for the BIH leaf nodes
6750 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6752 // now populate the BIH leaf nodes
6755 // add render surfaces
6756 renderelement3i = model->surfmesh.data_element3i;
6757 rendervertex3f = model->surfmesh.data_vertex3f;
6758 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6760 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6762 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6764 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6765 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6766 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6767 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6768 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6769 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6770 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6771 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6772 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6773 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6778 if (!userendersurfaces)
6780 // add collision brushes
6781 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6783 if (!brush->colbrushf)
6785 bihleafs[bihleafindex].type = BIH_BRUSH;
6786 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6787 bihleafs[bihleafindex].surfaceindex = -1;
6788 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6789 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6790 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6794 // add collision surfaces
6795 collisionelement3i = model->brush.data_collisionelement3i;
6796 collisionvertex3f = model->brush.data_collisionvertex3f;
6797 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6799 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6801 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
6802 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6803 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6804 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6805 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6806 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6807 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6808 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6809 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6810 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6816 // allocate buffers for the produced and temporary data
6817 bihmaxnodes = bihnumleafs - 1;
6818 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6819 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6820 temp_leafsortscratch = temp_leafsort + bihnumleafs;
6823 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6825 // we're done with the temporary data
6826 Mem_Free(temp_leafsort);
6828 // resize the BIH nodes array if it over-allocated
6829 if (out->maxnodes > out->numnodes)
6831 out->maxnodes = out->numnodes;
6832 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
6838 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6840 int supercontents = 0;
6841 if (nativecontents & CONTENTSQ3_SOLID)
6842 supercontents |= SUPERCONTENTS_SOLID;
6843 if (nativecontents & CONTENTSQ3_WATER)
6844 supercontents |= SUPERCONTENTS_WATER;
6845 if (nativecontents & CONTENTSQ3_SLIME)
6846 supercontents |= SUPERCONTENTS_SLIME;
6847 if (nativecontents & CONTENTSQ3_LAVA)
6848 supercontents |= SUPERCONTENTS_LAVA;
6849 if (nativecontents & CONTENTSQ3_BODY)
6850 supercontents |= SUPERCONTENTS_BODY;
6851 if (nativecontents & CONTENTSQ3_CORPSE)
6852 supercontents |= SUPERCONTENTS_CORPSE;
6853 if (nativecontents & CONTENTSQ3_NODROP)
6854 supercontents |= SUPERCONTENTS_NODROP;
6855 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6856 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6857 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6858 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6859 if (nativecontents & CONTENTSQ3_DONOTENTER)
6860 supercontents |= SUPERCONTENTS_DONOTENTER;
6861 if (nativecontents & CONTENTSQ3_BOTCLIP)
6862 supercontents |= SUPERCONTENTS_BOTCLIP;
6863 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6864 supercontents |= SUPERCONTENTS_OPAQUE;
6865 return supercontents;
6868 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6870 int nativecontents = 0;
6871 if (supercontents & SUPERCONTENTS_SOLID)
6872 nativecontents |= CONTENTSQ3_SOLID;
6873 if (supercontents & SUPERCONTENTS_WATER)
6874 nativecontents |= CONTENTSQ3_WATER;
6875 if (supercontents & SUPERCONTENTS_SLIME)
6876 nativecontents |= CONTENTSQ3_SLIME;
6877 if (supercontents & SUPERCONTENTS_LAVA)
6878 nativecontents |= CONTENTSQ3_LAVA;
6879 if (supercontents & SUPERCONTENTS_BODY)
6880 nativecontents |= CONTENTSQ3_BODY;
6881 if (supercontents & SUPERCONTENTS_CORPSE)
6882 nativecontents |= CONTENTSQ3_CORPSE;
6883 if (supercontents & SUPERCONTENTS_NODROP)
6884 nativecontents |= CONTENTSQ3_NODROP;
6885 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6886 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6887 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6888 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6889 if (supercontents & SUPERCONTENTS_DONOTENTER)
6890 nativecontents |= CONTENTSQ3_DONOTENTER;
6891 if (supercontents & SUPERCONTENTS_BOTCLIP)
6892 nativecontents |= CONTENTSQ3_BOTCLIP;
6893 if (!(supercontents & SUPERCONTENTS_OPAQUE))
6894 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6895 return nativecontents;
6898 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6903 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6904 node = node->children[1];
6906 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6907 if (loadmodel->brush.num_leafs < numleafs)
6908 loadmodel->brush.num_leafs = numleafs;
6911 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6914 q3dheader_t *header;
6915 float corner[3], yawradius, modelradius;
6917 mod->modeldatatypestring = "Q3BSP";
6919 mod->type = mod_brushq3;
6920 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6923 header = (q3dheader_t *)buffer;
6924 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6925 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6927 i = LittleLong(header->version);
6928 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
6929 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
6931 mod->soundfromcenter = true;
6932 mod->TraceBox = Mod_Q3BSP_TraceBox;
6933 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
6934 mod->TraceLine = Mod_Q3BSP_TraceLine;
6935 mod->TracePoint = Mod_Q3BSP_TracePoint;
6936 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
6937 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
6938 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
6939 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
6940 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
6941 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
6942 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
6943 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
6944 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
6945 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
6946 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
6947 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
6948 mod->brush.AmbientSoundLevelsForPoint = NULL;
6949 mod->brush.RoundUpToHullSize = NULL;
6950 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
6951 mod->Draw = R_Q1BSP_Draw;
6952 mod->DrawDepth = R_Q1BSP_DrawDepth;
6953 mod->DrawDebug = R_Q1BSP_DrawDebug;
6954 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
6955 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
6956 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
6957 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
6958 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
6959 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
6960 mod->DrawLight = R_Q1BSP_DrawLight;
6962 mod_base = (unsigned char *)header;
6964 // swap all the lumps
6965 header->ident = LittleLong(header->ident);
6966 header->version = LittleLong(header->version);
6967 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
6968 for (i = 0;i < lumps;i++)
6970 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
6971 if((char *) bufferend < (char *) buffer + j)
6972 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
6973 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
6974 if((char *) bufferend < (char *) buffer + j)
6975 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
6978 * NO, do NOT clear them!
6979 * they contain actual data referenced by other stuff.
6980 * Instead, before using the advertisements lump, check header->versio
6982 * Sorry, but otherwise it breaks memory of the first lump.
6983 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
6985 header->lumps[i].fileofs = 0;
6986 header->lumps[i].filelen = 0;
6990 mod->brush.qw_md4sum = 0;
6991 mod->brush.qw_md4sum2 = 0;
6992 for (i = 0;i < lumps;i++)
6994 if (i == Q3LUMP_ENTITIES)
6996 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
6997 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
6999 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7001 // all this checksumming can take a while, so let's send keepalives here too
7002 CL_KeepaliveMessage(false);
7005 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7006 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7007 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7008 if (header->version == Q3BSPVERSION_IG)
7009 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7011 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7012 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7013 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7014 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7015 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7016 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7017 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7018 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7019 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7020 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7021 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7022 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7023 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7024 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7025 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7027 // the MakePortals code works fine on the q3bsp data as well
7028 Mod_Q1BSP_MakePortals();
7030 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7031 loadmodel->brush.supportwateralpha = true;
7033 // make a single combined shadow mesh to allow optimized shadow volume creation
7034 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7036 loadmodel->brush.num_leafs = 0;
7037 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7039 if (loadmodel->brush.numsubmodels)
7040 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7043 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7048 // duplicate the basic information
7049 dpsnprintf(name, sizeof(name), "*%i", i);
7050 mod = Mod_FindName(name, loadmodel->name);
7051 // copy the base model to this one
7053 // rename the clone back to its proper name
7054 strlcpy(mod->name, name, sizeof(mod->name));
7055 mod->brush.parentmodel = loadmodel;
7056 // textures and memory belong to the main model
7057 mod->texturepool = NULL;
7058 mod->mempool = NULL;
7059 mod->brush.GetPVS = NULL;
7060 mod->brush.FatPVS = NULL;
7061 mod->brush.BoxTouchingPVS = NULL;
7062 mod->brush.BoxTouchingLeafPVS = NULL;
7063 mod->brush.BoxTouchingVisibleLeafs = NULL;
7064 mod->brush.FindBoxClusters = NULL;
7065 mod->brush.LightPoint = NULL;
7066 mod->brush.AmbientSoundLevelsForPoint = NULL;
7068 mod->brush.submodel = i;
7069 if (loadmodel->brush.submodels)
7070 loadmodel->brush.submodels[i] = mod;
7072 // make the model surface list (used by shadowing/lighting)
7073 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7074 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7075 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7076 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7077 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7078 Mod_MakeSortedSurfaces(mod);
7080 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7081 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7082 // enlarge the bounding box to enclose all geometry of this model,
7083 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7084 // which can in turn mess up the farclip (as well as culling when
7085 // outside the level - an unimportant concern)
7087 //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]);
7088 for (j = 0;j < mod->nummodelsurfaces;j++)
7090 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7091 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7093 if (!surface->num_vertices)
7095 for (k = 0;k < surface->num_vertices;k++, v += 3)
7097 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7098 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7099 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7100 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7101 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7102 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7105 //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]);
7106 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7107 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7108 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7109 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7110 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7111 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7112 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7113 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7114 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7115 mod->yawmins[2] = mod->normalmins[2];
7116 mod->yawmaxs[2] = mod->normalmaxs[2];
7117 mod->radius = modelradius;
7118 mod->radius2 = modelradius * modelradius;
7120 // this gets altered below if sky or water is used
7121 mod->DrawSky = NULL;
7122 mod->DrawAddWaterPlanes = NULL;
7124 for (j = 0;j < mod->nummodelsurfaces;j++)
7125 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7127 if (j < mod->nummodelsurfaces)
7128 mod->DrawSky = R_Q1BSP_DrawSky;
7130 for (j = 0;j < mod->nummodelsurfaces;j++)
7131 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7133 if (j < mod->nummodelsurfaces)
7134 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7136 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7137 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7139 // generate VBOs and other shared data before cloning submodels
7144 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);
7147 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7149 int i = LittleLong(((int *)buffer)[1]);
7150 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7151 Mod_Q3BSP_Load(mod,buffer, bufferend);
7152 else if (i == Q2BSPVERSION)
7153 Mod_Q2BSP_Load(mod,buffer, bufferend);
7155 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7158 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7160 Host_Error("Mod_MAP_Load: not yet implemented");
7166 typedef struct objvertex_s
7177 static unsigned char nobsp_pvs[1] = {1};
7179 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7181 const char *textbase = (char *)buffer, *text = textbase;
7185 char materialname[MAX_QPATH];
7186 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7187 int index1, index2, index3;
7188 objvertex_t vfirst, vprev, vcurrent;
7191 int numtriangles = 0;
7192 int maxtriangles = 0;
7193 objvertex_t *vertices = NULL;
7195 int maxtextures = 0, numtextures = 0, textureindex = 0;
7196 int maxv = 0, numv = 1;
7197 int maxvt = 0, numvt = 1;
7198 int maxvn = 0, numvn = 1;
7199 char *texturenames = NULL;
7200 float dist, modelradius, modelyawradius, yawradius;
7207 objvertex_t *thisvertex = NULL;
7208 int vertexhashindex;
7209 int *vertexhashtable = NULL;
7210 objvertex_t *vertexhashdata = NULL;
7211 objvertex_t *vdata = NULL;
7212 int vertexhashsize = 0;
7213 int vertexhashcount = 0;
7214 skinfile_t *skinfiles = NULL;
7215 unsigned char *data = NULL;
7216 int *submodelfirstsurface;
7217 msurface_t *surface;
7218 msurface_t *tempsurfaces;
7220 memset(&vfirst, 0, sizeof(vfirst));
7221 memset(&vprev, 0, sizeof(vprev));
7222 memset(&vcurrent, 0, sizeof(vcurrent));
7224 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7226 loadmodel->modeldatatypestring = "OBJ";
7228 loadmodel->type = mod_obj;
7229 loadmodel->soundfromcenter = true;
7230 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7231 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7232 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7233 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7234 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7235 loadmodel->brush.TraceLineOfSight = NULL;
7236 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7237 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7238 loadmodel->brush.GetPVS = NULL;
7239 loadmodel->brush.FatPVS = NULL;
7240 loadmodel->brush.BoxTouchingPVS = NULL;
7241 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7242 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7243 loadmodel->brush.FindBoxClusters = NULL;
7244 loadmodel->brush.LightPoint = NULL;
7245 loadmodel->brush.FindNonSolidLocation = NULL;
7246 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7247 loadmodel->brush.RoundUpToHullSize = NULL;
7248 loadmodel->brush.PointInLeaf = NULL;
7249 loadmodel->Draw = R_Q1BSP_Draw;
7250 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7251 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7252 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7253 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7254 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7255 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7256 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7257 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7258 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7260 skinfiles = Mod_LoadSkinFiles();
7261 if (loadmodel->numskins < 1)
7262 loadmodel->numskins = 1;
7264 // make skinscenes for the skins (no groups)
7265 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7266 for (i = 0;i < loadmodel->numskins;i++)
7268 loadmodel->skinscenes[i].firstframe = i;
7269 loadmodel->skinscenes[i].framecount = 1;
7270 loadmodel->skinscenes[i].loop = true;
7271 loadmodel->skinscenes[i].framerate = 10;
7277 // parse the OBJ text now
7280 static char emptyarg[1] = "";
7285 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7286 line[linelen] = text[linelen];
7288 for (argc = 0;argc < 4;argc++)
7289 argv[argc] = emptyarg;
7292 while (*s == ' ' || *s == '\t')
7302 while (*s == ' ' || *s == '\t')
7312 if (argv[0][0] == '#')
7314 if (!strcmp(argv[0], "v"))
7318 maxv = max(maxv * 2, 1024);
7319 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7321 v[numv*3+0] = atof(argv[1]);
7322 v[numv*3+2] = atof(argv[2]);
7323 v[numv*3+1] = atof(argv[3]);
7326 else if (!strcmp(argv[0], "vt"))
7330 maxvt = max(maxvt * 2, 1024);
7331 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7333 vt[numvt*2+0] = atof(argv[1]);
7334 vt[numvt*2+1] = 1-atof(argv[2]);
7337 else if (!strcmp(argv[0], "vn"))
7341 maxvn = max(maxvn * 2, 1024);
7342 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7344 vn[numvn*3+0] = atof(argv[1]);
7345 vn[numvn*3+2] = atof(argv[2]);
7346 vn[numvn*3+1] = atof(argv[3]);
7349 else if (!strcmp(argv[0], "f"))
7353 if (maxtextures <= numtextures)
7355 maxtextures = max(maxtextures * 2, 256);
7356 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7358 textureindex = numtextures++;
7359 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7361 for (j = 1;j < argc;j++)
7363 index1 = atoi(argv[j]);
7364 while(argv[j][0] && argv[j][0] != '/')
7368 index2 = atoi(argv[j]);
7369 while(argv[j][0] && argv[j][0] != '/')
7373 index3 = atoi(argv[j]);
7374 // negative refers to a recent vertex
7375 // zero means not specified
7376 // positive means an absolute vertex index
7378 index1 = numv - index1;
7380 index2 = numvt - index2;
7382 index3 = numvn - index3;
7383 vcurrent.nextindex = -1;
7384 vcurrent.textureindex = textureindex;
7385 vcurrent.submodelindex = submodelindex;
7386 VectorCopy(v + 3*index1, vcurrent.v);
7387 Vector2Copy(vt + 2*index2, vcurrent.vt);
7388 VectorCopy(vn + 3*index3, vcurrent.vn);
7389 if (numtriangles == 0)
7391 VectorCopy(vcurrent.v, mins);
7392 VectorCopy(vcurrent.v, maxs);
7396 mins[0] = min(mins[0], vcurrent.v[0]);
7397 mins[1] = min(mins[1], vcurrent.v[1]);
7398 mins[2] = min(mins[2], vcurrent.v[2]);
7399 maxs[0] = max(maxs[0], vcurrent.v[0]);
7400 maxs[1] = max(maxs[1], vcurrent.v[1]);
7401 maxs[2] = max(maxs[2], vcurrent.v[2]);
7407 if (maxtriangles <= numtriangles)
7409 maxtriangles = max(maxtriangles * 2, 32768);
7410 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7412 vertices[numtriangles*3+0] = vfirst;
7413 vertices[numtriangles*3+1] = vprev;
7414 vertices[numtriangles*3+2] = vcurrent;
7420 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7422 submodelindex = atof(argv[1]);
7423 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7425 else if (!strcmp(argv[0], "usemtl"))
7427 for (i = 0;i < numtextures;i++)
7428 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7430 if (i < numtextures)
7434 if (maxtextures <= numtextures)
7436 maxtextures = max(maxtextures * 2, 256);
7437 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7439 textureindex = numtextures++;
7440 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7445 // now that we have the OBJ data loaded as-is, we can convert it
7447 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7448 VectorCopy(mins, loadmodel->normalmins);
7449 VectorCopy(maxs, loadmodel->normalmaxs);
7450 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7451 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7452 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7453 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7454 modelradius = modelyawradius + modelradius * modelradius;
7455 modelyawradius = sqrt(modelyawradius);
7456 modelradius = sqrt(modelradius);
7457 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7458 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7459 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7460 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7461 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7462 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7463 loadmodel->radius = modelradius;
7464 loadmodel->radius2 = modelradius * modelradius;
7466 // allocate storage for triangles
7467 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7468 // allocate vertex hash structures to build an optimal vertex subset
7469 vertexhashsize = numtriangles*2;
7470 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7471 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7472 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7473 vertexhashcount = 0;
7475 // gather surface stats for assigning vertex/triangle ranges
7479 loadmodel->num_surfaces = 0;
7480 // allocate storage for the worst case number of surfaces, later we resize
7481 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7482 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7483 surface = tempsurfaces;
7484 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7486 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7487 for (textureindex = 0;textureindex < numtextures;textureindex++)
7489 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7491 thisvertex = vertices + vertexindex;
7492 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7495 // skip the surface creation if there are no triangles for it
7496 if (vertexindex == numtriangles*3)
7498 // create a surface for these vertices
7499 surfacevertices = 0;
7500 surfaceelements = 0;
7501 // we hack in a texture index in the surface to be fixed up later...
7502 surface->texture = (texture_t *)((size_t)textureindex);
7503 // calculate bounds as we go
7504 VectorCopy(thisvertex->v, surface->mins);
7505 VectorCopy(thisvertex->v, surface->maxs);
7506 for (;vertexindex < numtriangles*3;vertexindex++)
7508 thisvertex = vertices + vertexindex;
7509 if (thisvertex->submodelindex != submodelindex)
7511 if (thisvertex->textureindex != textureindex)
7513 // add vertex to surface bounds
7514 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7515 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7516 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7517 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7518 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7519 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7520 // add the vertex if it is not found in the merged set, and
7521 // get its index (triangle element) for the surface
7522 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7523 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7525 vdata = vertexhashdata + i;
7526 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7531 i = vertexhashcount++;
7532 vdata = vertexhashdata + i;
7533 *vdata = *thisvertex;
7534 vdata->nextindex = vertexhashtable[vertexhashindex];
7535 vertexhashtable[vertexhashindex] = i;
7538 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7541 surfacetriangles = surfaceelements / 3;
7542 surface->num_vertices = surfacevertices;
7543 surface->num_triangles = surfacetriangles;
7544 surface->num_firstvertex = firstvertex;
7545 surface->num_firsttriangle = firsttriangle;
7546 firstvertex += surface->num_vertices;
7547 firsttriangle += surface->num_triangles;
7549 loadmodel->num_surfaces++;
7552 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7553 numvertices = firstvertex;
7554 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7555 tempsurfaces = NULL;
7557 // allocate storage for final mesh data
7558 loadmodel->num_textures = numtextures * loadmodel->numskins;
7559 loadmodel->num_texturesperskin = numtextures;
7560 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 *));
7561 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7562 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7563 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7564 loadmodel->surfmesh.num_vertices = numvertices;
7565 loadmodel->surfmesh.num_triangles = numtriangles;
7566 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7567 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7568 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7569 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7570 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7571 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7572 if (loadmodel->surfmesh.num_vertices <= 65536)
7573 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7575 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7577 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7578 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7579 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7582 // load the textures
7583 for (textureindex = 0;textureindex < numtextures;textureindex++)
7584 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7585 Mod_FreeSkinFiles(skinfiles);
7587 // set the surface textures to their real values now that we loaded them...
7588 for (i = 0;i < loadmodel->num_surfaces;i++)
7589 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7593 Mem_Free(texturenames);
7597 Mem_Free(vertexhashtable);
7598 Mem_Free(vertexhashdata);
7600 // make a single combined shadow mesh to allow optimized shadow volume creation
7601 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7603 // compute all the mesh information that was not loaded from the file
7604 if (loadmodel->surfmesh.data_element3s)
7605 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7606 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7607 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7608 // generate normals if the file did not have them
7609 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7610 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
7611 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, true);
7612 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7614 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7615 loadmodel->brush.num_visleafs = 1;
7616 loadmodel->brush.num_leafs = 1;
7617 loadmodel->brush.num_nodes = 0;
7618 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7619 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7620 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7621 loadmodel->brush.num_pvsclusters = 1;
7622 loadmodel->brush.num_pvsclusterbytes = 1;
7623 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7624 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7625 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7626 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7627 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7628 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7629 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7630 loadmodel->brush.data_leafs->clusterindex = 0;
7631 loadmodel->brush.data_leafs->areaindex = 0;
7632 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7633 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7634 loadmodel->brush.data_leafs->numleafbrushes = 0;
7635 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7636 loadmodel->brush.supportwateralpha = true;
7638 if (loadmodel->brush.numsubmodels)
7639 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7642 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7647 // duplicate the basic information
7648 dpsnprintf(name, sizeof(name), "*%i", i);
7649 mod = Mod_FindName(name, loadmodel->name);
7650 // copy the base model to this one
7652 // rename the clone back to its proper name
7653 strlcpy(mod->name, name, sizeof(mod->name));
7654 mod->brush.parentmodel = loadmodel;
7655 // textures and memory belong to the main model
7656 mod->texturepool = NULL;
7657 mod->mempool = NULL;
7658 mod->brush.GetPVS = NULL;
7659 mod->brush.FatPVS = NULL;
7660 mod->brush.BoxTouchingPVS = NULL;
7661 mod->brush.BoxTouchingLeafPVS = NULL;
7662 mod->brush.BoxTouchingVisibleLeafs = NULL;
7663 mod->brush.FindBoxClusters = NULL;
7664 mod->brush.LightPoint = NULL;
7665 mod->brush.AmbientSoundLevelsForPoint = NULL;
7667 mod->brush.submodel = i;
7668 if (loadmodel->brush.submodels)
7669 loadmodel->brush.submodels[i] = mod;
7671 // make the model surface list (used by shadowing/lighting)
7672 mod->firstmodelsurface = submodelfirstsurface[i];
7673 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7674 mod->firstmodelbrush = 0;
7675 mod->nummodelbrushes = 0;
7676 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
7677 Mod_MakeSortedSurfaces(mod);
7679 VectorClear(mod->normalmins);
7680 VectorClear(mod->normalmaxs);
7682 for (j = 0;j < mod->nummodelsurfaces;j++)
7684 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7685 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7687 if (!surface->num_vertices)
7692 VectorCopy(v, mod->normalmins);
7693 VectorCopy(v, mod->normalmaxs);
7695 for (k = 0;k < surface->num_vertices;k++, v += 3)
7697 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7698 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7699 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7700 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7701 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7702 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7705 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7706 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7707 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7708 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7709 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7710 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7711 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7712 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7713 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7714 mod->yawmins[2] = mod->normalmins[2];
7715 mod->yawmaxs[2] = mod->normalmaxs[2];
7716 mod->radius = modelradius;
7717 mod->radius2 = modelradius * modelradius;
7719 // this gets altered below if sky or water is used
7720 mod->DrawSky = NULL;
7721 mod->DrawAddWaterPlanes = NULL;
7723 for (j = 0;j < mod->nummodelsurfaces;j++)
7724 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7726 if (j < mod->nummodelsurfaces)
7727 mod->DrawSky = R_Q1BSP_DrawSky;
7729 for (j = 0;j < mod->nummodelsurfaces;j++)
7730 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7732 if (j < mod->nummodelsurfaces)
7733 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7735 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
7736 mod->render_bih = mod->collision_bih;
7738 // generate VBOs and other shared data before cloning submodels
7743 Mem_Free(submodelfirstsurface);
7745 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);
7760 typedef struct objvertex_s
7768 typedef struct objtriangle_s
7770 objvertex_t vertex[3];
7772 // these fields are used only in conversion to surfaces
7775 int surfacevertexindex[3];
7776 float edgeplane[3][4];
7782 struct objnode_s *children[2];
7783 struct objnode_s *parent;
7784 objtriangle_t *triangles;
7793 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)
7799 float bestnormal[3];
7804 int numfronttriangles;
7805 int numbacktriangles;
7810 float outfrontpoints[5][3];
7811 float outbackpoints[5][3];
7812 int neededfrontpoints;
7813 int neededbackpoints;
7817 node = (objnode_t *)Mem_ExpandableArray_AllocRecord(array);
7818 node->parent = parent;
7821 VectorCopy(triangles[0].vertex[0].v, mins);
7822 VectorCopy(triangles[0].vertex[0].v, maxs);
7824 else if (parent && parent->children[0] == node)
7826 VectorCopy(parent->mins, mins);
7827 Vectorcopy(parent->maxs, maxs);
7829 else if (parent && parent->children[1] == node)
7831 VectorCopy(parent->mins, mins);
7832 Vectorcopy(parent->maxs, maxs);
7839 for (i = 0;i < numtriangles;i++)
7841 for (j = 0;j < 3;j++)
7843 mins[0] = min(mins[0], triangles[i].vertex[j].v[0]);
7844 mins[1] = min(mins[1], triangles[i].vertex[j].v[1]);
7845 mins[2] = min(mins[2], triangles[i].vertex[j].v[2]);
7846 maxs[0] = max(maxs[0], triangles[i].vertex[j].v[0]);
7847 maxs[1] = max(maxs[1], triangles[i].vertex[j].v[1]);
7848 maxs[2] = max(maxs[2], triangles[i].vertex[j].v[2]);
7851 VectorCopy(mins, node->mins);
7852 VectorCopy(maxs, node->maxs);
7853 if (numtriangles <= mod_obj_leaftriangles.integer)
7856 loadmodel->brush.num_leafs++;
7857 node->triangles = triangles;
7858 node->numtriangles = numtriangles;
7863 loadmodel->brush.num_nodes++;
7864 // pick a splitting plane from the various choices available to us...
7865 // early splits simply halve the interval
7867 VectorClear(bestnormal);
7869 if (numtriangles <= mod_obj_splitterlimit.integer)
7870 limit = numtriangles;
7873 for (i = -3;i < limit;i++)
7877 // first we try 3 axial splits (kdtree-like)
7879 VectorClear(normal);
7881 dist = (mins[j] + maxs[j]) * 0.5f;
7885 // then we try each triangle plane
7886 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7887 VectorNormalize(normal);
7888 dist = DotProduct(normal, triangles[i].vertex[0].v);
7889 // use positive axial values whenever possible
7890 if (normal[0] == -1)
7892 if (normal[1] == -1)
7894 if (normal[2] == -1)
7896 // skip planes that match the current best
7897 if (VectorCompare(normal, bestnormal) && dist == bestdist)
7904 for (j = 0;j < numtriangles;j++)
7906 dists[0] = DotProduct(normal, triangles[j].vertex[0].v) - dist;
7907 dists[1] = DotProduct(normal, triangles[j].vertex[1].v) - dist;
7908 dists[2] = DotProduct(normal, triangles[j].vertex[2].v) - dist;
7909 if (dists[0] < -DIST_EPSILON || dists[1] < -DIST_EPSILON || dists[2] < -DIST_EPSILON)
7911 if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7916 else if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7921 // score is supposed to:
7922 // prefer axial splits
7923 // prefer evenly dividing the input triangles
7924 // prefer triangles on the plane
7925 // avoid triangles crossing the plane
7926 score = count_on*count_on - count_both*count_both + min(count_front, count_back)*(count_front+count_back);
7927 if (normal[0] == 1 || normal[1] == 1 || normal[2] == 1)
7929 if (i == -3 || bestscore < score)
7931 VectorCopy(normal, bestnormal);
7937 // now we have chosen an optimal split plane...
7939 // divide triangles by the splitting plane
7940 numfronttriangles = 0;
7941 numbacktriangles = 0;
7942 for (i = 0;i < numtriangles;i++)
7944 neededfrontpoints = 0;
7945 neededbackpoints = 0;
7947 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);
7948 if (countonpoints > 1)
7950 // triangle lies on plane, assign it to one child only
7951 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7952 if (DotProduct(bestnormal, normal) >= 0)
7954 // assign to front side child
7955 obj_fronttriangles[numfronttriangles++] = triangles[i];
7959 // assign to back side child
7960 obj_backtriangles[numbacktriangles++] = triangles[i];
7965 // convert clipped polygons to triangles
7966 for (j = 0;j < neededfrontpoints-2;j++)
7968 obj_fronttriangles[numfronttriangles] = triangles[i];
7969 VectorCopy(outfrontpoints[0], obj_fronttriangles[numfronttriangles].vertex[0].v);
7970 VectorCopy(outfrontpoints[j+1], obj_fronttriangles[numfronttriangles].vertex[1].v);
7971 VectorCopy(outfrontpoints[j+2], obj_fronttriangles[numfronttriangles].vertex[2].v);
7972 numfronttriangles++;
7974 for (j = 0;j < neededbackpoints-2;j++)
7976 obj_backtriangles[numbacktriangles] = triangles[i];
7977 VectorCopy(outbackpoints[0], obj_backtriangles[numbacktriangles].vertex[0].v);
7978 VectorCopy(outbackpoints[j+1], obj_backtriangles[numbacktriangles].vertex[1].v);
7979 VectorCopy(outbackpoints[j+2], obj_backtriangles[numbacktriangles].vertex[2].v);
7985 // now copy the triangles out of the big buffer
7986 if (numfronttriangles)
7988 fronttriangles = Mem_Alloc(loadmodel->mempool, fronttriangles * sizeof(*fronttriangles));
7989 memcpy(fronttriangles, obj_fronttriangles, numfronttriangles * sizeof(*fronttriangles));
7992 fronttriangles = NULL;
7993 if (numbacktriangles)
7995 backtriangles = Mem_Alloc(loadmodel->mempool, backtriangles * sizeof(*backtriangles));
7996 memcpy(backtriangles, obj_backtriangles, numbacktriangles * sizeof(*backtriangles));
7999 backtriangles = NULL;
8001 // free the original triangles we were given
8003 Mem_Free(triangles);
8007 // now create the children...
8008 node->children[0] = Mod_OBJ_BSPNodeForTriangles(node, fronttriangles, numfronttriangles, frontmins, frontmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8009 node->children[1] = Mod_OBJ_BSPNodeForTriangles(node, backtriangles, numbacktriangles, backmins, backmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8013 void Mod_OBJ_SnapVertex(float *v)
8016 float a = mod_obj_vertexprecision.value;
8018 v[0] -= floor(v[0] * a + 0.5f) * b;
8019 v[1] -= floor(v[1] * a + 0.5f) * b;
8020 v[2] -= floor(v[2] * a + 0.5f) * b;
8023 void Mod_OBJ_ConvertBSPNode(objnode_t *objnode, mnode_t *mnodeparent)
8025 if (objnode->children[0])
8027 // convert to mnode_t
8028 mnode_t *mnode = loadmodel->brush.data_nodes + loadmodel->brush.num_nodes++;
8029 mnode->parent = mnodeparent;
8030 mnode->plane = loadmodel->brush.data_planes + loadmodel->brush.num_planes++;
8031 VectorCopy(objnode->normal, mnode->plane->normal);
8032 mnode->plane->dist = objnode->dist;
8033 PlaneClassify(mnode->plane);
8034 VectorCopy(objnode->mins, mnode->mins);
8035 VectorCopy(objnode->maxs, mnode->maxs);
8036 // push combinedsupercontents up to the parent
8038 mnodeparent->combinedsupercontents |= mnode->combinedsupercontents;
8039 mnode->children[0] = Mod_OBJ_ConvertBSPNode(objnode->children[0], mnode);
8040 mnode->children[1] = Mod_OBJ_ConvertBSPNode(objnode->children[1], mnode);
8044 // convert to mleaf_t
8045 mleaf_t *mleaf = loadmodel->brush.data_leafs + loadmodel->brush.num_leafs++;
8046 mleaf->parent = mnodeparent;
8047 VectorCopy(objnode->mins, mleaf->mins);
8048 VectorCopy(objnode->maxs, mleaf->maxs);
8049 mleaf->clusterindex = loadmodel->brush.num_leafs - 1;
8050 if (objnode->numtriangles)
8052 objtriangle_t *triangles = objnode->triangles;
8053 int numtriangles = objnode->numtriangles;
8057 objvertex_t vertex[3];
8059 maxsurfaces = numtriangles;
8061 // calculate some more data on each triangle for surface gathering
8062 for (i = 0;i < numtriangles;i++)
8064 triangle = triangles + i;
8065 texture = loadmodel->data_textures + triangle->textureindex;
8066 Mod_OBJ_SnapVertex(triangle->vertex[0].v);
8067 Mod_OBJ_SnapVertex(triangle->vertex[1].v);
8068 Mod_OBJ_SnapVertex(triangle->vertex[2].v);
8069 TriangleNormal(triangle->vertex[0].v, triangle->vertex[1].v, triangle->vertex[2].v, normal);
8071 if (fabs(normal[axis]) < fabs(normal[1]))
8073 if (fabs(normal[axis]) < fabs(normal[2]))
8075 VectorClear(normal);
8077 triangle->axis = axis;
8078 VectorSubtract(triangle->vertex[1].v, triangle->vertex[0].v, edge[0]);
8079 VectorSubtract(triangle->vertex[2].v, triangle->vertex[1].v, edge[1]);
8080 VectorSubtract(triangle->vertex[0].v, triangle->vertex[2].v, edge[2]);
8081 CrossProduct(edge[0], normal, triangle->edgeplane[0]);
8082 CrossProduct(edge[1], normal, triangle->edgeplane[1]);
8083 CrossProduct(edge[2], normal, triangle->edgeplane[2]);
8084 VectorNormalize(triangle->edgeplane[0]);
8085 VectorNormalize(triangle->edgeplane[1]);
8086 VectorNormalize(triangle->edgeplane[2]);
8087 triangle->edgeplane[0][3] = DotProduct(triangle->edgeplane[0], triangle->vertex[0].v);
8088 triangle->edgeplane[1][3] = DotProduct(triangle->edgeplane[1], triangle->vertex[1].v);
8089 triangle->edgeplane[2][3] = DotProduct(triangle->edgeplane[2], triangle->vertex[2].v);
8090 triangle->surfaceindex = 0;
8091 // add to the combined supercontents while we're here...
8092 mleaf->combinedsupercontents |= texture->supercontents;
8095 for (i = 0;i < numtriangles;i++)
8097 // skip already-assigned triangles
8098 if (triangles[i].surfaceindex)
8100 texture = loadmodel->data_textures + triangles[i].textureindex;
8101 // assign a new surface to this triangle
8102 triangles[i].surfaceindex = surfaceindex++;
8103 axis = triangles[i].axis;
8105 // find the triangle's neighbors, this can take multiple passes
8110 for (j = i+1;j < numtriangles;j++)
8112 if (triangles[j].surfaceindex || triangles[j].axis != axis || triangles[j].texture != texture)
8114 triangle = triangles + j;
8115 for (k = i;k < j;k++)
8117 if (triangles[k].surfaceindex != surfaceindex)
8119 if (VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[0].v)
8120 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[1].v)
8121 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[2].v)
8122 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[0].v)
8123 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[1].v)
8124 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[2].v)
8125 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[0].v)
8126 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[1].v)
8127 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[2].v))
8129 // shares a vertex position
8133 for (k = 0;k < numvertices;k++)
8134 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))
8136 if (k == numvertices)
8137 break; // not a neighbor
8138 // this triangle is a neighbor and has the same axis and texture
8139 // check now if it overlaps in lightmap projection space
8140 triangles[j].surfaceindex;
8144 //triangles[i].surfaceindex = surfaceindex++;
8145 for (surfaceindex = 0;surfaceindex < numsurfaces;surfaceindex++)
8147 if (surfaces[surfaceindex].texture != texture)
8149 // check if any triangles already in this surface overlap in lightmap projection space
8156 // let the collision code simply use the surfaces
8157 mleaf->containscollisionsurfaces = mleaf->combinedsupercontents != 0;
8158 mleaf->numleafsurfaces = ?;
8159 mleaf->firstleafsurface = ?;
8161 // push combinedsupercontents up to the parent
8163 mnodeparent->combinedsupercontents |= mleaf->combinedsupercontents;
8168 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
8171 const char *textbase = (char *)buffer, *text = textbase;
8175 char materialname[MAX_QPATH];
8176 int j, index1, index2, index3, first, prev, index;
8179 int numtriangles = 0;
8180 int maxtriangles = 131072;
8181 objtriangle_t *triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8183 int maxtextures = 256, numtextures = 0, textureindex = 0;
8184 int maxv = 1024, numv = 0;
8185 int maxvt = 1024, numvt = 0;
8186 int maxvn = 1024, numvn = 0;
8187 char **texturenames;
8188 float *v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
8189 float *vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
8190 float *vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
8191 objvertex_t vfirst, vprev, vcurrent;
8196 int maxverthash = 65536, numverthash = 0;
8197 int numhashindex = 65536;
8198 struct objverthash_s
8200 struct objverthash_s *next;
8206 *hash, **verthash = Mem_Alloc(tempmempool, numhashindex * sizeof(*verthash)), *verthashdata = Mem_Alloc(tempmempool, maxverthash * sizeof(*verthashdata)), *oldverthashdata;
8209 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8211 loadmodel->modeldatatypestring = "OBJ";
8213 loadmodel->type = mod_obj;
8214 loadmodel->soundfromcenter = true;
8215 loadmodel->TraceBox = Mod_OBJ_TraceBox;
8216 loadmodel->TraceLine = Mod_OBJ_TraceLine;
8217 loadmodel->TracePoint = Mod_OBJ_TracePoint;
8218 loadmodel->PointSuperContents = Mod_OBJ_PointSuperContents;
8219 loadmodel->brush.TraceLineOfSight = Mod_OBJ_TraceLineOfSight;
8220 loadmodel->brush.SuperContentsFromNativeContents = Mod_OBJ_SuperContentsFromNativeContents;
8221 loadmodel->brush.NativeContentsFromSuperContents = Mod_OBJ_NativeContentsFromSuperContents;
8222 loadmodel->brush.GetPVS = Mod_OBJ_GetPVS;
8223 loadmodel->brush.FatPVS = Mod_OBJ_FatPVS;
8224 loadmodel->brush.BoxTouchingPVS = Mod_OBJ_BoxTouchingPVS;
8225 loadmodel->brush.BoxTouchingLeafPVS = Mod_OBJ_BoxTouchingLeafPVS;
8226 loadmodel->brush.BoxTouchingVisibleLeafs = Mod_OBJ_BoxTouchingVisibleLeafs;
8227 loadmodel->brush.FindBoxClusters = Mod_OBJ_FindBoxClusters;
8228 loadmodel->brush.LightPoint = Mod_OBJ_LightPoint;
8229 loadmodel->brush.FindNonSolidLocation = Mod_OBJ_FindNonSolidLocation;
8230 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8231 loadmodel->brush.RoundUpToHullSize = NULL;
8232 loadmodel->brush.PointInLeaf = Mod_OBJ_PointInLeaf;
8233 loadmodel->Draw = R_Q1BSP_Draw;
8234 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
8235 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
8236 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
8237 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
8238 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
8239 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
8240 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
8241 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
8242 loadmodel->DrawLight = R_Q1BSP_DrawLight;
8247 // parse the OBJ text now
8254 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8255 line[linelen] = text[linelen];
8257 for (argc = 0;argc < (int)(sizeof(argv)/sizeof(argv[0]));argc++)
8261 while (*s == ' ' || *s == '\t')
8271 while (*s == ' ' || *s == '\t')
8276 if (argv[0][0] == '#')
8278 if (!strcmp(argv[0], "v"))
8284 v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
8287 memcpy(v, oldv, numv * sizeof(float[3]));
8291 v[numv*3+0] = atof(argv[1]);
8292 v[numv*3+1] = atof(argv[2]);
8293 v[numv*3+2] = atof(argv[3]);
8296 else if (!strcmp(argv[0], "vt"))
8302 vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
8305 memcpy(vt, oldvt, numvt * sizeof(float[2]));
8309 vt[numvt*2+0] = atof(argv[1]);
8310 vt[numvt*2+1] = atof(argv[2]);
8313 else if (!strcmp(argv[0], "vn"))
8319 vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
8322 memcpy(vn, oldvn, numvn * sizeof(float[3]));
8326 vn[numvn*3+0] = atof(argv[1]);
8327 vn[numvn*3+1] = atof(argv[2]);
8328 vn[numvn*3+2] = atof(argv[3]);
8331 else if (!strcmp(argv[0], "f"))
8333 for (j = 1;j < argc;j++)
8335 index1 = atoi(argv[j]);
8336 while(argv[j][0] && argv[j][0] != '/')
8340 index2 = atoi(argv[j]);
8341 while(argv[j][0] && argv[j][0] != '/')
8345 index3 = atoi(argv[j]);
8346 // negative refers to a recent vertex
8347 // zero means not specified
8348 // positive means an absolute vertex index
8350 index1 = numv - index1;
8352 index2 = numvt - index2;
8354 index3 = numvn - index3;
8355 VectorCopy(v + 3*index1, vcurrent.v);
8356 Vector2Copy(vt + 2*index2, vcurrent.vt);
8357 VectorCopy(vn + 3*index3, vcurrent.vn);
8358 if (numtriangles == 0)
8360 VectorCopy(vcurrent.v, mins);
8361 VectorCopy(vcurrent.v, maxs);
8365 mins[0] = min(mins[0], vcurrent.v[0]);
8366 mins[1] = min(mins[1], vcurrent.v[1]);
8367 mins[2] = min(mins[2], vcurrent.v[2]);
8368 maxs[0] = max(maxs[0], vcurrent.v[0]);
8369 maxs[1] = max(maxs[1], vcurrent.v[1]);
8370 maxs[2] = max(maxs[2], vcurrent.v[2]);
8376 if (maxtriangles <= numtriangles)
8378 objtriangle_t *oldtriangles = triangles;
8380 triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8383 memcpy(triangles, oldtriangles, maxtriangles * sizeof(*triangles));
8384 Mem_Free(oldtriangles);
8387 triangles[numtriangles].textureindex = textureindex;
8388 triangles[numtriangles].vertex[0] = vfirst;
8389 triangles[numtriangles].vertex[1] = vprev;
8390 triangles[numtriangles].vertex[2] = vcurrent;
8397 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8399 else if (!!strcmp(argv[0], "usemtl"))
8401 for (i = 0;i < numtextures;i++)
8402 if (!strcmp(texturenames[numtextures], argv[1]))
8404 if (i < numtextures)
8405 texture = textures + i;
8408 if (maxtextures <= numtextures)
8410 texture_t *oldtextures = textures;
8412 textures = Mem_Alloc(tempmempool, maxtextures * sizeof(*textures));
8415 memcpy(textures, oldtextures, numtextures * sizeof(*textures));
8416 Mem_Free(oldtextures);
8419 textureindex = numtextures++;
8420 texturenames[textureindex] = Mem_Alloc(tempmempool, strlen(argv[1]) + 1);
8421 memcpy(texturenames[textureindex], argv[1], strlen(argv[1]) + 1);
8431 // now that we have the OBJ data loaded as-is, we can convert it
8433 // load the textures
8434 loadmodel->num_textures = numtextures;
8435 loadmodel->data_textures = Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
8436 for (i = 0;i < numtextures;i++)
8437 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, texturenames[i], true, true, TEXF_MIPMAP | TEXF_ALPHA | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
8439 // free the texturenames array since we are now done with it
8440 for (i = 0;i < numtextures;i++)
8442 Mem_Free(texturenames[i]);
8443 texturenames[i] = NULL;
8445 Mem_Free(texturenames);
8446 texturenames = NULL;
8448 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8449 VectorCopy(mins, loadmodel->normalmins);
8450 VectorCopy(maxs, loadmodel->normalmaxs);
8451 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8452 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8453 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8454 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8455 modelradius = modelyawradius + modelradius * modelradius;
8456 modelyawradius = sqrt(modelyawradius);
8457 modelradius = sqrt(modelradius);
8458 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8459 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8460 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8461 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8462 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8463 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8464 loadmodel->radius = modelradius;
8465 loadmodel->radius2 = modelradius * modelradius;
8467 // make sure the temp triangle buffer is big enough for BSP building
8468 maxclippedtriangles = numtriangles*4;
8469 if (numtriangles > 0)
8471 clippedfronttriangles = Mem_Alloc(loadmodel->mempool, maxclippedtriangles * 2 * sizeof(objtriangle_t));
8472 clippedbacktriangles = clippedfronttriangles + maxclippedtriangles;
8475 // 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
8476 loadmodel->brush.num_leafs = 0;
8477 loadmodel->brush.num_nodes = 0;
8478 Mem_ExpandableArray_NewArray(&nodesarray, loadmodel->mempool, sizeof(objnode_t), 1024);
8479 rootnode = Mod_OBJ_BSPNodeForTriangles(triangles, numtriangles, mins, maxs, &nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8481 // convert the BSP tree to mnode_t and mleaf_t structures and convert the triangles to msurface_t...
8482 loadmodel->brush.data_leafs = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8483 loadmodel->brush.data_nodes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mnode_t));
8484 loadmodel->brush.data_planes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mplane_t));
8485 loadmodel->brush.num_leafs = 0;
8486 loadmodel->brush.num_nodes = 0;
8487 loadmodel->brush.num_planes = 0;
8488 Mod_OBJ_ConvertAndFreeBSPNode(rootnode);
8490 if (clippedfronttriangles)
8491 Mem_Free(clippedfronttriangles);
8492 maxclippedtriangles = 0;
8493 clippedfronttriangles = NULL;
8494 clippedbacktriangles = NULL;
8496 --- NOTHING DONE PAST THIS POINT ---
8498 loadmodel->numskins = LittleLong(pinmodel->num_skins);
8499 numxyz = LittleLong(pinmodel->num_xyz);
8500 numst = LittleLong(pinmodel->num_st);
8501 loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->num_tris);
8502 loadmodel->numframes = LittleLong(pinmodel->num_frames);
8503 loadmodel->surfmesh.num_morphframes = loadmodel->numframes;
8504 loadmodel->num_poses = loadmodel->surfmesh.num_morphframes;
8505 skinwidth = LittleLong(pinmodel->skinwidth);
8506 skinheight = LittleLong(pinmodel->skinheight);
8507 iskinwidth = 1.0f / skinwidth;
8508 iskinheight = 1.0f / skinheight;
8510 loadmodel->num_surfaces = 1;
8511 loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
8512 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]));
8513 loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
8514 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8515 loadmodel->sortedmodelsurfaces[0] = 0;
8516 loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
8517 loadmodel->surfmesh.data_morphmd2framesize6f = (float *)data;data += loadmodel->numframes * sizeof(float[6]);
8518 loadmodel->surfmesh.data_element3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8519 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8521 loadmodel->synctype = ST_RAND;
8524 inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
8525 skinfiles = Mod_LoadSkinFiles();
8528 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8529 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8530 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8531 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
8532 Mod_FreeSkinFiles(skinfiles);
8534 else if (loadmodel->numskins)
8536 // skins found (most likely not a player model)
8537 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8538 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8539 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8540 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
8541 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i * loadmodel->num_surfaces, inskin, true, true, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP | TEXF_COMPRESS);
8545 // no skins (most likely a player model)
8546 loadmodel->numskins = 1;
8547 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8548 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8549 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8550 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
8553 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8554 for (i = 0;i < loadmodel->numskins;i++)
8556 loadmodel->skinscenes[i].firstframe = i;
8557 loadmodel->skinscenes[i].framecount = 1;
8558 loadmodel->skinscenes[i].loop = true;
8559 loadmodel->skinscenes[i].framerate = 10;
8562 // load the triangles and stvert data
8563 inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
8564 intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
8565 md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 65536 * sizeof(hash));
8566 md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->surfmesh.num_triangles * 3 * sizeof(*hash));
8567 // swap the triangle list
8568 loadmodel->surfmesh.num_vertices = 0;
8569 for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
8571 for (j = 0;j < 3;j++)
8573 xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
8574 st = (unsigned short) LittleShort (intri[i].index_st[j]);
8577 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
8582 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
8585 hashindex = (xyz * 256 + st) & 65535;
8586 for (hash = md2verthash[hashindex];hash;hash = hash->next)
8587 if (hash->xyz == xyz && hash->st == st)
8591 hash = md2verthashdata + loadmodel->surfmesh.num_vertices++;
8594 hash->next = md2verthash[hashindex];
8595 md2verthash[hashindex] = hash;
8597 loadmodel->surfmesh.data_element3i[i*3+j] = (hash - md2verthashdata);
8601 vertremap = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(int));
8602 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));
8603 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
8604 loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)data;data += loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t);
8605 for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
8608 hash = md2verthashdata + i;
8609 vertremap[i] = hash->xyz;
8610 sts = LittleShort(inst[hash->st*2+0]);
8611 stt = LittleShort(inst[hash->st*2+1]);
8612 if (sts < 0 || sts >= skinwidth || stt < 0 || stt >= skinheight)
8614 Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, sts, stt, i);
8618 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = sts * iskinwidth;
8619 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = stt * iskinheight;
8622 Mem_Free(md2verthash);
8623 Mem_Free(md2verthashdata);
8625 // generate ushort elements array if possible
8626 if (loadmodel->surfmesh.num_vertices <= 65536)
8627 loadmodel->surfmesh.data_element3s = (unsigned short *)Mem_Alloc(loadmodel->mempool, sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles);
8630 datapointer = (base + LittleLong(pinmodel->ofs_frames));
8631 for (i = 0;i < loadmodel->surfmesh.num_morphframes;i++)
8636 pinframe = (md2frame_t *)datapointer;
8637 datapointer += sizeof(md2frame_t);
8638 // store the frame scale/translate into the appropriate array
8639 for (j = 0;j < 3;j++)
8641 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+j] = LittleFloat(pinframe->scale[j]);
8642 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+3+j] = LittleFloat(pinframe->translate[j]);
8644 // convert the vertices
8645 v = (trivertx_t *)datapointer;
8646 out = loadmodel->surfmesh.data_morphmdlvertex + i * loadmodel->surfmesh.num_vertices;
8647 for (k = 0;k < loadmodel->surfmesh.num_vertices;k++)
8648 out[k] = v[vertremap[k]];
8649 datapointer += numxyz * sizeof(trivertx_t);
8651 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
8652 loadmodel->animscenes[i].firstframe = i;
8653 loadmodel->animscenes[i].framecount = 1;
8654 loadmodel->animscenes[i].framerate = 10;
8655 loadmodel->animscenes[i].loop = true;
8658 Mem_Free(vertremap);
8660 Mod_MakeSortedSurfaces(loadmodel);
8661 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8662 Mod_Alias_CalculateBoundingBox();
8663 Mod_Alias_MorphMesh_CompileFrames();
8665 surface = loadmodel->data_surfaces;
8666 surface->texture = loadmodel->data_textures;
8667 surface->num_firsttriangle = 0;
8668 surface->num_triangles = loadmodel->surfmesh.num_triangles;
8669 surface->num_firstvertex = 0;
8670 surface->num_vertices = loadmodel->surfmesh.num_vertices;
8672 loadmodel->surfmesh.isanimated = false;
8674 if (loadmodel->surfmesh.data_element3s)
8675 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8676 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8679 #endif // !OBJASMODEL
8681 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
8683 // we already have done PVS culling at this point...
8684 // so we don't need to do it again.
8687 vec3_t testorigin, mins, maxs;
8689 testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
8690 testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
8691 testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
8693 if(model->brush.TraceLineOfSight(model, eye, testorigin))
8696 // expand the box a little
8697 mins[0] = (t+1) * minsX[0] - t * maxsX[0];
8698 maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
8699 mins[1] = (t+1) * minsX[1] - t * maxsX[1];
8700 maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
8701 mins[2] = (t+1) * minsX[2] - t * maxsX[2];
8702 maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
8704 for(i = 0; i != numsamples; ++i)
8706 testorigin[0] = lhrandom(mins[0], maxs[0]);
8707 testorigin[1] = lhrandom(mins[1], maxs[1]);
8708 testorigin[2] = lhrandom(mins[2], maxs[2]);
8710 if(model->brush.TraceLineOfSight(model, eye, testorigin))