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_picmipworld = {CVAR_SAVE, "r_picmipworld", "1", "whether gl_picmip shall apply to world textures too"};
32 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
34 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
35 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
38 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
39 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
40 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
42 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)"};
43 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)"};
44 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
45 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
46 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, ..."};
47 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)"};
48 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
49 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)"};
50 cvar_t mod_collision_bih = {0, "mod_collision_bih", "0", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
51 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"};
53 static texture_t mod_q1bsp_texture_solid;
54 static texture_t mod_q1bsp_texture_sky;
55 static texture_t mod_q1bsp_texture_lava;
56 static texture_t mod_q1bsp_texture_slime;
57 static texture_t mod_q1bsp_texture_water;
59 void Mod_BrushInit(void)
61 // Cvar_RegisterVariable(&r_subdivide_size);
62 Cvar_RegisterVariable(&r_novis);
63 Cvar_RegisterVariable(&r_picmipworld);
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_q1bsp_polygoncollisions);
82 Cvar_RegisterVariable(&mod_collision_bih);
83 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
85 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
86 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
87 mod_q1bsp_texture_solid.surfaceflags = 0;
88 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
90 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
91 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
92 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
93 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
95 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
96 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
97 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
98 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
100 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
101 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
102 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
103 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
105 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
106 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
107 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
108 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
111 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
118 // LordHavoc: modified to start at first clip node,
119 // in other words: first node of the (sub)model
120 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
122 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
124 return (mleaf_t *)node;
127 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
131 leaf = Mod_Q1BSP_PointInLeaf(model, p);
134 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
137 memcpy(out, leaf->ambient_sound_level, i);
143 memset(out, 0, outsize);
146 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
149 int nodestackindex = 0;
150 mnode_t *node, *nodestack[1024];
151 if (!model->brush.num_pvsclusters)
153 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
159 // node - recurse down the BSP tree
160 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
164 return -1; // ERROR: NAN bounding box!
165 // box is on one side of plane, take that path
166 node = node->children[sides-1];
170 // box crosses plane, take one path and remember the other
171 if (nodestackindex < 1024)
172 nodestack[nodestackindex++] = node->children[0];
173 node = node->children[1];
179 // leaf - add clusterindex to list
180 if (numclusters < maxclusters)
181 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
185 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
189 if (nodestackindex < 1024)
190 nodestack[nodestackindex++] = node->children[0];
191 node = node->children[1];
196 // leaf - add clusterindex to list
197 if (numclusters < maxclusters)
198 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
203 // try another path we didn't take earlier
204 if (nodestackindex == 0)
206 node = nodestack[--nodestackindex];
208 // return number of clusters found (even if more than the maxclusters)
212 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
214 int nodestackindex = 0;
215 mnode_t *node, *nodestack[1024];
216 if (!model->brush.num_pvsclusters)
218 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
224 // node - recurse down the BSP tree
225 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
229 return -1; // ERROR: NAN bounding box!
230 // box is on one side of plane, take that path
231 node = node->children[sides-1];
235 // box crosses plane, take one path and remember the other
236 if (nodestackindex < 1024)
237 nodestack[nodestackindex++] = node->children[0];
238 node = node->children[1];
244 // leaf - check cluster bit
245 int clusterindex = ((mleaf_t *)node)->clusterindex;
246 if (CHECKPVSBIT(pvs, clusterindex))
248 // it is visible, return immediately with the news
253 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
257 if (nodestackindex < 1024)
258 nodestack[nodestackindex++] = node->children[0];
259 node = node->children[1];
264 // leaf - check cluster bit
265 int clusterindex = ((mleaf_t *)node)->clusterindex;
266 if (CHECKPVSBIT(pvs, clusterindex))
268 // it is visible, return immediately with the news
274 // nothing to see here, try another path we didn't take earlier
275 if (nodestackindex == 0)
277 node = nodestack[--nodestackindex];
283 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
285 int nodestackindex = 0;
286 mnode_t *node, *nodestack[1024];
287 if (!model->brush.num_leafs)
289 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
295 // node - recurse down the BSP tree
296 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
300 return -1; // ERROR: NAN bounding box!
301 // box is on one side of plane, take that path
302 node = node->children[sides-1];
306 // box crosses plane, take one path and remember the other
307 if (nodestackindex < 1024)
308 nodestack[nodestackindex++] = node->children[0];
309 node = node->children[1];
315 // leaf - check cluster bit
316 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
317 if (CHECKPVSBIT(pvs, clusterindex))
319 // it is visible, return immediately with the news
324 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
328 if (nodestackindex < 1024)
329 nodestack[nodestackindex++] = node->children[0];
330 node = node->children[1];
335 // leaf - check cluster bit
336 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
337 if (CHECKPVSBIT(pvs, clusterindex))
339 // it is visible, return immediately with the news
345 // nothing to see here, try another path we didn't take earlier
346 if (nodestackindex == 0)
348 node = nodestack[--nodestackindex];
354 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
356 int nodestackindex = 0;
357 mnode_t *node, *nodestack[1024];
358 if (!model->brush.num_leafs)
360 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
366 // node - recurse down the BSP tree
367 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
371 return -1; // ERROR: NAN bounding box!
372 // box is on one side of plane, take that path
373 node = node->children[sides-1];
377 // box crosses plane, take one path and remember the other
378 if (nodestackindex < 1024)
379 nodestack[nodestackindex++] = node->children[0];
380 node = node->children[1];
386 // leaf - check if it is visible
387 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
389 // it is visible, return immediately with the news
394 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
398 if (nodestackindex < 1024)
399 nodestack[nodestackindex++] = node->children[0];
400 node = node->children[1];
405 // leaf - check if it is visible
406 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
408 // it is visible, return immediately with the news
414 // nothing to see here, try another path we didn't take earlier
415 if (nodestackindex == 0)
417 node = nodestack[--nodestackindex];
423 typedef struct findnonsolidlocationinfo_s
426 vec3_t absmin, absmax;
432 findnonsolidlocationinfo_t;
434 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
437 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
439 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
440 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
441 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
442 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
443 VectorSubtract(vert[1], vert[0], edge[0]);
444 VectorSubtract(vert[2], vert[1], edge[1]);
445 CrossProduct(edge[1], edge[0], facenormal);
446 if (facenormal[0] || facenormal[1] || facenormal[2])
448 VectorNormalize(facenormal);
449 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
450 if (f <= info->bestdist && f >= -info->bestdist)
452 VectorSubtract(vert[0], vert[2], edge[2]);
453 VectorNormalize(edge[0]);
454 VectorNormalize(edge[1]);
455 VectorNormalize(edge[2]);
456 CrossProduct(facenormal, edge[0], edgenormal[0]);
457 CrossProduct(facenormal, edge[1], edgenormal[1]);
458 CrossProduct(facenormal, edge[2], edgenormal[2]);
460 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
461 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
462 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
464 // we got lucky, the center is within the face
465 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
469 if (info->bestdist > dist)
471 info->bestdist = dist;
472 VectorScale(facenormal, (info->radius - -dist), info->nudge);
477 if (info->bestdist > dist)
479 info->bestdist = dist;
480 VectorScale(facenormal, (info->radius - dist), info->nudge);
486 // check which edge or vertex the center is nearest
487 for (i = 0;i < 3;i++)
489 f = DotProduct(info->center, edge[i]);
490 if (f >= DotProduct(vert[0], edge[i])
491 && f <= DotProduct(vert[1], edge[i]))
494 VectorMA(info->center, -f, edge[i], point);
495 dist = sqrt(DotProduct(point, point));
496 if (info->bestdist > dist)
498 info->bestdist = dist;
499 VectorScale(point, (info->radius / dist), info->nudge);
501 // skip both vertex checks
502 // (both are further away than this edge)
507 // not on edge, check first vertex of edge
508 VectorSubtract(info->center, vert[i], point);
509 dist = sqrt(DotProduct(point, point));
510 if (info->bestdist > dist)
512 info->bestdist = dist;
513 VectorScale(point, (info->radius / dist), info->nudge);
522 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
524 int surfacenum, k, *mark;
526 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
528 surface = info->model->data_surfaces + *mark;
529 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
531 if(surface->deprecatedq3num_bboxstride > 0)
534 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
535 for(i = 0; i < cnt; ++i)
537 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
539 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
541 tri = i * surface->deprecatedq3num_bboxstride + k;
542 if(tri >= surface->num_triangles)
544 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
551 for (k = 0;k < surface->num_triangles;k++)
553 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
560 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
564 float f = PlaneDiff(info->center, node->plane);
565 if (f >= -info->bestdist)
566 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
567 if (f <= info->bestdist)
568 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
572 if (((mleaf_t *)node)->numleafsurfaces)
573 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
577 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
580 findnonsolidlocationinfo_t info;
586 VectorCopy(in, info.center);
587 info.radius = radius;
592 VectorClear(info.nudge);
593 info.bestdist = radius;
594 VectorCopy(info.center, info.absmin);
595 VectorCopy(info.center, info.absmax);
596 info.absmin[0] -= info.radius + 1;
597 info.absmin[1] -= info.radius + 1;
598 info.absmin[2] -= info.radius + 1;
599 info.absmax[0] += info.radius + 1;
600 info.absmax[1] += info.radius + 1;
601 info.absmax[2] += info.radius + 1;
602 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
603 VectorAdd(info.center, info.nudge, info.center);
605 while (info.bestdist < radius && ++i < 10);
606 VectorCopy(info.center, out);
609 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
611 switch(nativecontents)
616 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
618 return SUPERCONTENTS_WATER;
620 return SUPERCONTENTS_SLIME;
622 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
624 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
629 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
631 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
632 return CONTENTS_SOLID;
633 if (supercontents & SUPERCONTENTS_SKY)
635 if (supercontents & SUPERCONTENTS_LAVA)
636 return CONTENTS_LAVA;
637 if (supercontents & SUPERCONTENTS_SLIME)
638 return CONTENTS_SLIME;
639 if (supercontents & SUPERCONTENTS_WATER)
640 return CONTENTS_WATER;
641 return CONTENTS_EMPTY;
644 typedef struct RecursiveHullCheckTraceInfo_s
646 // the hull we're tracing through
649 // the trace structure to fill in
652 // start, end, and end - start (in model space)
657 RecursiveHullCheckTraceInfo_t;
659 // 1/32 epsilon to keep floating point happy
660 #define DIST_EPSILON (0.03125)
662 #define HULLCHECKSTATE_EMPTY 0
663 #define HULLCHECKSTATE_SOLID 1
664 #define HULLCHECKSTATE_DONE 2
666 extern cvar_t collision_prefernudgedfraction;
667 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
669 // status variables, these don't need to be saved on the stack when
670 // recursing... but are because this should be thread-safe
671 // (note: tracing against a bbox is not thread-safe, yet)
676 // variables that need to be stored on the stack when recursing
681 // LordHavoc: a goto! everyone flee in terror... :)
686 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
687 if (!t->trace->startfound)
689 t->trace->startfound = true;
690 t->trace->startsupercontents |= num;
692 if (num & SUPERCONTENTS_LIQUIDSMASK)
693 t->trace->inwater = true;
695 t->trace->inopen = true;
696 if (num & SUPERCONTENTS_SOLID)
697 t->trace->hittexture = &mod_q1bsp_texture_solid;
698 else if (num & SUPERCONTENTS_SKY)
699 t->trace->hittexture = &mod_q1bsp_texture_sky;
700 else if (num & SUPERCONTENTS_LAVA)
701 t->trace->hittexture = &mod_q1bsp_texture_lava;
702 else if (num & SUPERCONTENTS_SLIME)
703 t->trace->hittexture = &mod_q1bsp_texture_slime;
705 t->trace->hittexture = &mod_q1bsp_texture_water;
706 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
707 t->trace->hitsupercontents = num;
708 if (num & t->trace->hitsupercontentsmask)
710 // if the first leaf is solid, set startsolid
711 if (t->trace->allsolid)
712 t->trace->startsolid = true;
713 #if COLLISIONPARANOID >= 3
716 return HULLCHECKSTATE_SOLID;
720 t->trace->allsolid = false;
721 #if COLLISIONPARANOID >= 3
724 return HULLCHECKSTATE_EMPTY;
728 // find the point distances
729 node = t->hull->clipnodes + num;
731 plane = t->hull->planes + node->planenum;
734 t1 = p1[plane->type] - plane->dist;
735 t2 = p2[plane->type] - plane->dist;
739 t1 = DotProduct (plane->normal, p1) - plane->dist;
740 t2 = DotProduct (plane->normal, p2) - plane->dist;
747 #if COLLISIONPARANOID >= 3
750 num = node->children[1];
759 #if COLLISIONPARANOID >= 3
762 num = node->children[0];
768 // the line intersects, find intersection point
769 // LordHavoc: this uses the original trace for maximum accuracy
770 #if COLLISIONPARANOID >= 3
775 t1 = t->start[plane->type] - plane->dist;
776 t2 = t->end[plane->type] - plane->dist;
780 t1 = DotProduct (plane->normal, t->start) - plane->dist;
781 t2 = DotProduct (plane->normal, t->end) - plane->dist;
784 midf = t1 / (t1 - t2);
785 midf = bound(p1f, midf, p2f);
786 VectorMA(t->start, midf, t->dist, mid);
788 // recurse both sides, front side first
789 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
790 // if this side is not empty, return what it is (solid or done)
791 if (ret != HULLCHECKSTATE_EMPTY)
794 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
795 // if other side is not solid, return what it is (empty or done)
796 if (ret != HULLCHECKSTATE_SOLID)
799 // front is air and back is solid, this is the impact point...
802 t->trace->plane.dist = -plane->dist;
803 VectorNegate (plane->normal, t->trace->plane.normal);
807 t->trace->plane.dist = plane->dist;
808 VectorCopy (plane->normal, t->trace->plane.normal);
811 // calculate the true fraction
812 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
813 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
814 midf = t1 / (t1 - t2);
815 t->trace->realfraction = bound(0, midf, 1);
817 // calculate the return fraction which is nudged off the surface a bit
818 midf = (t1 - DIST_EPSILON) / (t1 - t2);
819 t->trace->fraction = bound(0, midf, 1);
821 if (collision_prefernudgedfraction.integer)
822 t->trace->realfraction = t->trace->fraction;
824 #if COLLISIONPARANOID >= 3
827 return HULLCHECKSTATE_DONE;
830 //#if COLLISIONPARANOID < 2
831 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
834 mclipnode_t *nodes = t->hull->clipnodes;
835 mplane_t *planes = t->hull->planes;
837 VectorCopy(t->start, point);
840 plane = planes + nodes[num].planenum;
841 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
843 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
844 t->trace->startsupercontents |= num;
845 if (num & SUPERCONTENTS_LIQUIDSMASK)
846 t->trace->inwater = true;
848 t->trace->inopen = true;
849 if (num & t->trace->hitsupercontentsmask)
851 t->trace->allsolid = t->trace->startsolid = true;
852 return HULLCHECKSTATE_SOLID;
856 t->trace->allsolid = t->trace->startsolid = false;
857 return HULLCHECKSTATE_EMPTY;
862 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)
864 RecursiveHullCheckTraceInfo_t rhc;
866 memset(&rhc, 0, sizeof(rhc));
867 memset(trace, 0, sizeof(trace_t));
869 rhc.trace->fraction = 1;
870 rhc.trace->realfraction = 1;
871 rhc.trace->allsolid = true;
872 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
873 VectorCopy(start, rhc.start);
874 VectorCopy(start, rhc.end);
875 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
878 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)
880 RecursiveHullCheckTraceInfo_t rhc;
882 if (VectorCompare(start, end))
884 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
888 memset(&rhc, 0, sizeof(rhc));
889 memset(trace, 0, sizeof(trace_t));
891 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
892 rhc.trace->fraction = 1;
893 rhc.trace->realfraction = 1;
894 rhc.trace->allsolid = true;
895 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
896 VectorCopy(start, rhc.start);
897 VectorCopy(end, rhc.end);
898 VectorSubtract(rhc.end, rhc.start, rhc.dist);
899 #if COLLISIONPARANOID >= 2
900 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]);
901 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
906 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
907 memset(&testtrace, 0, sizeof(trace_t));
908 rhc.trace = &testtrace;
909 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
910 rhc.trace->fraction = 1;
911 rhc.trace->realfraction = 1;
912 rhc.trace->allsolid = true;
913 VectorCopy(test, rhc.start);
914 VectorCopy(test, rhc.end);
915 VectorClear(rhc.dist);
916 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
917 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
918 if (!trace->startsolid && testtrace.startsolid)
919 Con_Printf(" - ended in solid!\n");
923 if (VectorLength2(rhc.dist))
924 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
926 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
930 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)
932 // this function currently only supports same size start and end
934 RecursiveHullCheckTraceInfo_t rhc;
936 if (VectorCompare(boxmins, boxmaxs))
938 if (VectorCompare(start, end))
939 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
941 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
945 memset(&rhc, 0, sizeof(rhc));
946 memset(trace, 0, sizeof(trace_t));
948 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
949 rhc.trace->fraction = 1;
950 rhc.trace->realfraction = 1;
951 rhc.trace->allsolid = true;
952 VectorSubtract(boxmaxs, boxmins, boxsize);
954 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
955 else if (model->brush.ishlbsp)
957 // LordHavoc: this has to have a minor tolerance (the .1) because of
958 // minor float precision errors from the box being transformed around
959 if (boxsize[0] < 32.1)
961 if (boxsize[2] < 54) // pick the nearest of 36 or 72
962 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
964 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
967 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
971 // LordHavoc: this has to have a minor tolerance (the .1) because of
972 // minor float precision errors from the box being transformed around
973 if (boxsize[0] < 32.1)
974 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
976 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
978 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
979 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
980 VectorSubtract(rhc.end, rhc.start, rhc.dist);
981 #if COLLISIONPARANOID >= 2
982 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]);
983 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
988 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
989 memset(&testtrace, 0, sizeof(trace_t));
990 rhc.trace = &testtrace;
991 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
992 rhc.trace->fraction = 1;
993 rhc.trace->realfraction = 1;
994 rhc.trace->allsolid = true;
995 VectorCopy(test, rhc.start);
996 VectorCopy(test, rhc.end);
997 VectorClear(rhc.dist);
998 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
999 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1000 if (!trace->startsolid && testtrace.startsolid)
1001 Con_Printf(" - ended in solid!\n");
1005 if (VectorLength2(rhc.dist))
1006 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1008 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1012 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1014 int num = model->brushq1.hulls[0].firstclipnode;
1016 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1017 mplane_t *planes = model->brushq1.hulls[0].planes;
1020 plane = planes + nodes[num].planenum;
1021 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1023 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1026 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)
1030 colplanef_t cbox_planes[6];
1032 cbox.hasaabbplanes = true;
1033 cbox.supercontents = boxsupercontents;
1036 cbox.numtriangles = 0;
1037 cbox.planes = cbox_planes;
1039 cbox.elements = NULL;
1047 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];
1048 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];
1049 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];
1050 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];
1051 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];
1052 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];
1053 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1054 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1055 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1056 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1057 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1058 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1059 memset(trace, 0, sizeof(trace_t));
1060 trace->hitsupercontentsmask = hitsupercontentsmask;
1061 trace->fraction = 1;
1062 trace->realfraction = 1;
1063 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1065 RecursiveHullCheckTraceInfo_t rhc;
1066 static hull_t box_hull;
1067 static mclipnode_t box_clipnodes[6];
1068 static mplane_t box_planes[6];
1069 // fill in a default trace
1070 memset(&rhc, 0, sizeof(rhc));
1071 memset(trace, 0, sizeof(trace_t));
1072 //To keep everything totally uniform, bounding boxes are turned into small
1073 //BSP trees instead of being compared directly.
1074 // create a temp hull from bounding box sizes
1075 box_planes[0].dist = cmaxs[0] - mins[0];
1076 box_planes[1].dist = cmins[0] - maxs[0];
1077 box_planes[2].dist = cmaxs[1] - mins[1];
1078 box_planes[3].dist = cmins[1] - maxs[1];
1079 box_planes[4].dist = cmaxs[2] - mins[2];
1080 box_planes[5].dist = cmins[2] - maxs[2];
1081 #if COLLISIONPARANOID >= 3
1082 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]);
1085 if (box_hull.clipnodes == NULL)
1089 //Set up the planes and clipnodes so that the six floats of a bounding box
1090 //can just be stored out and get a proper hull_t structure.
1092 box_hull.clipnodes = box_clipnodes;
1093 box_hull.planes = box_planes;
1094 box_hull.firstclipnode = 0;
1095 box_hull.lastclipnode = 5;
1097 for (i = 0;i < 6;i++)
1099 box_clipnodes[i].planenum = i;
1103 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1105 box_clipnodes[i].children[side^1] = i + 1;
1107 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1109 box_planes[i].type = i>>1;
1110 box_planes[i].normal[i>>1] = 1;
1114 // trace a line through the generated clipping hull
1115 //rhc.boxsupercontents = boxsupercontents;
1116 rhc.hull = &box_hull;
1118 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1119 rhc.trace->fraction = 1;
1120 rhc.trace->realfraction = 1;
1121 rhc.trace->allsolid = true;
1122 VectorCopy(start, rhc.start);
1123 VectorCopy(end, rhc.end);
1124 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1125 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1126 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1127 if (rhc.trace->startsupercontents)
1128 rhc.trace->startsupercontents = boxsupercontents;
1132 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)
1134 memset(trace, 0, sizeof(trace_t));
1135 trace->fraction = 1;
1136 trace->realfraction = 1;
1137 if (BoxesOverlap(start, start, cmins, cmaxs))
1139 trace->startsupercontents |= boxsupercontents;
1140 if (hitsupercontentsmask & boxsupercontents)
1142 trace->startsolid = true;
1143 trace->allsolid = true;
1148 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1151 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1152 return trace.fraction == 1;
1155 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)
1159 float mid, distz = endz - startz;
1163 return false; // didn't hit anything
1165 switch (node->plane->type)
1168 node = node->children[x < node->plane->dist];
1171 node = node->children[y < node->plane->dist];
1174 side = startz < node->plane->dist;
1175 if ((endz < node->plane->dist) == side)
1177 node = node->children[side];
1180 // found an intersection
1181 mid = node->plane->dist;
1184 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1185 front += startz * node->plane->normal[2];
1186 back += endz * node->plane->normal[2];
1187 side = front < node->plane->dist;
1188 if ((back < node->plane->dist) == side)
1190 node = node->children[side];
1193 // found an intersection
1194 mid = startz + distz * (front - node->plane->dist) / (front - back);
1198 // go down front side
1199 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1200 return true; // hit something
1203 // check for impact on this node
1204 if (node->numsurfaces)
1206 int i, dsi, dti, lmwidth, lmheight;
1208 msurface_t *surface;
1209 unsigned char *lightmap;
1210 int maps, line3, size3;
1213 float scale, w, w00, w01, w10, w11;
1215 surface = model->data_surfaces + node->firstsurface;
1216 for (i = 0;i < node->numsurfaces;i++, surface++)
1218 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1219 continue; // no lightmaps
1221 // location we want to sample in the lightmap
1222 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;
1223 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;
1228 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1229 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1232 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1234 // calculate bilinear interpolation factors
1235 // and also multiply by fixedpoint conversion factors
1238 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1239 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1240 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1241 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1243 // values for pointer math
1244 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1245 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1247 // look up the pixel
1248 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1250 // bilinear filter each lightmap style, and sum them
1251 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1253 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1254 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1255 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1256 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1257 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1261 return true; // success
1266 // go down back side
1267 node = node->children[side ^ 1];
1269 distz = endz - startz;
1274 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1276 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1277 VectorSet(diffusenormal, 0, 0, 1);
1279 if (!model->brushq1.lightdata)
1281 VectorSet(ambientcolor, 1, 1, 1);
1282 VectorSet(diffusecolor, 0, 0, 0);
1286 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);
1289 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1292 unsigned char *outstart = out;
1293 while (out < outend)
1297 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));
1307 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));
1310 for (c = *in++;c > 0;c--)
1314 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));
1325 R_Q1BSP_LoadSplitSky
1327 A sky texture is 256*128, with the right side being a masked overlay
1330 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1335 unsigned *solidpixels = Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1336 unsigned *alphapixels = Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1338 // allocate a texture pool if we need it
1339 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1340 loadmodel->texturepool = R_AllocTexturePool();
1342 if (bytesperpixel == 4)
1344 for (y = 0;y < h;y++)
1346 for (x = 0;x < w;x++)
1348 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1349 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1355 // make an average value for the back to avoid
1356 // a fringe on the top level
1365 for (y = 0;y < h;y++)
1367 for (x = 0;x < w;x++)
1369 p = src[x*width+y+w];
1370 r += palette_rgb[p][0];
1371 g += palette_rgb[p][1];
1372 b += palette_rgb[p][2];
1375 bgra.b[2] = r/(w*h);
1376 bgra.b[1] = g/(w*h);
1377 bgra.b[0] = b/(w*h);
1379 for (y = 0;y < h;y++)
1381 for (x = 0;x < w;x++)
1383 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1385 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1390 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h);
1391 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h);
1392 Mem_Free(solidpixels);
1393 Mem_Free(alphapixels);
1396 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1398 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1399 skinframe_t *skinframe;
1401 texture_t *tx, *tx2, *anims[10], *altanims[10];
1403 unsigned char *data, *mtdata;
1405 char mapname[MAX_QPATH], name[MAX_QPATH];
1406 unsigned char zero[4];
1408 memset(zero, 0, sizeof(zero));
1410 loadmodel->data_textures = NULL;
1412 // add two slots for notexture walls and notexture liquids
1415 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1416 m->nummiptex = LittleLong (m->nummiptex);
1417 loadmodel->num_textures = m->nummiptex + 2;
1418 loadmodel->num_texturesperskin = loadmodel->num_textures;
1423 loadmodel->num_textures = 2;
1424 loadmodel->num_texturesperskin = loadmodel->num_textures;
1427 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1429 // fill out all slots with notexture
1430 if (cls.state != ca_dedicated)
1431 skinframe = R_SkinFrame_LoadMissing();
1434 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1436 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1439 if (cls.state != ca_dedicated)
1441 tx->numskinframes = 1;
1442 tx->skinframerate = 1;
1443 tx->skinframes[0] = skinframe;
1444 tx->currentskinframe = tx->skinframes[0];
1446 tx->basematerialflags = MATERIALFLAG_WALL;
1447 if (i == loadmodel->num_textures - 1)
1449 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1450 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1451 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1455 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1456 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1458 tx->currentframe = tx;
1460 // clear water settings
1463 tx->refractfactor = 1;
1464 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1465 tx->reflectfactor = 1;
1466 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1467 tx->r_water_wateralpha = 1;
1468 tx->specularscalemod = 1;
1469 tx->specularpowermod = 1;
1474 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1478 s = loadmodel->name;
1479 if (!strncasecmp(s, "maps/", 5))
1481 FS_StripExtension(s, mapname, sizeof(mapname));
1483 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1485 // LordHavoc: mostly rewritten map texture loader
1486 for (i = 0;i < m->nummiptex;i++)
1488 dofs[i] = LittleLong(dofs[i]);
1489 if (r_nosurftextures.integer)
1493 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1496 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1498 // copy name, but only up to 16 characters
1499 // (the output buffer can hold more than this, but the input buffer is
1501 for (j = 0;j < 16 && dmiptex->name[j];j++)
1502 name[j] = dmiptex->name[j];
1507 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1508 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1511 mtwidth = LittleLong(dmiptex->width);
1512 mtheight = LittleLong(dmiptex->height);
1514 j = LittleLong(dmiptex->offsets[0]);
1518 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1520 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1523 mtdata = (unsigned char *)dmiptex + j;
1526 if ((mtwidth & 15) || (mtheight & 15))
1527 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1529 // LordHavoc: force all names to lowercase
1530 for (j = 0;name[j];j++)
1531 if (name[j] >= 'A' && name[j] <= 'Z')
1532 name[j] += 'a' - 'A';
1534 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1537 tx = loadmodel->data_textures + i;
1538 strlcpy(tx->name, name, sizeof(tx->name));
1539 tx->width = mtwidth;
1540 tx->height = mtheight;
1542 if (tx->name[0] == '*')
1544 if (!strncmp(tx->name, "*lava", 5))
1546 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1547 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1549 else if (!strncmp(tx->name, "*slime", 6))
1551 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1552 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1556 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1557 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1560 else if (!strncmp(tx->name, "sky", 3))
1562 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1563 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1567 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1568 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1571 if (cls.state != ca_dedicated)
1573 // LordHavoc: HL sky textures are entirely different than quake
1574 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1576 data = loadimagepixelsbgra(tx->name, false, false, r_texture_convertsRGB_skin.integer);
1577 if (data && image_width == image_height * 2)
1579 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1582 else if (mtdata != NULL)
1583 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1587 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS, false);
1589 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS, false);
1592 // did not find external texture, load it from the bsp or wad3
1593 if (loadmodel->brush.ishlbsp)
1595 // internal texture overrides wad
1596 unsigned char *pixels, *freepixels;
1597 pixels = freepixels = NULL;
1599 pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1601 pixels = freepixels = W_GetTextureBGRA(tx->name);
1604 tx->width = image_width;
1605 tx->height = image_height;
1606 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0), pixels, image_width, image_height);
1609 Mem_Free(freepixels);
1611 else if (mtdata) // texture included
1612 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0), false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1614 // if skinframe is still NULL the "missing" texture will be used
1616 tx->skinframes[0] = skinframe;
1619 tx->basematerialflags = MATERIALFLAG_WALL;
1620 if (tx->name[0] == '*')
1622 // LordHavoc: some turbulent textures should not be affected by wateralpha
1623 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1625 // replace the texture with transparent black
1626 Vector4Set(zero, 128, 128, 128, 128);
1627 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zero, 1, 1);
1628 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1630 else if (!strncmp(tx->name,"*lava",5)
1631 || !strncmp(tx->name,"*teleport",9)
1632 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1633 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1635 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1636 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1637 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1639 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1641 // replace the texture with black
1642 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zero, 1, 1);
1643 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1645 else if (!strncmp(tx->name, "sky", 3))
1646 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1647 else if (!strcmp(tx->name, "caulk"))
1648 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1649 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1650 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1652 // start out with no animation
1653 tx->currentframe = tx;
1654 tx->currentskinframe = tx->skinframes[0];
1658 // sequence the animations
1659 for (i = 0;i < m->nummiptex;i++)
1661 tx = loadmodel->data_textures + i;
1662 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1664 if (tx->anim_total[0] || tx->anim_total[1])
1665 continue; // already sequenced
1667 // find the number of frames in the animation
1668 memset(anims, 0, sizeof(anims));
1669 memset(altanims, 0, sizeof(altanims));
1671 for (j = i;j < m->nummiptex;j++)
1673 tx2 = loadmodel->data_textures + j;
1674 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1678 if (num >= '0' && num <= '9')
1679 anims[num - '0'] = tx2;
1680 else if (num >= 'a' && num <= 'j')
1681 altanims[num - 'a'] = tx2;
1683 Con_Printf("Bad animating texture %s\n", tx->name);
1687 for (j = 0;j < 10;j++)
1694 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1697 for (j = 0;j < max;j++)
1701 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1705 for (j = 0;j < altmax;j++)
1709 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1718 // if there is no alternate animation, duplicate the primary
1719 // animation into the alternate
1721 for (k = 0;k < 10;k++)
1722 altanims[k] = anims[k];
1725 // link together the primary animation
1726 for (j = 0;j < max;j++)
1729 tx2->animated = true;
1730 tx2->anim_total[0] = max;
1731 tx2->anim_total[1] = altmax;
1732 for (k = 0;k < 10;k++)
1734 tx2->anim_frames[0][k] = anims[k];
1735 tx2->anim_frames[1][k] = altanims[k];
1739 // if there really is an alternate anim...
1740 if (anims[0] != altanims[0])
1742 // link together the alternate animation
1743 for (j = 0;j < altmax;j++)
1746 tx2->animated = true;
1747 // the primary/alternate are reversed here
1748 tx2->anim_total[0] = altmax;
1749 tx2->anim_total[1] = max;
1750 for (k = 0;k < 10;k++)
1752 tx2->anim_frames[0][k] = altanims[k];
1753 tx2->anim_frames[1][k] = anims[k];
1760 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1763 unsigned char *in, *out, *data, d;
1764 char litfilename[MAX_QPATH];
1765 char dlitfilename[MAX_QPATH];
1766 fs_offset_t filesize;
1767 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1769 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1770 for (i=0; i<l->filelen; i++)
1771 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1773 else // LordHavoc: bsp version 29 (normal white lighting)
1775 // LordHavoc: hope is not lost yet, check for a .lit file to load
1776 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1777 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1778 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1779 strlcat (litfilename, ".lit", sizeof (litfilename));
1780 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1781 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1784 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1786 i = LittleLong(((int *)data)[1]);
1789 if (developer_loading.integer)
1790 Con_Printf("loaded %s\n", litfilename);
1791 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1792 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1794 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1797 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1799 i = LittleLong(((int *)data)[1]);
1802 if (developer_loading.integer)
1803 Con_Printf("loaded %s\n", dlitfilename);
1804 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1805 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
1806 loadmodel->brushq3.deluxemapping_modelspace = false;
1807 loadmodel->brushq3.deluxemapping = true;
1816 Con_Printf("Unknown .lit file version (%d)\n", i);
1818 else if (filesize == 8)
1819 Con_Print("Empty .lit file, ignoring\n");
1821 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
1828 // LordHavoc: oh well, expand the white lighting data
1831 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1832 in = mod_base + l->fileofs;
1833 out = loadmodel->brushq1.lightdata;
1834 for (i = 0;i < l->filelen;i++)
1844 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1846 loadmodel->brushq1.num_compressedpvs = 0;
1847 loadmodel->brushq1.data_compressedpvs = NULL;
1850 loadmodel->brushq1.num_compressedpvs = l->filelen;
1851 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1852 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1855 // used only for HalfLife maps
1856 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1858 char key[128], value[4096];
1862 if (!COM_ParseToken_Simple(&data, false, false))
1864 if (com_token[0] != '{')
1868 if (!COM_ParseToken_Simple(&data, false, false))
1870 if (com_token[0] == '}')
1871 break; // end of worldspawn
1872 if (com_token[0] == '_')
1873 strlcpy(key, com_token + 1, sizeof(key));
1875 strlcpy(key, com_token, sizeof(key));
1876 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1877 key[strlen(key)-1] = 0;
1878 if (!COM_ParseToken_Simple(&data, false, false))
1880 dpsnprintf(value, sizeof(value), "%s", com_token);
1881 if (!strcmp("wad", key)) // for HalfLife maps
1883 if (loadmodel->brush.ishlbsp)
1886 for (i = 0;i < (int)sizeof(value);i++)
1887 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1891 for (;i < (int)sizeof(value);i++)
1893 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1894 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1896 else if (value[i] == ';' || value[i] == 0)
1900 W_LoadTextureWadFile(&value[j], false);
1912 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1914 loadmodel->brush.entities = NULL;
1917 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
1918 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1919 loadmodel->brush.entities[l->filelen] = 0;
1920 if (loadmodel->brush.ishlbsp)
1921 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1925 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1931 in = (dvertex_t *)(mod_base + l->fileofs);
1932 if (l->filelen % sizeof(*in))
1933 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1934 count = l->filelen / sizeof(*in);
1935 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1937 loadmodel->brushq1.vertexes = out;
1938 loadmodel->brushq1.numvertexes = count;
1940 for ( i=0 ; i<count ; i++, in++, out++)
1942 out->position[0] = LittleFloat(in->point[0]);
1943 out->position[1] = LittleFloat(in->point[1]);
1944 out->position[2] = LittleFloat(in->point[2]);
1948 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1949 // can be used for this
1951 int SB_ReadInt (unsigned char **buffer)
1954 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1960 float SB_ReadFloat (unsigned char **buffer)
1968 u.i = SB_ReadInt (buffer);
1972 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1974 unsigned char *index;
1978 index = (unsigned char *)(mod_base + l->fileofs);
1979 if (l->filelen % (48+4*hullinfo->filehulls))
1980 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1982 count = l->filelen / (48+4*hullinfo->filehulls);
1983 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1985 loadmodel->brushq1.submodels = out;
1986 loadmodel->brush.numsubmodels = count;
1988 for (i = 0; i < count; i++, out++)
1990 // spread out the mins / maxs by a pixel
1991 out->mins[0] = SB_ReadFloat (&index) - 1;
1992 out->mins[1] = SB_ReadFloat (&index) - 1;
1993 out->mins[2] = SB_ReadFloat (&index) - 1;
1994 out->maxs[0] = SB_ReadFloat (&index) + 1;
1995 out->maxs[1] = SB_ReadFloat (&index) + 1;
1996 out->maxs[2] = SB_ReadFloat (&index) + 1;
1997 out->origin[0] = SB_ReadFloat (&index);
1998 out->origin[1] = SB_ReadFloat (&index);
1999 out->origin[2] = SB_ReadFloat (&index);
2000 for (j = 0; j < hullinfo->filehulls; j++)
2001 out->headnode[j] = SB_ReadInt (&index);
2002 out->visleafs = SB_ReadInt (&index);
2003 out->firstface = SB_ReadInt (&index);
2004 out->numfaces = SB_ReadInt (&index);
2008 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2014 in = (dedge_t *)(mod_base + l->fileofs);
2015 if (l->filelen % sizeof(*in))
2016 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2017 count = l->filelen / sizeof(*in);
2018 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2020 loadmodel->brushq1.edges = out;
2021 loadmodel->brushq1.numedges = count;
2023 for ( i=0 ; i<count ; i++, in++, out++)
2025 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2026 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2027 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2029 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);
2030 if(!loadmodel->brushq1.numvertexes)
2031 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2039 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2043 int i, j, k, count, miptex;
2045 in = (texinfo_t *)(mod_base + l->fileofs);
2046 if (l->filelen % sizeof(*in))
2047 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2048 count = l->filelen / sizeof(*in);
2049 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2051 loadmodel->brushq1.texinfo = out;
2052 loadmodel->brushq1.numtexinfo = count;
2054 for (i = 0;i < count;i++, in++, out++)
2056 for (k = 0;k < 2;k++)
2057 for (j = 0;j < 4;j++)
2058 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2060 miptex = LittleLong(in->miptex);
2061 out->flags = LittleLong(in->flags);
2063 out->texture = NULL;
2064 if (loadmodel->data_textures)
2066 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2067 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2069 out->texture = loadmodel->data_textures + miptex;
2071 if (out->flags & TEX_SPECIAL)
2073 // if texture chosen is NULL or the shader needs a lightmap,
2074 // force to notexture water shader
2075 if (out->texture == NULL)
2076 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2080 // if texture chosen is NULL, force to notexture
2081 if (out->texture == NULL)
2082 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2088 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2093 mins[0] = mins[1] = mins[2] = 9999;
2094 maxs[0] = maxs[1] = maxs[2] = -9999;
2096 for (i = 0;i < numverts;i++)
2098 for (j = 0;j < 3;j++, v++)
2108 #define MAX_SUBDIVPOLYTRIANGLES 4096
2109 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2111 static int subdivpolyverts, subdivpolytriangles;
2112 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2113 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2115 static int subdivpolylookupvert(vec3_t v)
2118 for (i = 0;i < subdivpolyverts;i++)
2119 if (subdivpolyvert[i][0] == v[0]
2120 && subdivpolyvert[i][1] == v[1]
2121 && subdivpolyvert[i][2] == v[2])
2123 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2124 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2125 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2126 return subdivpolyverts++;
2129 static void SubdividePolygon(int numverts, float *verts)
2131 int i, i1, i2, i3, f, b, c, p;
2132 vec3_t mins, maxs, front[256], back[256];
2133 float m, *pv, *cv, dist[256], frac;
2136 Host_Error("SubdividePolygon: ran out of verts in buffer");
2138 BoundPoly(numverts, verts, mins, maxs);
2140 for (i = 0;i < 3;i++)
2142 m = (mins[i] + maxs[i]) * 0.5;
2143 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2144 if (maxs[i] - m < 8)
2146 if (m - mins[i] < 8)
2150 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2151 dist[c] = cv[i] - m;
2154 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2158 VectorCopy(pv, front[f]);
2163 VectorCopy(pv, back[b]);
2166 if (dist[p] == 0 || dist[c] == 0)
2168 if ((dist[p] > 0) != (dist[c] > 0) )
2171 frac = dist[p] / (dist[p] - dist[c]);
2172 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2173 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2174 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2180 SubdividePolygon(f, front[0]);
2181 SubdividePolygon(b, back[0]);
2185 i1 = subdivpolylookupvert(verts);
2186 i2 = subdivpolylookupvert(verts + 3);
2187 for (i = 2;i < numverts;i++)
2189 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2191 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2195 i3 = subdivpolylookupvert(verts + i * 3);
2196 subdivpolyindex[subdivpolytriangles][0] = i1;
2197 subdivpolyindex[subdivpolytriangles][1] = i2;
2198 subdivpolyindex[subdivpolytriangles][2] = i3;
2200 subdivpolytriangles++;
2204 //Breaks a polygon up along axial 64 unit
2205 //boundaries so that turbulent and sky warps
2206 //can be done reasonably.
2207 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2213 subdivpolytriangles = 0;
2214 subdivpolyverts = 0;
2215 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2216 if (subdivpolytriangles < 1)
2217 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2219 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2220 mesh->num_vertices = subdivpolyverts;
2221 mesh->num_triangles = subdivpolytriangles;
2222 mesh->vertex = (surfvertex_t *)(mesh + 1);
2223 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2224 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2226 for (i = 0;i < mesh->num_triangles;i++)
2227 for (j = 0;j < 3;j++)
2228 mesh->index[i*3+j] = subdivpolyindex[i][j];
2230 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2232 VectorCopy(subdivpolyvert[i], v->v);
2233 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2234 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2239 extern cvar_t gl_max_lightmapsize;
2240 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2243 msurface_t *surface;
2244 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2245 float texmins[2], texmaxs[2], val;
2246 rtexture_t *lightmaptexture, *deluxemaptexture;
2248 in = (dface_t *)(mod_base + l->fileofs);
2249 if (l->filelen % sizeof(*in))
2250 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2251 count = l->filelen / sizeof(*in);
2252 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2253 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2255 loadmodel->num_surfaces = count;
2257 loadmodel->brushq1.firstrender = true;
2258 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2262 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2264 numedges = (unsigned short)LittleShort(in->numedges);
2265 totalverts += numedges;
2266 totaltris += numedges - 2;
2269 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2271 lightmaptexture = NULL;
2272 deluxemaptexture = r_texture_blanknormalmap;
2274 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2275 totallightmapsamples = 0;
2279 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2281 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2283 // FIXME: validate edges, texinfo, etc?
2284 firstedge = LittleLong(in->firstedge);
2285 numedges = (unsigned short)LittleShort(in->numedges);
2286 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)
2287 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2288 i = (unsigned short)LittleShort(in->texinfo);
2289 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2290 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2291 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2292 surface->texture = surface->lightmapinfo->texinfo->texture;
2294 planenum = (unsigned short)LittleShort(in->planenum);
2295 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2296 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2298 //surface->flags = surface->texture->flags;
2299 //if (LittleShort(in->side))
2300 // surface->flags |= SURF_PLANEBACK;
2301 //surface->plane = loadmodel->brush.data_planes + planenum;
2303 surface->num_firstvertex = totalverts;
2304 surface->num_vertices = numedges;
2305 surface->num_firsttriangle = totaltris;
2306 surface->num_triangles = numedges - 2;
2307 totalverts += numedges;
2308 totaltris += numedges - 2;
2310 // convert edges back to a normal polygon
2311 for (i = 0;i < surface->num_vertices;i++)
2313 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2315 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2317 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2319 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2320 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2321 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2322 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2323 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2324 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2325 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2326 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2329 for (i = 0;i < surface->num_triangles;i++)
2331 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2332 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2333 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2336 // compile additional data about the surface geometry
2337 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);
2338 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);
2339 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2341 // generate surface extents information
2342 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2343 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2344 for (i = 1;i < surface->num_vertices;i++)
2346 for (j = 0;j < 2;j++)
2348 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2349 texmins[j] = min(texmins[j], val);
2350 texmaxs[j] = max(texmaxs[j], val);
2353 for (i = 0;i < 2;i++)
2355 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2356 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2359 smax = surface->lightmapinfo->extents[0] >> 4;
2360 tmax = surface->lightmapinfo->extents[1] >> 4;
2361 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2362 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2365 for (i = 0;i < MAXLIGHTMAPS;i++)
2366 surface->lightmapinfo->styles[i] = in->styles[i];
2367 surface->lightmaptexture = NULL;
2368 surface->deluxemaptexture = r_texture_blanknormalmap;
2369 i = LittleLong(in->lightofs);
2372 surface->lightmapinfo->samples = NULL;
2374 // give non-lightmapped water a 1x white lightmap
2375 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2377 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2378 surface->lightmapinfo->styles[0] = 0;
2379 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2383 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2384 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2385 else // LordHavoc: white lighting (bsp version 29)
2387 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2388 if (loadmodel->brushq1.nmaplightdata)
2389 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2392 // check if we should apply a lightmap to this
2393 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2395 if (ssize > 256 || tsize > 256)
2396 Host_Error("Bad surface extents");
2398 if (lightmapsize < ssize)
2399 lightmapsize = ssize;
2400 if (lightmapsize < tsize)
2401 lightmapsize = tsize;
2403 totallightmapsamples += ssize*tsize;
2405 // force lightmap upload on first time seeing the surface
2407 // additionally this is used by the later code to see if a
2408 // lightmap is needed on this surface (rather than duplicating the
2410 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2414 // small maps (such as ammo boxes especially) don't need big lightmap
2415 // textures, so this code tries to guess a good size based on
2416 // totallightmapsamples (size of the lightmaps lump basically), as well as
2417 // trying to max out the size if there is a lot of lightmap data to store
2418 // additionally, never choose a lightmapsize that is smaller than the
2419 // largest surface encountered (as it would fail)
2421 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2424 // now that we've decided the lightmap texture size, we can do the rest
2425 if (cls.state != ca_dedicated)
2427 int stainmapsize = 0;
2428 mod_alloclightmap_state_t allocState;
2430 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2431 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2433 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2434 float u, v, ubase, vbase, uscale, vscale;
2436 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2439 smax = surface->lightmapinfo->extents[0] >> 4;
2440 tmax = surface->lightmapinfo->extents[1] >> 4;
2441 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2442 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2443 stainmapsize += ssize * tsize * 3;
2445 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2447 // allocate a texture pool if we need it
2448 if (loadmodel->texturepool == NULL)
2449 loadmodel->texturepool = R_AllocTexturePool();
2450 // could not find room, make a new lightmap
2451 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2452 loadmodel->brushq3.data_lightmaps = Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2453 loadmodel->brushq3.data_deluxemaps = Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2454 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, NULL);
2455 if (loadmodel->brushq1.nmaplightdata)
2456 loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, NULL);
2458 Mod_AllocLightmap_Reset(&allocState);
2459 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2461 surface->lightmaptexture = lightmaptexture;
2462 surface->deluxemaptexture = deluxemaptexture;
2463 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2464 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2466 uscale = 1.0f / (float)lightmapsize;
2467 vscale = 1.0f / (float)lightmapsize;
2468 ubase = lightmapx * uscale;
2469 vbase = lightmapy * vscale;
2471 for (i = 0;i < surface->num_vertices;i++)
2473 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);
2474 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);
2475 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2476 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2477 // LordHavoc: calc lightmap data offset for vertex lighting to use
2480 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2484 if (cl_stainmaps.integer)
2486 // allocate stainmaps for permanent marks on walls and clear white
2487 unsigned char *stainsamples = NULL;
2488 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2489 memset(stainsamples, 255, stainmapsize);
2491 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2493 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2495 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2496 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2497 surface->lightmapinfo->stainsamples = stainsamples;
2498 stainsamples += ssize * tsize * 3;
2503 // generate ushort elements array if possible
2504 if (loadmodel->surfmesh.data_element3s)
2505 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2506 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2509 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2512 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2513 node->parent = parent;
2516 // this is a node, recurse to children
2517 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2518 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2519 // combine supercontents of children
2520 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2525 mleaf_t *leaf = (mleaf_t *)node;
2526 // if this is a leaf, calculate supercontents mask from all collidable
2527 // primitives in the leaf (brushes and collision surfaces)
2528 // also flag if the leaf contains any collision surfaces
2529 leaf->combinedsupercontents = 0;
2530 // combine the supercontents values of all brushes in this leaf
2531 for (j = 0;j < leaf->numleafbrushes;j++)
2532 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2533 // check if this leaf contains any collision surfaces (q3 patches)
2534 for (j = 0;j < leaf->numleafsurfaces;j++)
2536 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2537 if (surface->num_collisiontriangles)
2539 leaf->containscollisionsurfaces = true;
2540 leaf->combinedsupercontents |= surface->texture->supercontents;
2546 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2552 in = (dnode_t *)(mod_base + l->fileofs);
2553 if (l->filelen % sizeof(*in))
2554 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2555 count = l->filelen / sizeof(*in);
2556 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2558 loadmodel->brush.data_nodes = out;
2559 loadmodel->brush.num_nodes = count;
2561 for ( i=0 ; i<count ; i++, in++, out++)
2563 for (j=0 ; j<3 ; j++)
2565 out->mins[j] = LittleShort(in->mins[j]);
2566 out->maxs[j] = LittleShort(in->maxs[j]);
2569 p = LittleLong(in->planenum);
2570 out->plane = loadmodel->brush.data_planes + p;
2572 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2573 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2575 for (j=0 ; j<2 ; j++)
2577 // LordHavoc: this code supports broken bsp files produced by
2578 // arguire qbsp which can produce more than 32768 nodes, any value
2579 // below count is assumed to be a node number, any other value is
2580 // assumed to be a leaf number
2581 p = (unsigned short)LittleShort(in->children[j]);
2584 if (p < loadmodel->brush.num_nodes)
2585 out->children[j] = loadmodel->brush.data_nodes + p;
2588 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2589 // map it to the solid leaf
2590 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2595 // note this uses 65535 intentionally, -1 is leaf 0
2597 if (p < loadmodel->brush.num_leafs)
2598 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2601 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2602 // map it to the solid leaf
2603 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2609 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2612 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2618 in = (dleaf_t *)(mod_base + l->fileofs);
2619 if (l->filelen % sizeof(*in))
2620 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2621 count = l->filelen / sizeof(*in);
2622 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2624 loadmodel->brush.data_leafs = out;
2625 loadmodel->brush.num_leafs = count;
2626 // get visleafs from the submodel data
2627 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2628 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2629 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2630 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2632 for ( i=0 ; i<count ; i++, in++, out++)
2634 for (j=0 ; j<3 ; j++)
2636 out->mins[j] = LittleShort(in->mins[j]);
2637 out->maxs[j] = LittleShort(in->maxs[j]);
2640 // FIXME: this function could really benefit from some error checking
2642 out->contents = LittleLong(in->contents);
2644 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2645 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2646 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2648 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);
2649 out->firstleafsurface = NULL;
2650 out->numleafsurfaces = 0;
2653 out->clusterindex = i - 1;
2654 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2655 out->clusterindex = -1;
2657 p = LittleLong(in->visofs);
2658 // ignore visofs errors on leaf 0 (solid)
2659 if (p >= 0 && out->clusterindex >= 0)
2661 if (p >= loadmodel->brushq1.num_compressedpvs)
2662 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2664 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);
2667 for (j = 0;j < 4;j++)
2668 out->ambient_sound_level[j] = in->ambient_level[j];
2670 // FIXME: Insert caustics here
2674 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2678 const unsigned char *pvs;
2679 // if there's no vis data, assume supported (because everything is visible all the time)
2680 if (!loadmodel->brush.data_pvsclusters)
2682 // check all liquid leafs to see if they can see into empty leafs, if any
2683 // can we can assume this map supports r_wateralpha
2684 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2686 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2688 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2689 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2690 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2697 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2704 in = (dclipnode_t *)(mod_base + l->fileofs);
2705 if (l->filelen % sizeof(*in))
2706 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2707 count = l->filelen / sizeof(*in);
2708 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2710 loadmodel->brushq1.clipnodes = out;
2711 loadmodel->brushq1.numclipnodes = count;
2713 for (i = 1; i < MAX_MAP_HULLS; i++)
2715 hull = &loadmodel->brushq1.hulls[i];
2716 hull->clipnodes = out;
2717 hull->firstclipnode = 0;
2718 hull->lastclipnode = count-1;
2719 hull->planes = loadmodel->brush.data_planes;
2720 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2721 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2722 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2723 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2724 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2725 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2726 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2729 for (i=0 ; i<count ; i++, out++, in++)
2731 out->planenum = LittleLong(in->planenum);
2732 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2733 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2734 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2735 if (out->children[0] >= count)
2736 out->children[0] -= 65536;
2737 if (out->children[1] >= count)
2738 out->children[1] -= 65536;
2739 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2740 Host_Error("Corrupt clipping hull(out of range planenum)");
2744 //Duplicate the drawing hull structure as a clipping hull
2745 static void Mod_Q1BSP_MakeHull0(void)
2752 hull = &loadmodel->brushq1.hulls[0];
2754 in = loadmodel->brush.data_nodes;
2755 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2757 hull->clipnodes = out;
2758 hull->firstclipnode = 0;
2759 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2760 hull->planes = loadmodel->brush.data_planes;
2762 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2764 out->planenum = in->plane - loadmodel->brush.data_planes;
2765 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2766 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2770 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2775 in = (short *)(mod_base + l->fileofs);
2776 if (l->filelen % sizeof(*in))
2777 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2778 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2779 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2781 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2783 j = (unsigned short) LittleShort(in[i]);
2784 if (j >= loadmodel->num_surfaces)
2785 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2786 loadmodel->brush.data_leafsurfaces[i] = j;
2790 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2795 in = (int *)(mod_base + l->fileofs);
2796 if (l->filelen % sizeof(*in))
2797 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2798 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2799 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2801 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2802 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2806 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2812 in = (dplane_t *)(mod_base + l->fileofs);
2813 if (l->filelen % sizeof(*in))
2814 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2816 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2817 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2819 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2821 out->normal[0] = LittleFloat(in->normal[0]);
2822 out->normal[1] = LittleFloat(in->normal[1]);
2823 out->normal[2] = LittleFloat(in->normal[2]);
2824 out->dist = LittleFloat(in->dist);
2830 static void Mod_Q1BSP_LoadMapBrushes(void)
2834 int submodel, numbrushes;
2835 qboolean firstbrush;
2836 char *text, *maptext;
2837 char mapfilename[MAX_QPATH];
2838 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2839 strlcat (mapfilename, ".map", sizeof (mapfilename));
2840 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
2844 if (!COM_ParseToken_Simple(&data, false, false))
2849 if (!COM_ParseToken_Simple(&data, false, false))
2851 if (com_token[0] != '{')
2857 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2860 if (!COM_ParseToken_Simple(&data, false, false))
2862 if (com_token[0] == '}')
2863 break; // end of entity
2864 if (com_token[0] == '{')
2871 if (submodel > loadmodel->brush.numsubmodels)
2873 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2877 model = loadmodel->brush.submodels[submodel];
2884 if (!COM_ParseToken_Simple(&data, false, false))
2886 if (com_token[0] == '}')
2887 break; // end of brush
2888 // each brush face should be this format:
2889 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2890 // FIXME: support hl .map format
2891 for (pointnum = 0;pointnum < 3;pointnum++)
2893 COM_ParseToken_Simple(&data, false, false);
2894 for (componentnum = 0;componentnum < 3;componentnum++)
2896 COM_ParseToken_Simple(&data, false, false);
2897 point[pointnum][componentnum] = atof(com_token);
2899 COM_ParseToken_Simple(&data, false, false);
2901 COM_ParseToken_Simple(&data, false, false);
2902 strlcpy(facetexture, com_token, sizeof(facetexture));
2903 COM_ParseToken_Simple(&data, false, false);
2904 //scroll_s = atof(com_token);
2905 COM_ParseToken_Simple(&data, false, false);
2906 //scroll_t = atof(com_token);
2907 COM_ParseToken_Simple(&data, false, false);
2908 //rotate = atof(com_token);
2909 COM_ParseToken_Simple(&data, false, false);
2910 //scale_s = atof(com_token);
2911 COM_ParseToken_Simple(&data, false, false);
2912 //scale_t = atof(com_token);
2913 TriangleNormal(point[0], point[1], point[2], planenormal);
2914 VectorNormalizeDouble(planenormal);
2915 planedist = DotProduct(point[0], planenormal);
2916 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2926 #define MAX_PORTALPOINTS 64
2928 typedef struct portal_s
2931 mnode_t *nodes[2]; // [0] = front side of plane
2932 struct portal_s *next[2];
2934 double points[3*MAX_PORTALPOINTS];
2935 struct portal_s *chain; // all portals are linked into a list
2939 static memexpandablearray_t portalarray;
2941 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2943 // process only nodes (leafs already had their box calculated)
2947 // calculate children first
2948 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2949 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2951 // make combined bounding box from children
2952 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2953 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2954 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2955 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2956 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2957 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2960 static void Mod_Q1BSP_FinalizePortals(void)
2962 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
2966 mleaf_t *leaf, *endleaf;
2968 // tally up portal and point counts and recalculate bounding boxes for all
2969 // leafs (because qbsp is very sloppy)
2970 leaf = loadmodel->brush.data_leafs;
2971 endleaf = leaf + loadmodel->brush.num_leafs;
2972 if (mod_recalculatenodeboxes.integer)
2974 for (;leaf < endleaf;leaf++)
2976 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
2977 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2982 for (portalindex = 0;portalindex < portalrange;portalindex++)
2984 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
2987 // note: this check must match the one below or it will usually corrupt memory
2988 // 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
2989 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2992 numpoints += p->numpoints * 2;
2995 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
2996 loadmodel->brush.num_portals = numportals;
2997 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
2998 loadmodel->brush.num_portalpoints = numpoints;
2999 // clear all leaf portal chains
3000 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3001 loadmodel->brush.data_leafs[i].portals = NULL;
3002 // process all portals in the global portal chain, while freeing them
3003 portal = loadmodel->brush.data_portals;
3004 point = loadmodel->brush.data_portalpoints;
3005 for (portalindex = 0;portalindex < portalrange;portalindex++)
3007 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3010 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3012 // note: this check must match the one above or it will usually corrupt memory
3013 // 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
3014 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3016 // first make the back to front portal(forward portal)
3017 portal->points = point;
3018 portal->numpoints = p->numpoints;
3019 portal->plane.dist = p->plane.dist;
3020 VectorCopy(p->plane.normal, portal->plane.normal);
3021 portal->here = (mleaf_t *)p->nodes[1];
3022 portal->past = (mleaf_t *)p->nodes[0];
3024 for (j = 0;j < portal->numpoints;j++)
3026 VectorCopy(p->points + j*3, point->position);
3029 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3030 PlaneClassify(&portal->plane);
3032 // link into leaf's portal chain
3033 portal->next = portal->here->portals;
3034 portal->here->portals = portal;
3036 // advance to next portal
3039 // then make the front to back portal(backward portal)
3040 portal->points = point;
3041 portal->numpoints = p->numpoints;
3042 portal->plane.dist = -p->plane.dist;
3043 VectorNegate(p->plane.normal, portal->plane.normal);
3044 portal->here = (mleaf_t *)p->nodes[0];
3045 portal->past = (mleaf_t *)p->nodes[1];
3047 for (j = portal->numpoints - 1;j >= 0;j--)
3049 VectorCopy(p->points + j*3, point->position);
3052 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3053 PlaneClassify(&portal->plane);
3055 // link into leaf's portal chain
3056 portal->next = portal->here->portals;
3057 portal->here->portals = portal;
3059 // advance to next portal
3062 // add the portal's polygon points to the leaf bounding boxes
3063 if (mod_recalculatenodeboxes.integer)
3065 for (i = 0;i < 2;i++)
3067 leaf = (mleaf_t *)p->nodes[i];
3068 for (j = 0;j < p->numpoints;j++)
3070 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3071 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3072 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3073 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3074 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3075 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3081 // now recalculate the node bounding boxes from the leafs
3082 if (mod_recalculatenodeboxes.integer)
3083 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3091 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3094 Host_Error("AddPortalToNodes: NULL front node");
3096 Host_Error("AddPortalToNodes: NULL back node");
3097 if (p->nodes[0] || p->nodes[1])
3098 Host_Error("AddPortalToNodes: already included");
3099 // 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
3101 p->nodes[0] = front;
3102 p->next[0] = (portal_t *)front->portals;
3103 front->portals = (mportal_t *)p;
3106 p->next[1] = (portal_t *)back->portals;
3107 back->portals = (mportal_t *)p;
3112 RemovePortalFromNode
3115 static void RemovePortalFromNodes(portal_t *portal)
3119 void **portalpointer;
3121 for (i = 0;i < 2;i++)
3123 node = portal->nodes[i];
3125 portalpointer = (void **) &node->portals;
3128 t = (portal_t *)*portalpointer;
3130 Host_Error("RemovePortalFromNodes: portal not in leaf");
3134 if (portal->nodes[0] == node)
3136 *portalpointer = portal->next[0];
3137 portal->nodes[0] = NULL;
3139 else if (portal->nodes[1] == node)
3141 *portalpointer = portal->next[1];
3142 portal->nodes[1] = NULL;
3145 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3149 if (t->nodes[0] == node)
3150 portalpointer = (void **) &t->next[0];
3151 else if (t->nodes[1] == node)
3152 portalpointer = (void **) &t->next[1];
3154 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3159 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3160 static double *portalpointsbuffer;
3161 static int portalpointsbufferoffset;
3162 static int portalpointsbuffersize;
3163 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3166 mnode_t *front, *back, *other_node;
3167 mplane_t clipplane, *plane;
3168 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3169 int numfrontpoints, numbackpoints;
3170 double *frontpoints, *backpoints;
3172 // if a leaf, we're done
3176 // get some space for our clipping operations to use
3177 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3179 portalpointsbuffersize = portalpointsbufferoffset * 2;
3180 portalpointsbuffer = Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3182 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3183 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3184 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3185 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3187 plane = node->plane;
3189 front = node->children[0];
3190 back = node->children[1];
3192 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3194 // create the new portal by generating a polygon for the node plane,
3195 // and clipping it by all of the other portals(which came from nodes above this one)
3196 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3197 nodeportal->plane = *plane;
3199 // 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)
3200 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);
3201 nodeportal->numpoints = 4;
3202 side = 0; // shut up compiler warning
3203 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3205 clipplane = portal->plane;
3206 if (portal->nodes[0] == portal->nodes[1])
3207 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3208 if (portal->nodes[0] == node)
3210 else if (portal->nodes[1] == node)
3212 clipplane.dist = -clipplane.dist;
3213 VectorNegate(clipplane.normal, clipplane.normal);
3217 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3219 for (i = 0;i < nodeportal->numpoints*3;i++)
3220 frontpoints[i] = nodeportal->points[i];
3221 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);
3222 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3226 if (nodeportal->numpoints < 3)
3228 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3229 nodeportal->numpoints = 0;
3231 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3233 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3234 nodeportal->numpoints = 0;
3237 AddPortalToNodes(nodeportal, front, back);
3239 // split the portals of this node along this node's plane and assign them to the children of this node
3240 // (migrating the portals downward through the tree)
3241 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3243 if (portal->nodes[0] == portal->nodes[1])
3244 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3245 if (portal->nodes[0] == node)
3247 else if (portal->nodes[1] == node)
3250 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3251 nextportal = portal->next[side];
3252 if (!portal->numpoints)
3255 other_node = portal->nodes[!side];
3256 RemovePortalFromNodes(portal);
3258 // cut the portal into two portals, one on each side of the node plane
3259 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);
3261 if (!numfrontpoints)
3264 AddPortalToNodes(portal, back, other_node);
3266 AddPortalToNodes(portal, other_node, back);
3272 AddPortalToNodes(portal, front, other_node);
3274 AddPortalToNodes(portal, other_node, front);
3278 // the portal is split
3279 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3280 temp = splitportal->chain;
3281 *splitportal = *portal;
3282 splitportal->chain = temp;
3283 for (i = 0;i < numbackpoints*3;i++)
3284 splitportal->points[i] = backpoints[i];
3285 splitportal->numpoints = numbackpoints;
3286 for (i = 0;i < numfrontpoints*3;i++)
3287 portal->points[i] = frontpoints[i];
3288 portal->numpoints = numfrontpoints;
3292 AddPortalToNodes(portal, front, other_node);
3293 AddPortalToNodes(splitportal, back, other_node);
3297 AddPortalToNodes(portal, other_node, front);
3298 AddPortalToNodes(splitportal, other_node, back);
3302 Mod_Q1BSP_RecursiveNodePortals(front);
3303 Mod_Q1BSP_RecursiveNodePortals(back);
3305 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3308 static void Mod_Q1BSP_MakePortals(void)
3310 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3311 portalpointsbufferoffset = 0;
3312 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3313 portalpointsbuffer = Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3314 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3315 Mem_Free(portalpointsbuffer);
3316 portalpointsbuffer = NULL;
3317 portalpointsbufferoffset = 0;
3318 portalpointsbuffersize = 0;
3319 Mod_Q1BSP_FinalizePortals();
3320 Mem_ExpandableArray_FreeArray(&portalarray);
3323 //Returns PVS data for a given point
3324 //(note: can return NULL)
3325 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3328 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3330 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3331 if (((mleaf_t *)node)->clusterindex >= 0)
3332 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3337 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)
3341 float d = PlaneDiff(org, node->plane);
3343 node = node->children[0];
3344 else if (d < -radius)
3345 node = node->children[1];
3348 // go down both sides
3349 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3350 node = node->children[1];
3353 // if this leaf is in a cluster, accumulate the pvs bits
3354 if (((mleaf_t *)node)->clusterindex >= 0)
3357 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3358 for (i = 0;i < pvsbytes;i++)
3359 pvsbuffer[i] |= pvs[i];
3363 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3364 //of the given point.
3365 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3367 int bytes = model->brush.num_pvsclusterbytes;
3368 bytes = min(bytes, pvsbufferlength);
3369 if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3371 memset(pvsbuffer, 0xFF, bytes);
3375 memset(pvsbuffer, 0, bytes);
3376 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3380 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3385 VectorSubtract(inmaxs, inmins, size);
3386 if (cmodel->brush.ishlbsp)
3389 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3390 else if (size[0] <= 32)
3392 if (size[2] < 54) // pick the nearest of 36 or 72
3393 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3395 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3398 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3403 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3404 else if (size[0] <= 32)
3405 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3407 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3409 VectorCopy(inmins, outmins);
3410 VectorAdd(inmins, hull->clip_size, outmaxs);
3413 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3418 float dist, modelyawradius, modelradius;
3419 msurface_t *surface;
3420 int numshadowmeshtriangles;
3421 hullinfo_t hullinfo;
3422 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3423 model_brush_lightstyleinfo_t styleinfo[256];
3424 unsigned char *datapointer;
3426 mod->modeldatatypestring = "Q1BSP";
3428 mod->type = mod_brushq1;
3430 header = (dheader_t *)buffer;
3432 i = LittleLong(header->version);
3433 if (i != BSPVERSION && i != 30)
3434 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3435 mod->brush.ishlbsp = i == 30;
3437 // fill in hull info
3438 VectorClear (hullinfo.hullsizes[0][0]);
3439 VectorClear (hullinfo.hullsizes[0][1]);
3440 if (mod->brush.ishlbsp)
3442 mod->modeldatatypestring = "HLBSP";
3444 hullinfo.filehulls = 4;
3445 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3446 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3447 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3448 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3449 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3450 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3454 hullinfo.filehulls = 4;
3455 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3456 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3457 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3458 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3462 mod_base = (unsigned char*)buffer;
3463 for (i = 0; i < HEADER_LUMPS; i++)
3465 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3466 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3469 mod->soundfromcenter = true;
3470 mod->TraceBox = Mod_Q1BSP_TraceBox;
3471 mod->TraceLine = Mod_Q1BSP_TraceLine;
3472 mod->TracePoint = Mod_Q1BSP_TracePoint;
3473 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3474 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3475 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3476 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3477 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3478 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3479 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3480 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3481 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3482 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3483 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3484 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3485 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3486 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3487 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3488 mod->Draw = R_Q1BSP_Draw;
3489 mod->DrawDepth = R_Q1BSP_DrawDepth;
3490 mod->DrawDebug = R_Q1BSP_DrawDebug;
3491 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3492 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3493 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3494 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3495 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3496 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3497 mod->DrawLight = R_Q1BSP_DrawLight;
3501 mod->brush.qw_md4sum = 0;
3502 mod->brush.qw_md4sum2 = 0;
3503 for (i = 0;i < HEADER_LUMPS;i++)
3506 if (i == LUMP_ENTITIES)
3508 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3509 mod->brush.qw_md4sum ^= LittleLong(temp);
3510 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3512 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3513 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3516 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3517 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3518 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3519 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3520 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3521 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3522 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3523 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3524 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3525 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3526 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3527 // load submodels before leafs because they contain the number of vis leafs
3528 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3529 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3530 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3531 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3533 // check if the map supports transparent water rendering
3534 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3536 if (mod->brushq1.data_compressedpvs)
3537 Mem_Free(mod->brushq1.data_compressedpvs);
3538 mod->brushq1.data_compressedpvs = NULL;
3539 mod->brushq1.num_compressedpvs = 0;
3541 Mod_Q1BSP_MakeHull0();
3542 Mod_Q1BSP_MakePortals();
3544 mod->numframes = 2; // regular and alternate animation
3547 // make a single combined shadow mesh to allow optimized shadow volume creation
3548 numshadowmeshtriangles = 0;
3549 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3551 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3552 numshadowmeshtriangles += surface->num_triangles;
3554 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3555 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3556 Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, loadmodel->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
3557 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true, false);
3558 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
3560 if (loadmodel->brush.numsubmodels)
3561 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3563 // LordHavoc: to clear the fog around the original quake submodel code, I
3565 // first of all, some background info on the submodels:
3566 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3567 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3568 // now the weird for loop itself:
3569 // the loop functions in an odd way, on each iteration it sets up the
3570 // current 'mod' model (which despite the confusing code IS the model of
3571 // the number i), at the end of the loop it duplicates the model to become
3572 // the next submodel, and loops back to set up the new submodel.
3574 // LordHavoc: now the explanation of my sane way (which works identically):
3575 // set up the world model, then on each submodel copy from the world model
3576 // and set up the submodel with the respective model info.
3577 totalstylesurfaces = 0;
3579 for (i = 0;i < mod->brush.numsubmodels;i++)
3581 memset(stylecounts, 0, sizeof(stylecounts));
3582 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3584 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3585 for (j = 0;j < MAXLIGHTMAPS;j++)
3586 stylecounts[surface->lightmapinfo->styles[j]]++;
3588 for (k = 0;k < 255;k++)
3592 totalstylesurfaces += stylecounts[k];
3595 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3596 for (i = 0;i < mod->brush.numsubmodels;i++)
3598 // LordHavoc: this code was originally at the end of this loop, but
3599 // has been transformed to something more readable at the start here.
3604 // duplicate the basic information
3605 dpsnprintf(name, sizeof(name), "*%i", i);
3606 mod = Mod_FindName(name, loadmodel->name);
3607 // copy the base model to this one
3609 // rename the clone back to its proper name
3610 strlcpy(mod->name, name, sizeof(mod->name));
3611 mod->brush.parentmodel = loadmodel;
3612 // textures and memory belong to the main model
3613 mod->texturepool = NULL;
3614 mod->mempool = NULL;
3615 mod->brush.GetPVS = NULL;
3616 mod->brush.FatPVS = NULL;
3617 mod->brush.BoxTouchingPVS = NULL;
3618 mod->brush.BoxTouchingLeafPVS = NULL;
3619 mod->brush.BoxTouchingVisibleLeafs = NULL;
3620 mod->brush.FindBoxClusters = NULL;
3621 mod->brush.LightPoint = NULL;
3622 mod->brush.AmbientSoundLevelsForPoint = NULL;
3625 mod->brush.submodel = i;
3627 if (loadmodel->brush.submodels)
3628 loadmodel->brush.submodels[i] = mod;
3630 bm = &mod->brushq1.submodels[i];
3632 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3633 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3635 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3636 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3639 mod->firstmodelsurface = bm->firstface;
3640 mod->nummodelsurfaces = bm->numfaces;
3642 // set node/leaf parents for this submodel
3643 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3645 // make the model surface list (used by shadowing/lighting)
3646 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3647 Mod_MakeSortedSurfaces(mod);
3649 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3650 // (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)
3651 VectorCopy(bm->mins, mod->normalmins);
3652 VectorCopy(bm->maxs, mod->normalmaxs);
3653 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3654 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3655 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3656 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3657 modelradius = modelyawradius + modelradius * modelradius;
3658 modelyawradius = sqrt(modelyawradius);
3659 modelradius = sqrt(modelradius);
3660 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3661 mod->yawmins[2] = mod->normalmins[2];
3662 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3663 mod->yawmaxs[2] = mod->normalmaxs[2];
3664 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3665 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3666 mod->radius = modelradius;
3667 mod->radius2 = modelradius * modelradius;
3669 // this gets altered below if sky or water is used
3670 mod->DrawSky = NULL;
3671 mod->DrawAddWaterPlanes = NULL;
3673 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3674 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3675 if (mod->nummodelsurfaces)
3677 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3678 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3680 if (j < mod->nummodelsurfaces)
3681 mod->DrawSky = R_Q1BSP_DrawSky;
3683 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3684 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION))
3686 if (j < mod->nummodelsurfaces)
3687 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3689 // build lightstyle update chains
3690 // (used to rapidly mark lightmapupdateflags on many surfaces
3691 // when d_lightstylevalue changes)
3692 memset(stylecounts, 0, sizeof(stylecounts));
3693 for (k = 0;k < mod->nummodelsurfaces;k++)
3695 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3696 for (j = 0;j < MAXLIGHTMAPS;j++)
3697 stylecounts[surface->lightmapinfo->styles[j]]++;
3699 mod->brushq1.num_lightstyles = 0;
3700 for (k = 0;k < 255;k++)
3704 styleinfo[mod->brushq1.num_lightstyles].style = k;
3705 styleinfo[mod->brushq1.num_lightstyles].value = 0;
3706 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3707 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3708 remapstyles[k] = mod->brushq1.num_lightstyles;
3709 mod->brushq1.num_lightstyles++;
3712 for (k = 0;k < mod->nummodelsurfaces;k++)
3714 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3715 for (j = 0;j < MAXLIGHTMAPS;j++)
3717 if (surface->lightmapinfo->styles[j] != 255)
3719 int r = remapstyles[surface->lightmapinfo->styles[j]];
3720 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3724 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3725 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3729 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3730 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3732 //mod->brushq1.num_visleafs = bm->visleafs;
3734 if (mod_q1bsp_polygoncollisions.integer)
3736 Mod_MakeCollisionBIH(mod, true);
3737 // point traces and contents checks still use the bsp tree
3738 mod->TraceLine = Mod_CollisionBIH_TraceLine;
3739 mod->TraceBox = Mod_CollisionBIH_TraceBox;
3742 // generate VBOs and other shared data before cloning submodels
3746 Mod_Q1BSP_LoadMapBrushes();
3747 //Mod_Q1BSP_ProcessLightList();
3751 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);
3754 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3758 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3765 in = (void *)(mod_base + l->fileofs);
3766 if (l->filelen % sizeof(*in))
3767 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3768 count = l->filelen / sizeof(*in);
3769 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3772 loadmodel->num = count;
3774 for (i = 0;i < count;i++, in++, out++)
3780 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3787 in = (void *)(mod_base + l->fileofs);
3788 if (l->filelen % sizeof(*in))
3789 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3790 count = l->filelen / sizeof(*in);
3791 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3794 loadmodel->num = count;
3796 for (i = 0;i < count;i++, in++, out++)
3802 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3809 in = (void *)(mod_base + l->fileofs);
3810 if (l->filelen % sizeof(*in))
3811 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3812 count = l->filelen / sizeof(*in);
3813 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3816 loadmodel->num = count;
3818 for (i = 0;i < count;i++, in++, out++)
3824 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3831 in = (void *)(mod_base + l->fileofs);
3832 if (l->filelen % sizeof(*in))
3833 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3834 count = l->filelen / sizeof(*in);
3835 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3838 loadmodel->num = count;
3840 for (i = 0;i < count;i++, in++, out++)
3846 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3853 in = (void *)(mod_base + l->fileofs);
3854 if (l->filelen % sizeof(*in))
3855 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3856 count = l->filelen / sizeof(*in);
3857 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3860 loadmodel->num = count;
3862 for (i = 0;i < count;i++, in++, out++)
3868 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3875 in = (void *)(mod_base + l->fileofs);
3876 if (l->filelen % sizeof(*in))
3877 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3878 count = l->filelen / sizeof(*in);
3879 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3882 loadmodel->num = count;
3884 for (i = 0;i < count;i++, in++, out++)
3890 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3897 in = (void *)(mod_base + l->fileofs);
3898 if (l->filelen % sizeof(*in))
3899 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3900 count = l->filelen / sizeof(*in);
3901 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3904 loadmodel->num = count;
3906 for (i = 0;i < count;i++, in++, out++)
3912 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3919 in = (void *)(mod_base + l->fileofs);
3920 if (l->filelen % sizeof(*in))
3921 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3922 count = l->filelen / sizeof(*in);
3923 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3926 loadmodel->num = count;
3928 for (i = 0;i < count;i++, in++, out++)
3934 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3941 in = (void *)(mod_base + l->fileofs);
3942 if (l->filelen % sizeof(*in))
3943 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3944 count = l->filelen / sizeof(*in);
3945 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3948 loadmodel->num = count;
3950 for (i = 0;i < count;i++, in++, out++)
3956 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3963 in = (void *)(mod_base + l->fileofs);
3964 if (l->filelen % sizeof(*in))
3965 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3966 count = l->filelen / sizeof(*in);
3967 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3970 loadmodel->num = count;
3972 for (i = 0;i < count;i++, in++, out++)
3978 static void Mod_Q2BSP_LoadEdges(lump_t *l)
3985 in = (void *)(mod_base + l->fileofs);
3986 if (l->filelen % sizeof(*in))
3987 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
3988 count = l->filelen / sizeof(*in);
3989 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3992 loadmodel->num = count;
3994 for (i = 0;i < count;i++, in++, out++)
4000 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4007 in = (void *)(mod_base + l->fileofs);
4008 if (l->filelen % sizeof(*in))
4009 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4010 count = l->filelen / sizeof(*in);
4011 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4014 loadmodel->num = count;
4016 for (i = 0;i < count;i++, in++, out++)
4022 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4029 in = (void *)(mod_base + l->fileofs);
4030 if (l->filelen % sizeof(*in))
4031 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4032 count = l->filelen / sizeof(*in);
4033 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4036 loadmodel->num = count;
4038 for (i = 0;i < count;i++, in++, out++)
4044 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4051 in = (void *)(mod_base + l->fileofs);
4052 if (l->filelen % sizeof(*in))
4053 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4054 count = l->filelen / sizeof(*in);
4055 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4058 loadmodel->num = count;
4060 for (i = 0;i < count;i++, in++, out++)
4066 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4073 in = (void *)(mod_base + l->fileofs);
4074 if (l->filelen % sizeof(*in))
4075 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4076 count = l->filelen / sizeof(*in);
4077 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4080 loadmodel->num = count;
4082 for (i = 0;i < count;i++, in++, out++)
4088 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4095 in = (void *)(mod_base + l->fileofs);
4096 if (l->filelen % sizeof(*in))
4097 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4098 count = l->filelen / sizeof(*in);
4099 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4102 loadmodel->num = count;
4104 for (i = 0;i < count;i++, in++, out++)
4110 static void Mod_Q2BSP_LoadModels(lump_t *l)
4117 in = (void *)(mod_base + l->fileofs);
4118 if (l->filelen % sizeof(*in))
4119 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4120 count = l->filelen / sizeof(*in);
4121 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4124 loadmodel->num = count;
4126 for (i = 0;i < count;i++, in++, out++)
4132 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4135 q2dheader_t *header;
4137 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4139 mod->modeldatatypestring = "Q2BSP";
4141 mod->type = mod_brushq2;
4143 header = (q2dheader_t *)buffer;
4145 i = LittleLong(header->version);
4146 if (i != Q2BSPVERSION)
4147 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4149 mod_base = (unsigned char *)header;
4151 // swap all the lumps
4152 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4153 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4155 mod->brush.qw_md4sum = 0;
4156 mod->brush.qw_md4sum2 = 0;
4157 for (i = 0;i < Q2HEADER_LUMPS;i++)
4159 if (i == Q2LUMP_ENTITIES)
4161 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4162 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4164 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4167 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4168 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4169 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4170 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4171 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4172 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4173 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4174 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4175 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4176 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4177 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4178 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4179 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4180 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4181 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4182 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4183 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4184 // LordHavoc: must go last because this makes the submodels
4185 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4188 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4189 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4191 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4194 char key[128], value[MAX_INPUTLINE];
4196 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4197 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4198 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4201 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4202 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4203 loadmodel->brush.entities[l->filelen] = 0;
4204 data = loadmodel->brush.entities;
4205 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4206 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4207 loadmodel->brushq3.deluxemapping = false;
4208 if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4212 if (!COM_ParseToken_Simple(&data, false, false))
4214 if (com_token[0] == '}')
4215 break; // end of worldspawn
4216 if (com_token[0] == '_')
4217 strlcpy(key, com_token + 1, sizeof(key));
4219 strlcpy(key, com_token, sizeof(key));
4220 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4221 key[strlen(key)-1] = 0;
4222 if (!COM_ParseToken_Simple(&data, false, false))
4224 strlcpy(value, com_token, sizeof(value));
4225 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4227 #if _MSC_VER >= 1400
4228 #define sscanf sscanf_s
4231 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4232 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4234 VectorSet(v, 64, 64, 128);
4235 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4236 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]);
4237 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4238 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4241 else if (!strcmp("deluxeMaps", key))
4243 if (!strcmp(com_token, "1"))
4245 loadmodel->brushq3.deluxemapping = true;
4246 loadmodel->brushq3.deluxemapping_modelspace = true;
4248 else if (!strcmp(com_token, "2"))
4250 loadmodel->brushq3.deluxemapping = true;
4251 loadmodel->brushq3.deluxemapping_modelspace = false;
4258 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4264 in = (q3dtexture_t *)(mod_base + l->fileofs);
4265 if (l->filelen % sizeof(*in))
4266 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4267 count = l->filelen / sizeof(*in);
4268 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4270 loadmodel->data_textures = out;
4271 loadmodel->num_textures = count;
4272 loadmodel->num_texturesperskin = loadmodel->num_textures;
4274 for (i = 0;i < count;i++)
4276 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4277 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4278 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4281 if (cls.state == ca_dedicated)
4284 for (i = 0;i < count;i++, in++, out++)
4285 Mod_LoadTextureFromQ3Shader(out, out->name, true, true, TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS);
4288 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4294 in = (q3dplane_t *)(mod_base + l->fileofs);
4295 if (l->filelen % sizeof(*in))
4296 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4297 count = l->filelen / sizeof(*in);
4298 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4300 loadmodel->brush.data_planes = out;
4301 loadmodel->brush.num_planes = count;
4303 for (i = 0;i < count;i++, in++, out++)
4305 out->normal[0] = LittleFloat(in->normal[0]);
4306 out->normal[1] = LittleFloat(in->normal[1]);
4307 out->normal[2] = LittleFloat(in->normal[2]);
4308 out->dist = LittleFloat(in->dist);
4313 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4316 q3mbrushside_t *out;
4319 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4320 if (l->filelen % sizeof(*in))
4321 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4322 count = l->filelen / sizeof(*in);
4323 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4325 loadmodel->brush.data_brushsides = out;
4326 loadmodel->brush.num_brushsides = count;
4328 for (i = 0;i < count;i++, in++, out++)
4330 n = LittleLong(in->planeindex);
4331 if (n < 0 || n >= loadmodel->brush.num_planes)
4332 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4333 out->plane = loadmodel->brush.data_planes + n;
4334 n = LittleLong(in->textureindex);
4335 if (n < 0 || n >= loadmodel->num_textures)
4336 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4337 out->texture = loadmodel->data_textures + n;
4341 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4343 q3dbrushside_ig_t *in;
4344 q3mbrushside_t *out;
4347 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4348 if (l->filelen % sizeof(*in))
4349 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4350 count = l->filelen / sizeof(*in);
4351 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4353 loadmodel->brush.data_brushsides = out;
4354 loadmodel->brush.num_brushsides = count;
4356 for (i = 0;i < count;i++, in++, out++)
4358 n = LittleLong(in->planeindex);
4359 if (n < 0 || n >= loadmodel->brush.num_planes)
4360 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4361 out->plane = loadmodel->brush.data_planes + n;
4362 n = LittleLong(in->textureindex);
4363 if (n < 0 || n >= loadmodel->num_textures)
4364 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4365 out->texture = loadmodel->data_textures + n;
4369 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4373 int i, j, n, c, count, maxplanes, q3surfaceflags;
4374 colplanef_t *planes;
4376 in = (q3dbrush_t *)(mod_base + l->fileofs);
4377 if (l->filelen % sizeof(*in))
4378 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4379 count = l->filelen / sizeof(*in);
4380 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4382 loadmodel->brush.data_brushes = out;
4383 loadmodel->brush.num_brushes = count;
4388 for (i = 0;i < count;i++, in++, out++)
4390 n = LittleLong(in->firstbrushside);
4391 c = LittleLong(in->numbrushsides);
4392 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4393 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4394 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4395 out->numbrushsides = c;
4396 n = LittleLong(in->textureindex);
4397 if (n < 0 || n >= loadmodel->num_textures)
4398 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4399 out->texture = loadmodel->data_textures + n;
4401 // make a list of mplane_t structs to construct a colbrush from
4402 if (maxplanes < out->numbrushsides)
4404 maxplanes = out->numbrushsides;
4407 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4410 for (j = 0;j < out->numbrushsides;j++)
4412 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4413 planes[j].dist = out->firstbrushside[j].plane->dist;
4414 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4415 planes[j].texture = out->firstbrushside[j].texture;
4416 q3surfaceflags |= planes[j].q3surfaceflags;
4418 // make the colbrush from the planes
4419 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4421 // this whole loop can take a while (e.g. on redstarrepublic4)
4422 CL_KeepaliveMessage(false);
4428 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4434 in = (q3deffect_t *)(mod_base + l->fileofs);
4435 if (l->filelen % sizeof(*in))
4436 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4437 count = l->filelen / sizeof(*in);
4438 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4440 loadmodel->brushq3.data_effects = out;
4441 loadmodel->brushq3.num_effects = count;
4443 for (i = 0;i < count;i++, in++, out++)
4445 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4446 n = LittleLong(in->brushindex);
4447 if (n >= loadmodel->brush.num_brushes)
4449 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4452 out->brushindex = n;
4453 out->unknown = LittleLong(in->unknown);
4457 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4462 in = (q3dvertex_t *)(mod_base + l->fileofs);
4463 if (l->filelen % sizeof(*in))
4464 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4465 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4466 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4467 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4468 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4469 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4470 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4472 for (i = 0;i < count;i++, in++)
4474 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4475 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4476 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4477 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4478 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4479 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4480 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4481 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4482 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4483 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4484 // svector/tvector are calculated later in face loading
4485 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4486 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4487 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4488 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4492 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4498 in = (int *)(mod_base + l->fileofs);
4499 if (l->filelen % sizeof(int[3]))
4500 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4501 count = l->filelen / sizeof(*in);
4503 if(!loadmodel->brushq3.num_vertices)
4506 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4507 loadmodel->brushq3.num_triangles = 0;
4511 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4512 loadmodel->brushq3.num_triangles = count / 3;
4513 loadmodel->brushq3.data_element3i = out;
4515 for (i = 0;i < count;i++, in++, out++)
4517 *out = LittleLong(*in);
4518 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4520 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4526 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4528 q3dlightmap_t *input_pointer;
4529 int i, j, k, count, power, power2, endlightmap, mergewidth, mergeheight;
4532 unsigned char *convertedpixels;
4533 char mapname[MAX_QPATH];
4534 int size, bytesperpixel, rgbmap[3];
4536 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4538 // defaults for q3bsp
4545 loadmodel->brushq3.lightmapsize = 128;
4547 if (cls.state == ca_dedicated)
4550 if(mod_q3bsp_nolightmaps.integer)
4556 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4557 if (developer_loading.integer)
4558 Con_Printf("Using internal lightmaps\n");
4559 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4560 if (l->filelen % sizeof(*input_pointer))
4561 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4562 count = l->filelen / sizeof(*input_pointer);
4563 for(i = 0; i < count; ++i)
4564 inpixels[i] = input_pointer[i].rgb;
4568 // no internal lightmaps
4569 // try external lightmaps
4570 if (developer_loading.integer)
4571 Con_Printf("Using external lightmaps\n");
4572 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4573 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false);
4577 // using EXTERNAL lightmaps instead
4578 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4580 Mem_Free(inpixels[0]);
4581 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4591 for(count = 1; ; ++count)
4593 inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false);
4594 if(!inpixels[count])
4595 break; // we got all of them
4596 if(image_width != size || image_height != size)
4598 for(i = 0; i <= count; ++i)
4599 Mem_Free(inpixels[i]);
4600 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4605 convertedpixels = (unsigned char *) Mem_Alloc(tempmempool, size*size*4);
4606 loadmodel->brushq3.lightmapsize = size;
4607 loadmodel->brushq3.num_originallightmaps = count;
4609 // now check the surfaces to see if any of them index an odd numbered
4610 // lightmap, if so this is not a deluxemapped bsp file
4612 // also check what lightmaps are actually used, because q3map2 sometimes
4613 // (always?) makes an unused one at the end, which
4614 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4615 // reason when only one lightmap is used, which can throw off the
4616 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4617 // to see if the second lightmap is blank, if so it is not deluxemapped.
4618 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4619 // in Mod_Q3BSP_LoadEntities was failed
4620 if (!loadmodel->brushq3.deluxemapping)
4622 loadmodel->brushq3.deluxemapping = !(count & 1);
4623 loadmodel->brushq3.deluxemapping_modelspace = true;
4625 if (loadmodel->brushq3.deluxemapping)
4627 int facecount = faceslump->filelen / sizeof(q3dface_t);
4628 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4629 for (i = 0;i < facecount;i++)
4631 j = LittleLong(faces[i].lightmapindex);
4634 endlightmap = max(endlightmap, j + 1);
4635 if ((j & 1) || j + 1 >= count)
4637 loadmodel->brushq3.deluxemapping = false;
4644 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4645 // reason when only one lightmap is used, which can throw off the
4646 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4647 // to see if the second lightmap is blank, if so it is not deluxemapped.
4649 // further research has shown q3map2 sometimes creates a deluxemap and two
4650 // blank lightmaps, which must be handled properly as well
4651 if (endlightmap == 1 && count > 1)
4654 for (i = 0;i < size*size;i++)
4656 if (c[bytesperpixel*i + rgbmap[0]])
4658 if (c[bytesperpixel*i + rgbmap[1]])
4660 if (c[bytesperpixel*i + rgbmap[2]])
4665 // all pixels in the unused lightmap were black...
4666 loadmodel->brushq3.deluxemapping = false;
4671 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4673 // figure out what the most reasonable merge power is within limits
4675 loadmodel->brushq3.num_lightmapmergepower = 0;
4677 for(i = 0; (128 << i) < size; ++i)
4679 // i is now 0 for 128, 1 for 256, etc
4681 for (power = 1;power + i <= mod_q3bsp_lightmapmergepower.integer && (size << power) <= (int)vid.maxtexturesize_2d && (1 << (power * 2)) < 4 * (count >> (loadmodel->brushq3.deluxemapping ? 1 : 0)); power++)
4682 loadmodel->brushq3.num_lightmapmergepower = power;
4684 loadmodel->brushq3.num_lightmapmerge = 1 << loadmodel->brushq3.num_lightmapmergepower;
4686 loadmodel->brushq3.num_mergedlightmaps = ((count >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) + (1 << (loadmodel->brushq3.num_lightmapmergepower * 2)) - 1) >> (loadmodel->brushq3.num_lightmapmergepower * 2);
4687 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4688 if (loadmodel->brushq3.deluxemapping)
4689 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4691 // allocate a texture pool if we need it
4692 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4693 loadmodel->texturepool = R_AllocTexturePool();
4695 power = loadmodel->brushq3.num_lightmapmergepower;
4697 for (i = 0;i < count;i++)
4699 // figure out which merged lightmap texture this fits into
4700 int lightmapindex = i >> (loadmodel->brushq3.deluxemapping + power2);
4701 for (k = 0;k < size*size;k++)
4703 convertedpixels[k*4+0] = inpixels[i][k*bytesperpixel+rgbmap[0]];
4704 convertedpixels[k*4+1] = inpixels[i][k*bytesperpixel+rgbmap[1]];
4705 convertedpixels[k*4+2] = inpixels[i][k*bytesperpixel+rgbmap[2]];
4706 convertedpixels[k*4+3] = 255;
4708 if (loadmodel->brushq3.num_lightmapmergepower > 0)
4710 // if the lightmap has not been allocated yet, create it
4711 if (!loadmodel->brushq3.data_lightmaps[lightmapindex])
4713 // create a lightmap only as large as necessary to hold the
4714 // remaining size*size blocks
4715 // if there are multiple merged lightmap textures then they will
4716 // all be full size except the last one which may be smaller
4717 // because it only needs to the remaining blocks, and it will often
4718 // be odd sizes like 2048x512 due to only being 25% full or so.
4719 j = (count >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) - (lightmapindex << power2);
4720 for (mergewidth = 1;mergewidth < j && mergewidth < (1 << power);mergewidth *= 2)
4722 for (mergeheight = 1;mergewidth*mergeheight < j && mergeheight < (1 << power);mergeheight *= 2)
4724 if (developer_loading.integer)
4725 Con_Printf("lightmap merge texture #%i is %ix%i (%i of %i used)\n", lightmapindex, mergewidth*size, mergeheight*size, min(j, mergewidth*mergeheight), mergewidth*mergeheight);
4726 loadmodel->brushq3.data_lightmaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", lightmapindex), mergewidth * size, mergeheight * size, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : TEXF_ALLOWUPDATES), NULL);
4727 if (loadmodel->brushq3.data_deluxemaps)
4728 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%04i", lightmapindex), mergewidth * size, mergeheight * size, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : TEXF_ALLOWUPDATES), NULL);
4730 mergewidth = R_TextureWidth(loadmodel->brushq3.data_lightmaps[lightmapindex]) / size;
4731 mergeheight = R_TextureHeight(loadmodel->brushq3.data_lightmaps[lightmapindex]) / size;
4732 j = (i >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) & ((1 << power2) - 1);
4733 if (loadmodel->brushq3.deluxemapping && (i & 1))
4734 R_UpdateTexture(loadmodel->brushq3.data_deluxemaps[lightmapindex], convertedpixels, (j % mergewidth) * size, (j / mergewidth) * size, size, size);
4736 R_UpdateTexture(loadmodel->brushq3.data_lightmaps [lightmapindex], convertedpixels, (j % mergewidth) * size, (j / mergewidth) * size, size, size);
4740 // figure out which merged lightmap texture this fits into
4741 if (loadmodel->brushq3.deluxemapping && (i & 1))
4742 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%04i", lightmapindex), size, size, convertedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), NULL);
4744 loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", lightmapindex), size, size, convertedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), NULL);
4748 Mem_Free(convertedpixels);
4751 for(i = 0; i < count; ++i)
4752 Mem_Free(inpixels[i]);
4756 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
4761 *collisionstride = stride;
4764 cnt = (num_triangles + stride - 1) / stride;
4765 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
4766 for(j = 0; j < cnt; ++j)
4768 mins = &((*collisionbbox6f)[6 * j + 0]);
4769 maxs = &((*collisionbbox6f)[6 * j + 3]);
4770 for(k = 0; k < stride; ++k)
4772 tri = j * stride + k;
4773 if(tri >= num_triangles)
4775 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
4776 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
4777 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
4778 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
4779 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
4780 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
4781 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
4782 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
4783 if(vert[0] < mins[0]) mins[0] = vert[0];
4784 if(vert[1] < mins[1]) mins[1] = vert[1];
4785 if(vert[2] < mins[2]) mins[2] = vert[2];
4786 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4787 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4788 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4789 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
4790 if(vert[0] < mins[0]) mins[0] = vert[0];
4791 if(vert[1] < mins[1]) mins[1] = vert[1];
4792 if(vert[2] < mins[2]) mins[2] = vert[2];
4793 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4794 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4795 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4800 *collisionbbox6f = NULL;
4803 typedef struct patchtess_s
4807 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
4810 float *originalvertex3f;
4813 #define PATCHTESS_SAME_LODGROUP(a,b) \
4815 (a).lodgroup[0] == (b).lodgroup[0] && \
4816 (a).lodgroup[1] == (b).lodgroup[1] && \
4817 (a).lodgroup[2] == (b).lodgroup[2] && \
4818 (a).lodgroup[3] == (b).lodgroup[3] && \
4819 (a).lodgroup[4] == (b).lodgroup[4] && \
4820 (a).lodgroup[5] == (b).lodgroup[5] \
4823 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4825 q3dface_t *in, *oldin;
4826 msurface_t *out, *oldout;
4827 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;
4828 float lightmaptcbase[2], lightmaptcscale[2];
4829 //int *originalelement3i;
4830 //int *originalneighbor3i;
4831 float *originalvertex3f;
4832 //float *originalsvector3f;
4833 //float *originaltvector3f;
4834 float *originalnormal3f;
4835 float *originalcolor4f;
4836 float *originaltexcoordtexture2f;
4837 float *originaltexcoordlightmap2f;
4838 float *surfacecollisionvertex3f;
4839 int *surfacecollisionelement3i;
4841 patchtess_t *patchtess = NULL;
4842 int patchtesscount = 0;
4845 in = (q3dface_t *)(mod_base + l->fileofs);
4846 if (l->filelen % sizeof(*in))
4847 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4848 count = l->filelen / sizeof(*in);
4849 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4851 loadmodel->data_surfaces = out;
4852 loadmodel->num_surfaces = count;
4855 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
4863 for (;i < count;i++, in++, out++)
4865 // check face type first
4866 type = LittleLong(in->type);
4867 if (type != Q3FACETYPE_FLAT
4868 && type != Q3FACETYPE_PATCH
4869 && type != Q3FACETYPE_MESH
4870 && type != Q3FACETYPE_FLARE)
4872 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4876 n = LittleLong(in->textureindex);
4877 if (n < 0 || n >= loadmodel->num_textures)
4879 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4882 out->texture = loadmodel->data_textures + n;
4883 n = LittleLong(in->effectindex);
4884 if (n < -1 || n >= loadmodel->brushq3.num_effects)
4886 if (developer_extra.integer)
4887 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4893 out->effect = loadmodel->brushq3.data_effects + n;
4895 if (cls.state != ca_dedicated)
4897 out->lightmaptexture = NULL;
4898 out->deluxemaptexture = r_texture_blanknormalmap;
4899 n = LittleLong(in->lightmapindex);
4902 else if (n >= loadmodel->brushq3.num_originallightmaps)
4904 if(loadmodel->brushq3.num_originallightmaps != 0)
4905 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
4910 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> (loadmodel->brushq3.num_lightmapmergepower * 2 + loadmodel->brushq3.deluxemapping)];
4911 if (loadmodel->brushq3.deluxemapping)
4912 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> (loadmodel->brushq3.num_lightmapmergepower * 2 + loadmodel->brushq3.deluxemapping)];
4916 firstvertex = LittleLong(in->firstvertex);
4917 numvertices = LittleLong(in->numvertices);
4918 firstelement = LittleLong(in->firstelement);
4919 numtriangles = LittleLong(in->numelements) / 3;
4920 if (numtriangles * 3 != LittleLong(in->numelements))
4922 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));
4925 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4927 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);
4930 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4932 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);
4937 case Q3FACETYPE_FLAT:
4938 case Q3FACETYPE_MESH:
4939 // no processing necessary
4941 case Q3FACETYPE_PATCH:
4942 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4943 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4944 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))
4946 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
4949 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4951 // convert patch to Q3FACETYPE_MESH
4952 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4953 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4954 // bound to user settings
4955 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4956 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4957 // bound to sanity settings
4958 xtess = bound(0, xtess, 1024);
4959 ytess = bound(0, ytess, 1024);
4961 // lower quality collision patches! Same procedure as before, but different cvars
4962 // convert patch to Q3FACETYPE_MESH
4963 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4964 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4965 // bound to user settings
4966 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
4967 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
4968 // bound to sanity settings
4969 cxtess = bound(0, cxtess, 1024);
4970 cytess = bound(0, cytess, 1024);
4972 // store it for the LOD grouping step
4973 patchtess[patchtesscount].info.xsize = patchsize[0];
4974 patchtess[patchtesscount].info.ysize = patchsize[1];
4975 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
4976 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
4977 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
4978 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
4980 patchtess[patchtesscount].surface_id = i;
4981 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
4982 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
4983 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
4984 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
4985 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
4986 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
4987 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
4990 case Q3FACETYPE_FLARE:
4991 if (developer_extra.integer)
4992 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
4996 out->num_vertices = numvertices;
4997 out->num_triangles = numtriangles;
4998 meshvertices += out->num_vertices;
4999 meshtriangles += out->num_triangles;
5002 // Fix patches tesselations so that they make no seams
5006 for(i = 0; i < patchtesscount; ++i)
5008 for(j = i+1; j < patchtesscount; ++j)
5010 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5013 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5020 // Calculate resulting number of triangles
5021 collisionvertices = 0;
5022 collisiontriangles = 0;
5023 for(i = 0; i < patchtesscount; ++i)
5025 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5026 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5027 numvertices = finalwidth * finalheight;
5028 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5030 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5031 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5032 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5033 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5035 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5036 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5037 numvertices = finalwidth * finalheight;
5038 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5040 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5041 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5042 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5043 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5049 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5050 if (collisiontriangles)
5052 loadmodel->brush.data_collisionvertex3f = Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5053 loadmodel->brush.data_collisionelement3i = Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5057 collisionvertices = 0;
5058 collisiontriangles = 0;
5059 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5061 if (out->num_vertices < 3 || out->num_triangles < 1)
5064 type = LittleLong(in->type);
5065 firstvertex = LittleLong(in->firstvertex);
5066 firstelement = LittleLong(in->firstelement);
5067 out->num_firstvertex = meshvertices;
5068 out->num_firsttriangle = meshtriangles;
5069 out->num_firstcollisiontriangle = collisiontriangles;
5072 case Q3FACETYPE_FLAT:
5073 case Q3FACETYPE_MESH:
5074 // no processing necessary, except for lightmap merging
5075 for (j = 0;j < out->num_vertices;j++)
5077 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5078 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5079 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5080 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5081 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5082 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5083 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5084 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5085 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5086 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5087 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5088 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5089 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5090 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5092 for (j = 0;j < out->num_triangles*3;j++)
5093 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5095 case Q3FACETYPE_PATCH:
5096 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5097 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5098 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5099 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5100 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5101 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5102 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5104 xtess = ytess = cxtess = cytess = -1;
5105 for(j = 0; j < patchtesscount; ++j)
5106 if(patchtess[j].surface_id == i)
5108 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5109 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5110 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5111 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5116 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5117 xtess = ytess = cxtess = cytess = 0;
5120 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5121 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5122 finalvertices = finalwidth * finalheight;
5123 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5124 type = Q3FACETYPE_MESH;
5125 // generate geometry
5126 // (note: normals are skipped because they get recalculated)
5127 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5128 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5129 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5130 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5131 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5132 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5134 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);
5136 if (developer_extra.integer)
5138 if (out->num_triangles < finaltriangles)
5139 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);
5141 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);
5143 // q3map does not put in collision brushes for curves... ugh
5144 // build the lower quality collision geometry
5145 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5146 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5147 finalvertices = finalwidth * finalheight;
5148 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5150 // legacy collision geometry implementation
5151 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5152 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5153 out->num_collisionvertices = finalvertices;
5154 out->num_collisiontriangles = finaltriangles;
5155 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5156 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5158 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5159 Mod_SnapVertices(3, out->num_collisionvertices, out->deprecatedq3data_collisionvertex3f, 1);
5161 oldnumtriangles = out->num_triangles;
5162 oldnumtriangles2 = out->num_collisiontriangles;
5163 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->num_collisiontriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5165 // now optimize the collision mesh by finding triangle bboxes...
5166 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5167 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);
5169 // store collision geometry for BIH collision tree
5170 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5171 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5172 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5173 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5174 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5175 oldnumtriangles = out->num_triangles;
5176 oldnumtriangles2 = out->num_collisiontriangles;
5177 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->num_collisiontriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5179 if (developer_extra.integer)
5180 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);
5182 collisionvertices += finalvertices;
5183 collisiontriangles += out->num_collisiontriangles;
5188 meshvertices += out->num_vertices;
5189 meshtriangles += out->num_triangles;
5190 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5191 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)
5193 if (invalidelements)
5195 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);
5196 for (j = 0;j < out->num_triangles * 3;j++)
5198 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5199 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)
5200 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5204 // calculate a bounding box
5205 VectorClear(out->mins);
5206 VectorClear(out->maxs);
5207 if (out->num_vertices)
5209 if (cls.state != ca_dedicated && out->lightmaptexture)
5211 // figure out which part of the merged lightmap this fits into
5212 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5213 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5214 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5215 lightmapindex &= mergewidth * mergeheight - 1;
5216 lightmaptcscale[0] = 1.0f / mergewidth;
5217 lightmaptcscale[1] = 1.0f / mergeheight;
5218 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5219 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5220 // modify the lightmap texcoords to match this region of the merged lightmap
5221 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5223 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5224 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5227 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5228 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5229 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5231 out->mins[0] = min(out->mins[0], v[0]);
5232 out->maxs[0] = max(out->maxs[0], v[0]);
5233 out->mins[1] = min(out->mins[1], v[1]);
5234 out->maxs[1] = max(out->maxs[1], v[1]);
5235 out->mins[2] = min(out->mins[2], v[2]);
5236 out->maxs[2] = max(out->maxs[2], v[2]);
5238 out->mins[0] -= 1.0f;
5239 out->mins[1] -= 1.0f;
5240 out->mins[2] -= 1.0f;
5241 out->maxs[0] += 1.0f;
5242 out->maxs[1] += 1.0f;
5243 out->maxs[2] += 1.0f;
5245 // set lightmap styles for consistency with q1bsp
5246 //out->lightmapinfo->styles[0] = 0;
5247 //out->lightmapinfo->styles[1] = 255;
5248 //out->lightmapinfo->styles[2] = 255;
5249 //out->lightmapinfo->styles[3] = 255;
5254 for (;i < count;i++, out++)
5256 if(out->num_vertices && out->num_triangles)
5258 if(out->num_vertices == 0)
5259 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d has no vertices, ignoring\n", i);
5260 if(out->num_triangles == 0)
5261 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d has no triangles, ignoring\n", i);
5264 // for per pixel lighting
5265 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);
5267 // generate ushort elements array if possible
5268 if (loadmodel->surfmesh.data_element3s)
5269 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5270 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5272 // free the no longer needed vertex data
5273 loadmodel->brushq3.num_vertices = 0;
5274 if (loadmodel->brushq3.data_vertex3f)
5275 Mem_Free(loadmodel->brushq3.data_vertex3f);
5276 loadmodel->brushq3.data_vertex3f = NULL;
5277 loadmodel->brushq3.data_normal3f = NULL;
5278 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5279 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5280 loadmodel->brushq3.data_color4f = NULL;
5281 // free the no longer needed triangle data
5282 loadmodel->brushq3.num_triangles = 0;
5283 if (loadmodel->brushq3.data_element3i)
5284 Mem_Free(loadmodel->brushq3.data_element3i);
5285 loadmodel->brushq3.data_element3i = NULL;
5288 Mem_Free(patchtess);
5291 static void Mod_Q3BSP_LoadModels(lump_t *l)
5295 int i, j, n, c, count;
5297 in = (q3dmodel_t *)(mod_base + l->fileofs);
5298 if (l->filelen % sizeof(*in))
5299 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5300 count = l->filelen / sizeof(*in);
5301 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5303 loadmodel->brushq3.data_models = out;
5304 loadmodel->brushq3.num_models = count;
5306 for (i = 0;i < count;i++, in++, out++)
5308 for (j = 0;j < 3;j++)
5310 out->mins[j] = LittleFloat(in->mins[j]);
5311 out->maxs[j] = LittleFloat(in->maxs[j]);
5313 n = LittleLong(in->firstface);
5314 c = LittleLong(in->numfaces);
5315 if (n < 0 || n + c > loadmodel->num_surfaces)
5316 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5319 n = LittleLong(in->firstbrush);
5320 c = LittleLong(in->numbrushes);
5321 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5322 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5323 out->firstbrush = n;
5324 out->numbrushes = c;
5328 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5334 in = (int *)(mod_base + l->fileofs);
5335 if (l->filelen % sizeof(*in))
5336 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5337 count = l->filelen / sizeof(*in);
5338 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5340 loadmodel->brush.data_leafbrushes = out;
5341 loadmodel->brush.num_leafbrushes = count;
5343 for (i = 0;i < count;i++, in++, out++)
5345 n = LittleLong(*in);
5346 if (n < 0 || n >= loadmodel->brush.num_brushes)
5347 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5352 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5358 in = (int *)(mod_base + l->fileofs);
5359 if (l->filelen % sizeof(*in))
5360 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5361 count = l->filelen / sizeof(*in);
5362 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5364 loadmodel->brush.data_leafsurfaces = out;
5365 loadmodel->brush.num_leafsurfaces = count;
5367 for (i = 0;i < count;i++, in++, out++)
5369 n = LittleLong(*in);
5370 if (n < 0 || n >= loadmodel->num_surfaces)
5371 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5376 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5380 int i, j, n, c, count;
5382 in = (q3dleaf_t *)(mod_base + l->fileofs);
5383 if (l->filelen % sizeof(*in))
5384 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5385 count = l->filelen / sizeof(*in);
5386 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5388 loadmodel->brush.data_leafs = out;
5389 loadmodel->brush.num_leafs = count;
5391 for (i = 0;i < count;i++, in++, out++)
5395 out->clusterindex = LittleLong(in->clusterindex);
5396 out->areaindex = LittleLong(in->areaindex);
5397 for (j = 0;j < 3;j++)
5399 // yes the mins/maxs are ints
5400 out->mins[j] = LittleLong(in->mins[j]) - 1;
5401 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5403 n = LittleLong(in->firstleafface);
5404 c = LittleLong(in->numleaffaces);
5405 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5406 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5407 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5408 out->numleafsurfaces = c;
5409 n = LittleLong(in->firstleafbrush);
5410 c = LittleLong(in->numleafbrushes);
5411 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5412 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5413 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5414 out->numleafbrushes = c;
5418 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5424 in = (q3dnode_t *)(mod_base + l->fileofs);
5425 if (l->filelen % sizeof(*in))
5426 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5427 count = l->filelen / sizeof(*in);
5428 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5430 loadmodel->brush.data_nodes = out;
5431 loadmodel->brush.num_nodes = count;
5433 for (i = 0;i < count;i++, in++, out++)
5436 n = LittleLong(in->planeindex);
5437 if (n < 0 || n >= loadmodel->brush.num_planes)
5438 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5439 out->plane = loadmodel->brush.data_planes + n;
5440 for (j = 0;j < 2;j++)
5442 n = LittleLong(in->childrenindex[j]);
5445 if (n >= loadmodel->brush.num_nodes)
5446 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5447 out->children[j] = loadmodel->brush.data_nodes + n;
5452 if (n >= loadmodel->brush.num_leafs)
5453 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5454 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5457 for (j = 0;j < 3;j++)
5459 // yes the mins/maxs are ints
5460 out->mins[j] = LittleLong(in->mins[j]) - 1;
5461 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5465 // set the parent pointers
5466 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5469 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5472 q3dlightgrid_t *out;
5475 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5476 if (l->filelen % sizeof(*in))
5477 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5478 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5479 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5480 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5481 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5482 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5483 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5484 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5485 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5486 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5487 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5488 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5489 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5490 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5491 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]);
5492 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]);
5494 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5497 if (l->filelen < count * (int)sizeof(*in))
5499 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]);
5500 return; // ignore the grid if we cannot understand it
5502 if (l->filelen != count * (int)sizeof(*in))
5503 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5504 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5505 loadmodel->brushq3.data_lightgrid = out;
5506 loadmodel->brushq3.num_lightgrid = count;
5507 // no swapping or validation necessary
5508 memcpy(out, in, count * (int)sizeof(*out));
5512 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5517 if (l->filelen == 0)
5520 // unvised maps often have cluster indices even without pvs, so check
5521 // leafs to find real number of clusters
5522 loadmodel->brush.num_pvsclusters = 1;
5523 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5524 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5527 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5528 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5529 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5530 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5534 in = (q3dpvs_t *)(mod_base + l->fileofs);
5536 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5538 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5539 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5540 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5541 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5542 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5543 if (l->filelen < totalchains + (int)sizeof(*in))
5544 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);
5546 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5547 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5550 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5552 int i, j, k, index[3];
5553 float transformed[3], blend1, blend2, blend, stylescale;
5554 q3dlightgrid_t *a, *s;
5556 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5557 stylescale = r_refdef.scene.rtlightstylevalue[0];
5559 if (!model->brushq3.num_lightgrid)
5561 ambientcolor[0] = stylescale;
5562 ambientcolor[1] = stylescale;
5563 ambientcolor[2] = stylescale;
5567 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5568 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5569 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5570 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5571 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5572 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5573 index[0] = (int)floor(transformed[0]);
5574 index[1] = (int)floor(transformed[1]);
5575 index[2] = (int)floor(transformed[2]);
5576 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5578 // now lerp the values
5579 VectorClear(diffusenormal);
5580 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5581 for (k = 0;k < 2;k++)
5583 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5584 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5586 for (j = 0;j < 2;j++)
5588 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5589 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5591 for (i = 0;i < 2;i++)
5593 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5594 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5596 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5597 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5598 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5599 // this uses the mod_md3_sin table because the values are
5600 // already in the 0-255 range, the 64+ bias fetches a cosine
5601 // instead of a sine value
5602 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5603 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5604 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5605 //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)));
5610 // normalize the light direction before turning
5611 VectorNormalize(diffusenormal);
5612 //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]);
5615 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5618 double midf, mid[3];
5624 // find the point distances
5625 mplane_t *plane = node->plane;
5626 if (plane->type < 3)
5628 t1 = p1[plane->type] - plane->dist;
5629 t2 = p2[plane->type] - plane->dist;
5633 t1 = DotProduct (plane->normal, p1) - plane->dist;
5634 t2 = DotProduct (plane->normal, p2) - plane->dist;
5641 node = node->children[1];
5650 node = node->children[0];
5656 midf = t1 / (t1 - t2);
5657 VectorLerp(p1, midf, p2, mid);
5659 // recurse both sides, front side first
5660 // return 2 if empty is followed by solid (hit something)
5661 // do not return 2 if both are solid or both empty,
5662 // or if start is solid and end is empty
5663 // as these degenerate cases usually indicate the eye is in solid and
5664 // should see the target point anyway
5665 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
5668 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5673 return ((mleaf_t *)node)->clusterindex < 0;
5676 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5678 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
5681 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
5682 return trace.fraction == 1;
5686 double tracestart[3], traceend[3];
5687 VectorCopy(start, tracestart);
5688 VectorCopy(end, traceend);
5689 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
5693 static void Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const vec3_t point)
5695 const bih_leaf_t *leaf;
5696 const bih_node_t *node;
5697 const colbrushf_t *brush;
5699 while (nodenum >= 0)
5701 node = model->collision_bih.nodes + nodenum;
5702 axis = node->type - BIH_SPLITX;
5703 if (point[axis] <= node->backmax)
5705 if (point[axis] >= node->frontmin)
5706 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, node->front, point);
5707 nodenum = node->back;
5709 else if (point[axis] >= node->frontmin)
5710 nodenum = node->front;
5711 else // no overlap with either child? just return
5714 if (!model->collision_bih.leafs)
5716 leaf = model->collision_bih.leafs + (-1-nodenum);
5721 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5722 Collision_TracePointBrushFloat(trace, point, brush);
5725 // collision triangle - skipped because they have no volume
5728 // render triangle - skipped because they have no volume
5735 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)
5737 const bih_leaf_t *leaf;
5738 const bih_node_t *node;
5739 const colbrushf_t *brush;
5741 const texture_t *texture;
5755 segmentmins[0] = min(start[0], end[0]);
5756 segmentmins[1] = min(start[1], end[1]);
5757 segmentmins[2] = min(start[2], end[2]);
5758 segmentmaxs[0] = max(start[0], end[0]);
5759 segmentmaxs[1] = max(start[1], end[1]);
5760 segmentmaxs[2] = max(start[2], end[2]);
5761 while (nodenum >= 0)
5763 node = model->collision_bih.nodes + nodenum;
5765 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
5768 axis = node->type - BIH_SPLITX;
5770 if (segmentmins[axis] <= node->backmax)
5772 if (segmentmaxs[axis] >= node->frontmin)
5773 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5774 nodenum = node->back;
5776 else if (segmentmaxs[axis] >= node->frontmin)
5777 nodenum = node->front;
5779 return; // trace falls between children
5781 frontdist1 = start[axis] - node->backmax;
5782 frontdist2 = end[axis] - node->backmax;
5783 backdist1 = start[axis] - node->frontmin;
5784 backdist2 = end[axis] - node->frontmin;
5797 // start end START END
5798 nodenum = node->front;
5801 // START end START END
5802 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5803 VectorLerp(start, frontfrac, end, clipped[0]);
5805 segmentmins[0] = min(start[0], end[0]);
5806 segmentmins[1] = min(start[1], end[1]);
5807 segmentmins[2] = min(start[2], end[2]);
5808 segmentmaxs[0] = max(start[0], end[0]);
5809 segmentmaxs[1] = max(start[1], end[1]);
5810 segmentmaxs[2] = max(start[2], end[2]);
5811 nodenum = node->front;
5814 // start END START END
5815 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5816 VectorLerp(start, frontfrac, end, clipped[0]);
5818 segmentmins[0] = min(start[0], end[0]);
5819 segmentmins[1] = min(start[1], end[1]);
5820 segmentmins[2] = min(start[2], end[2]);
5821 segmentmaxs[0] = max(start[0], end[0]);
5822 segmentmaxs[1] = max(start[1], end[1]);
5823 segmentmaxs[2] = max(start[2], end[2]);
5824 nodenum = node->front;
5827 // START END START END
5828 return; // line falls in gap between children
5830 // start end start END
5831 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5832 backfrac = backdist1 / (backdist1 - backdist2);
5833 VectorLerp(start, backfrac, end, clipped[0]);
5835 segmentmins[0] = min(start[0], end[0]);
5836 segmentmins[1] = min(start[1], end[1]);
5837 segmentmins[2] = min(start[2], end[2]);
5838 segmentmaxs[0] = max(start[0], end[0]);
5839 segmentmaxs[1] = max(start[1], end[1]);
5840 segmentmaxs[2] = max(start[2], end[2]);
5841 nodenum = node->back;
5844 // START end start END
5845 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5846 VectorLerp(start, frontfrac, end, clipped[1]);
5847 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5848 backfrac = backdist1 / (backdist1 - backdist2);
5849 VectorLerp(start, backfrac, end, clipped[0]);
5851 segmentmins[0] = min(start[0], end[0]);
5852 segmentmins[1] = min(start[1], end[1]);
5853 segmentmins[2] = min(start[2], end[2]);
5854 segmentmaxs[0] = max(start[0], end[0]);
5855 segmentmaxs[1] = max(start[1], end[1]);
5856 segmentmaxs[2] = max(start[2], end[2]);
5857 nodenum = node->back;
5860 // start END start END
5861 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5862 VectorLerp(start, frontfrac, end, clipped[1]);
5863 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5864 backfrac = backdist1 / (backdist1 - backdist2);
5865 VectorLerp(start, backfrac, end, clipped[0]);
5867 segmentmins[0] = min(start[0], end[0]);
5868 segmentmins[1] = min(start[1], end[1]);
5869 segmentmins[2] = min(start[2], end[2]);
5870 segmentmaxs[0] = max(start[0], end[0]);
5871 segmentmaxs[1] = max(start[1], end[1]);
5872 segmentmaxs[2] = max(start[2], end[2]);
5873 nodenum = node->back;
5876 // START END start END
5877 backfrac = backdist1 / (backdist1 - backdist2);
5878 VectorLerp(start, backfrac, end, clipped[0]);
5880 segmentmins[0] = min(start[0], end[0]);
5881 segmentmins[1] = min(start[1], end[1]);
5882 segmentmins[2] = min(start[2], end[2]);
5883 segmentmaxs[0] = max(start[0], end[0]);
5884 segmentmaxs[1] = max(start[1], end[1]);
5885 segmentmaxs[2] = max(start[2], end[2]);
5886 nodenum = node->back;
5889 // start end START end
5890 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5891 backfrac = backdist1 / (backdist1 - backdist2);
5892 VectorLerp(start, backfrac, end, clipped[0]);
5894 segmentmins[0] = min(start[0], end[0]);
5895 segmentmins[1] = min(start[1], end[1]);
5896 segmentmins[2] = min(start[2], end[2]);
5897 segmentmaxs[0] = max(start[0], end[0]);
5898 segmentmaxs[1] = max(start[1], end[1]);
5899 segmentmaxs[2] = max(start[2], end[2]);
5900 nodenum = node->back;
5903 // START end START end
5904 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5905 VectorLerp(start, frontfrac, end, clipped[1]);
5906 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5907 backfrac = backdist1 / (backdist1 - backdist2);
5908 VectorLerp(start, backfrac, end, clipped[0]);
5910 segmentmins[0] = min(start[0], end[0]);
5911 segmentmins[1] = min(start[1], end[1]);
5912 segmentmins[2] = min(start[2], end[2]);
5913 segmentmaxs[0] = max(start[0], end[0]);
5914 segmentmaxs[1] = max(start[1], end[1]);
5915 segmentmaxs[2] = max(start[2], end[2]);
5916 nodenum = node->back;
5919 // start END START end
5920 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5921 VectorLerp(start, frontfrac, end, clipped[1]);
5922 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5923 backfrac = backdist1 / (backdist1 - backdist2);
5924 VectorLerp(start, backfrac, end, clipped[0]);
5926 segmentmins[0] = min(start[0], end[0]);
5927 segmentmins[1] = min(start[1], end[1]);
5928 segmentmins[2] = min(start[2], end[2]);
5929 segmentmaxs[0] = max(start[0], end[0]);
5930 segmentmaxs[1] = max(start[1], end[1]);
5931 segmentmaxs[2] = max(start[2], end[2]);
5932 nodenum = node->back;
5935 // START END START end
5936 backfrac = backdist1 / (backdist1 - backdist2);
5937 VectorLerp(start, backfrac, end, clipped[0]);
5939 segmentmins[0] = min(start[0], end[0]);
5940 segmentmins[1] = min(start[1], end[1]);
5941 segmentmins[2] = min(start[2], end[2]);
5942 segmentmaxs[0] = max(start[0], end[0]);
5943 segmentmaxs[1] = max(start[1], end[1]);
5944 segmentmaxs[2] = max(start[2], end[2]);
5945 nodenum = node->back;
5948 // start end start end
5949 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5950 nodenum = node->back;
5953 // START end start end
5954 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5955 VectorLerp(start, frontfrac, end, clipped[1]);
5956 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5957 nodenum = node->back;
5960 // start END start end
5961 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5962 VectorLerp(start, frontfrac, end, clipped[1]);
5963 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5964 nodenum = node->back;
5967 // START END start end
5968 nodenum = node->back;
5973 if (!model->collision_bih.leafs)
5975 leaf = model->collision_bih.leafs + (-1-nodenum);
5977 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
5984 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5985 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
5988 // collision triangle
5989 if (!mod_q3bsp_curves_collisions.integer)
5991 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
5992 texture = model->data_textures + leaf->textureindex;
5993 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);
5997 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
5998 texture = model->data_textures + leaf->textureindex;
5999 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);
6006 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)
6008 const bih_leaf_t *leaf;
6009 const bih_node_t *node;
6010 const colbrushf_t *brush;
6012 const texture_t *texture;
6014 while (nodenum >= 0)
6016 node = model->collision_bih.nodes + nodenum;
6017 axis = node->type - BIH_SPLITX;
6020 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6023 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6024 nodenum = node->back;
6027 if (segmentmins[axis] <= node->backmax)
6029 if (segmentmaxs[axis] >= node->frontmin)
6030 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6031 nodenum = node->back;
6033 else if (segmentmaxs[axis] >= node->frontmin)
6034 nodenum = node->front;
6036 return; // trace falls between children
6038 if (!model->collision_bih.leafs)
6040 leaf = model->collision_bih.leafs + (-1-nodenum);
6042 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6049 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6050 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6053 // collision triangle
6054 if (!mod_q3bsp_curves_collisions.integer)
6056 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6057 texture = model->data_textures + leaf->textureindex;
6058 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);
6062 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6063 texture = model->data_textures + leaf->textureindex;
6064 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);
6071 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)
6073 memset(trace, 0, sizeof(*trace));
6074 trace->fraction = 1;
6075 trace->realfraction = 1;
6076 trace->hitsupercontentsmask = hitsupercontentsmask;
6077 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6080 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)
6082 if (VectorCompare(start, end))
6084 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6088 memset(trace, 0, sizeof(*trace));
6089 trace->fraction = 1;
6090 trace->realfraction = 1;
6091 trace->hitsupercontentsmask = hitsupercontentsmask;
6092 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6095 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)
6097 float segmentmins[3], segmentmaxs[3];
6098 colboxbrushf_t thisbrush_start, thisbrush_end;
6099 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6101 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6103 vec3_t shiftstart, shiftend;
6104 VectorAdd(start, boxmins, shiftstart);
6105 VectorAdd(end, boxmins, shiftend);
6106 if (VectorCompare(start, end))
6107 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6110 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6111 VectorSubtract(trace->endpos, boxmins, trace->endpos);
6116 // box trace, performed as brush trace
6117 memset(trace, 0, sizeof(*trace));
6118 trace->fraction = 1;
6119 trace->realfraction = 1;
6120 trace->hitsupercontentsmask = hitsupercontentsmask;
6121 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6122 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6123 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6124 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6125 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6126 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6127 VectorAdd(start, boxmins, boxstartmins);
6128 VectorAdd(start, boxmaxs, boxstartmaxs);
6129 VectorAdd(end, boxmins, boxendmins);
6130 VectorAdd(end, boxmaxs, boxendmaxs);
6131 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6132 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6133 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6136 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6139 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6140 return trace.startsupercontents;
6143 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)
6146 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6148 int hitsupercontents;
6149 VectorSet(end, start[0], start[1], model->normalmins[2]);
6151 memset(trace, 0, sizeof(*trace));
6152 trace->fraction = 1;
6153 trace->realfraction = 1;
6154 trace->hitsupercontentsmask = hitsupercontentsmask;
6156 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6157 hitsupercontents = trace->hitsupercontents;
6158 memset(trace, 0, sizeof(*trace));
6159 trace->fraction = 1;
6160 trace->realfraction = 1;
6161 trace->hitsupercontentsmask = hitsupercontentsmask;
6162 trace->startsupercontents = hitsupercontents;
6166 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6169 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6172 VectorSet(end, start[0], start[1], model->normalmins[2]);
6173 memset(&trace, 0, sizeof(trace));
6175 trace.realfraction = 1;
6176 trace.hitsupercontentsmask = 0;
6177 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(&trace, model, model->collision_bih.rootnode, start, end, start, end);
6178 return trace.hitsupercontents;
6184 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6189 // find which leaf the point is in
6191 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6192 // point trace the brushes
6193 leaf = (mleaf_t *)node;
6194 for (i = 0;i < leaf->numleafbrushes;i++)
6196 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6197 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6199 brush->markframe = markframe;
6200 Collision_TracePointBrushFloat(trace, point, brush);
6203 // can't do point traces on curves (they have no thickness)
6206 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)
6208 int i, startside, endside;
6209 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6211 msurface_t *surface;
6214 // walk the tree until we hit a leaf, recursing for any split cases
6217 // abort if this part of the bsp tree can not be hit by this trace
6218 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6220 plane = node->plane;
6221 // axial planes are much more common than non-axial, so an optimized
6222 // axial case pays off here
6223 if (plane->type < 3)
6225 dist1 = start[plane->type] - plane->dist;
6226 dist2 = end[plane->type] - plane->dist;
6230 dist1 = DotProduct(start, plane->normal) - plane->dist;
6231 dist2 = DotProduct(end, plane->normal) - plane->dist;
6233 startside = dist1 < 0;
6234 endside = dist2 < 0;
6235 if (startside == endside)
6237 // most of the time the line fragment is on one side of the plane
6238 node = node->children[startside];
6242 // line crosses node plane, split the line
6243 dist1 = PlaneDiff(linestart, plane);
6244 dist2 = PlaneDiff(lineend, plane);
6245 midfrac = dist1 / (dist1 - dist2);
6246 VectorLerp(linestart, midfrac, lineend, mid);
6247 // take the near side first
6248 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6249 // if we found an impact on the front side, don't waste time
6250 // exploring the far side
6251 if (midfrac <= trace->realfraction)
6252 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6256 // abort if this part of the bsp tree can not be hit by this trace
6257 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6260 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6261 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6262 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6263 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6264 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6265 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6266 // line trace the brushes
6267 leaf = (mleaf_t *)node;
6268 for (i = 0;i < leaf->numleafbrushes;i++)
6270 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6271 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6273 brush->markframe = markframe;
6274 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6277 // can't do point traces on curves (they have no thickness)
6278 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6280 // line trace the curves
6281 for (i = 0;i < leaf->numleafsurfaces;i++)
6283 surface = model->data_surfaces + leaf->firstleafsurface[i];
6284 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6286 surface->deprecatedq3collisionmarkframe = markframe;
6287 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);
6293 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)
6299 msurface_t *surface;
6301 float nodesegmentmins[3], nodesegmentmaxs[3];
6302 // walk the tree until we hit a leaf, recursing for any split cases
6305 // abort if this part of the bsp tree can not be hit by this trace
6306 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6308 plane = node->plane;
6309 // axial planes are much more common than non-axial, so an optimized
6310 // axial case pays off here
6311 if (plane->type < 3)
6313 // this is an axial plane, compare bounding box directly to it and
6314 // recurse sides accordingly
6315 // recurse down node sides
6316 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6317 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6318 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6319 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6323 // this is a non-axial plane, so check if the start and end boxes
6324 // are both on one side of the plane to handle 'diagonal' cases
6325 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6329 // segment crosses plane
6330 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6333 // if sides == 0 then the trace itself is bogus (Not A Number values),
6334 // in this case we simply pretend the trace hit nothing
6336 return; // ERROR: NAN bounding box!
6337 // take whichever side the segment box is on
6338 node = node->children[sides - 1];
6340 // abort if this part of the bsp tree can not be hit by this trace
6341 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6343 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6344 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6345 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6346 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6347 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6348 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6350 leaf = (mleaf_t *)node;
6351 for (i = 0;i < leaf->numleafbrushes;i++)
6353 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6354 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6356 brush->markframe = markframe;
6357 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6360 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6362 for (i = 0;i < leaf->numleafsurfaces;i++)
6364 surface = model->data_surfaces + leaf->firstleafsurface[i];
6365 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6367 surface->deprecatedq3collisionmarkframe = markframe;
6368 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);
6375 static int markframe = 0;
6377 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)
6381 memset(trace, 0, sizeof(*trace));
6382 trace->fraction = 1;
6383 trace->realfraction = 1;
6384 trace->hitsupercontentsmask = hitsupercontentsmask;
6385 if (mod_collision_bih.integer)
6386 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6387 else if (model->brush.submodel)
6389 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6390 if (brush->colbrushf)
6391 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6394 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6397 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)
6400 float segmentmins[3], segmentmaxs[3];
6401 msurface_t *surface;
6404 if (VectorCompare(start, end))
6406 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6410 memset(trace, 0, sizeof(*trace));
6411 trace->fraction = 1;
6412 trace->realfraction = 1;
6413 trace->hitsupercontentsmask = hitsupercontentsmask;
6414 segmentmins[0] = min(start[0], end[0]) - 1;
6415 segmentmins[1] = min(start[1], end[1]) - 1;
6416 segmentmins[2] = min(start[2], end[2]) - 1;
6417 segmentmaxs[0] = max(start[0], end[0]) + 1;
6418 segmentmaxs[1] = max(start[1], end[1]) + 1;
6419 segmentmaxs[2] = max(start[2], end[2]) + 1;
6420 if (mod_collision_bih.integer)
6421 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6422 else if (model->brush.submodel)
6424 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6425 if (brush->colbrushf)
6426 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6427 if (mod_q3bsp_curves_collisions.integer)
6428 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6429 if (surface->num_collisiontriangles)
6430 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);
6433 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6436 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)
6439 float segmentmins[3], segmentmaxs[3];
6440 msurface_t *surface;
6442 colboxbrushf_t thisbrush_start, thisbrush_end;
6443 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6445 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6447 vec3_t shiftstart, shiftend;
6448 VectorAdd(start, boxmins, shiftstart);
6449 VectorAdd(end, boxmins, shiftend);
6450 if (VectorCompare(start, end))
6451 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6454 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6455 VectorSubtract(trace->endpos, boxmins, trace->endpos);
6460 // box trace, performed as brush trace
6461 memset(trace, 0, sizeof(*trace));
6462 trace->fraction = 1;
6463 trace->realfraction = 1;
6464 trace->hitsupercontentsmask = hitsupercontentsmask;
6465 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6466 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6467 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6468 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6469 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6470 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6471 VectorAdd(start, boxmins, boxstartmins);
6472 VectorAdd(start, boxmaxs, boxstartmaxs);
6473 VectorAdd(end, boxmins, boxendmins);
6474 VectorAdd(end, boxmaxs, boxendmaxs);
6475 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6476 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6477 if (mod_collision_bih.integer)
6478 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6479 else if (model->brush.submodel)
6481 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6482 if (brush->colbrushf)
6483 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, brush->colbrushf, brush->colbrushf);
6484 if (mod_q3bsp_curves_collisions.integer)
6485 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6486 if (surface->num_collisiontriangles)
6487 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);
6490 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, &thisbrush_start.brush, &thisbrush_end.brush, ++markframe, segmentmins, segmentmaxs);
6493 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6496 int supercontents = 0;
6498 if (mod_collision_bih.integer)
6501 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6502 supercontents = trace.startsupercontents;
6504 // test if the point is inside each brush
6505 else if (model->brush.submodel)
6507 // submodels are effectively one leaf
6508 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6509 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6510 supercontents |= brush->colbrushf->supercontents;
6514 mnode_t *node = model->brush.data_nodes;
6516 // find which leaf the point is in
6518 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6519 leaf = (mleaf_t *)node;
6520 // now check the brushes in the leaf
6521 for (i = 0;i < leaf->numleafbrushes;i++)
6523 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6524 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6525 supercontents |= brush->colbrushf->supercontents;
6528 return supercontents;
6531 void Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces)
6539 int nummodelbrushes = model->nummodelbrushes;
6540 int nummodelsurfaces = model->nummodelsurfaces;
6542 const int *collisionelement3i;
6543 const float *collisionvertex3f;
6544 const int *renderelement3i;
6545 const float *rendervertex3f;
6546 bih_leaf_t *bihleafs;
6547 bih_node_t *bihnodes;
6549 int *temp_leafsortscratch;
6550 const msurface_t *surface;
6551 const q3mbrush_t *brush;
6553 // find out how many BIH leaf nodes we need
6555 if (userendersurfaces)
6557 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6558 bihnumleafs += surface->num_triangles;
6562 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6563 if (brush->colbrushf)
6565 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6566 bihnumleafs += surface->num_collisiontriangles;
6572 // allocate the memory for the BIH leaf nodes
6573 bihleafs = Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6575 // now populate the BIH leaf nodes
6577 if (userendersurfaces)
6579 // add render surfaces
6580 renderelement3i = model->surfmesh.data_element3i;
6581 rendervertex3f = model->surfmesh.data_vertex3f;
6582 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6584 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6586 bihleafs[bihleafindex].type = BIH_LEAF + 2;
6587 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6588 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6589 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6590 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6591 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6592 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6593 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6594 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6601 // add collision brushes
6602 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6604 if (!brush->colbrushf)
6606 bihleafs[bihleafindex].type = BIH_LEAF;
6607 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6608 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6609 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6610 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6614 // add collision surfaces
6615 collisionelement3i = model->brush.data_collisionelement3i;
6616 collisionvertex3f = model->brush.data_collisionvertex3f;
6617 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6619 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6621 bihleafs[bihleafindex].type = BIH_LEAF + 1;
6622 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6623 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6624 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6625 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6626 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6627 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6628 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6629 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6635 // allocate buffers for the produced and temporary data
6636 bihmaxnodes = bihnumleafs - 1;
6637 bihnodes = Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6638 temp_leafsort = Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6639 temp_leafsortscratch = temp_leafsort + bihnumleafs;
6642 BIH_Build(&model->collision_bih, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6644 // we're done with the temporary data
6645 Mem_Free(temp_leafsort);
6647 // resize the BIH nodes array if it over-allocated
6648 if (model->collision_bih.maxnodes > model->collision_bih.numnodes)
6650 model->collision_bih.maxnodes = model->collision_bih.numnodes;
6651 model->collision_bih.nodes = Mem_Realloc(loadmodel->mempool, model->collision_bih.nodes, model->collision_bih.numnodes * sizeof(bih_node_t));
6655 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6657 int supercontents = 0;
6658 if (nativecontents & CONTENTSQ3_SOLID)
6659 supercontents |= SUPERCONTENTS_SOLID;
6660 if (nativecontents & CONTENTSQ3_WATER)
6661 supercontents |= SUPERCONTENTS_WATER;
6662 if (nativecontents & CONTENTSQ3_SLIME)
6663 supercontents |= SUPERCONTENTS_SLIME;
6664 if (nativecontents & CONTENTSQ3_LAVA)
6665 supercontents |= SUPERCONTENTS_LAVA;
6666 if (nativecontents & CONTENTSQ3_BODY)
6667 supercontents |= SUPERCONTENTS_BODY;
6668 if (nativecontents & CONTENTSQ3_CORPSE)
6669 supercontents |= SUPERCONTENTS_CORPSE;
6670 if (nativecontents & CONTENTSQ3_NODROP)
6671 supercontents |= SUPERCONTENTS_NODROP;
6672 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6673 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6674 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6675 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6676 if (nativecontents & CONTENTSQ3_DONOTENTER)
6677 supercontents |= SUPERCONTENTS_DONOTENTER;
6678 if (nativecontents & CONTENTSQ3_BOTCLIP)
6679 supercontents |= SUPERCONTENTS_BOTCLIP;
6680 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6681 supercontents |= SUPERCONTENTS_OPAQUE;
6682 return supercontents;
6685 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6687 int nativecontents = 0;
6688 if (supercontents & SUPERCONTENTS_SOLID)
6689 nativecontents |= CONTENTSQ3_SOLID;
6690 if (supercontents & SUPERCONTENTS_WATER)
6691 nativecontents |= CONTENTSQ3_WATER;
6692 if (supercontents & SUPERCONTENTS_SLIME)
6693 nativecontents |= CONTENTSQ3_SLIME;
6694 if (supercontents & SUPERCONTENTS_LAVA)
6695 nativecontents |= CONTENTSQ3_LAVA;
6696 if (supercontents & SUPERCONTENTS_BODY)
6697 nativecontents |= CONTENTSQ3_BODY;
6698 if (supercontents & SUPERCONTENTS_CORPSE)
6699 nativecontents |= CONTENTSQ3_CORPSE;
6700 if (supercontents & SUPERCONTENTS_NODROP)
6701 nativecontents |= CONTENTSQ3_NODROP;
6702 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6703 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6704 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6705 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6706 if (supercontents & SUPERCONTENTS_DONOTENTER)
6707 nativecontents |= CONTENTSQ3_DONOTENTER;
6708 if (supercontents & SUPERCONTENTS_BOTCLIP)
6709 nativecontents |= CONTENTSQ3_BOTCLIP;
6710 if (!(supercontents & SUPERCONTENTS_OPAQUE))
6711 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6712 return nativecontents;
6715 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6720 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6721 node = node->children[1];
6723 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6724 if (loadmodel->brush.num_leafs < numleafs)
6725 loadmodel->brush.num_leafs = numleafs;
6728 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6730 int i, j, numshadowmeshtriangles, lumps;
6731 q3dheader_t *header;
6732 float corner[3], yawradius, modelradius;
6733 msurface_t *surface;
6735 mod->modeldatatypestring = "Q3BSP";
6737 mod->type = mod_brushq3;
6738 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6741 header = (q3dheader_t *)buffer;
6742 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6743 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6745 i = LittleLong(header->version);
6746 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
6747 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
6749 mod->soundfromcenter = true;
6750 mod->TraceBox = Mod_Q3BSP_TraceBox;
6751 mod->TraceLine = Mod_Q3BSP_TraceLine;
6752 mod->TracePoint = Mod_Q3BSP_TracePoint;
6753 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
6754 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
6755 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
6756 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
6757 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
6758 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
6759 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
6760 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
6761 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
6762 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
6763 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
6764 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
6765 mod->brush.AmbientSoundLevelsForPoint = NULL;
6766 mod->brush.RoundUpToHullSize = NULL;
6767 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
6768 mod->Draw = R_Q1BSP_Draw;
6769 mod->DrawDepth = R_Q1BSP_DrawDepth;
6770 mod->DrawDebug = R_Q1BSP_DrawDebug;
6771 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
6772 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
6773 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
6774 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
6775 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
6776 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
6777 mod->DrawLight = R_Q1BSP_DrawLight;
6779 mod_base = (unsigned char *)header;
6781 // swap all the lumps
6782 header->ident = LittleLong(header->ident);
6783 header->version = LittleLong(header->version);
6784 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
6785 for (i = 0;i < lumps;i++)
6787 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
6788 if((char *) bufferend < (char *) buffer + j)
6789 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
6790 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
6791 if((char *) bufferend < (char *) buffer + j)
6792 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
6795 * NO, do NOT clear them!
6796 * they contain actual data referenced by other stuff.
6797 * Instead, before using the advertisements lump, check header->versio
6799 * Sorry, but otherwise it breaks memory of the first lump.
6800 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
6802 header->lumps[i].fileofs = 0;
6803 header->lumps[i].filelen = 0;
6807 mod->brush.qw_md4sum = 0;
6808 mod->brush.qw_md4sum2 = 0;
6809 for (i = 0;i < lumps;i++)
6811 if (i == Q3LUMP_ENTITIES)
6813 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
6814 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
6816 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
6818 // all this checksumming can take a while, so let's send keepalives here too
6819 CL_KeepaliveMessage(false);
6822 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
6823 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
6824 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
6825 if (header->version == Q3BSPVERSION_IG)
6826 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
6828 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
6829 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
6830 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
6831 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
6832 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
6833 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
6834 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
6835 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
6836 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
6837 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
6838 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
6839 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
6840 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
6841 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
6842 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
6844 // the MakePortals code works fine on the q3bsp data as well
6845 Mod_Q1BSP_MakePortals();
6847 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
6848 loadmodel->brush.supportwateralpha = true;
6850 // make a single combined shadow mesh to allow optimized shadow volume creation
6851 numshadowmeshtriangles = 0;
6852 if (cls.state != ca_dedicated)
6854 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
6856 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
6857 numshadowmeshtriangles += surface->num_triangles;
6859 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
6860 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
6861 if (surface->num_triangles > 0)
6862 Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, loadmodel->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
6863 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true, false);
6864 if (loadmodel->brush.shadowmesh)
6865 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
6868 loadmodel->brush.num_leafs = 0;
6869 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
6871 if (loadmodel->brush.numsubmodels)
6872 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
6875 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
6880 // duplicate the basic information
6881 dpsnprintf(name, sizeof(name), "*%i", i);
6882 mod = Mod_FindName(name, loadmodel->name);
6883 // copy the base model to this one
6885 // rename the clone back to its proper name
6886 strlcpy(mod->name, name, sizeof(mod->name));
6887 mod->brush.parentmodel = loadmodel;
6888 // textures and memory belong to the main model
6889 mod->texturepool = NULL;
6890 mod->mempool = NULL;
6891 mod->brush.GetPVS = NULL;
6892 mod->brush.FatPVS = NULL;
6893 mod->brush.BoxTouchingPVS = NULL;
6894 mod->brush.BoxTouchingLeafPVS = NULL;
6895 mod->brush.BoxTouchingVisibleLeafs = NULL;
6896 mod->brush.FindBoxClusters = NULL;
6897 mod->brush.LightPoint = NULL;
6898 mod->brush.AmbientSoundLevelsForPoint = NULL;
6900 mod->brush.submodel = i;
6901 if (loadmodel->brush.submodels)
6902 loadmodel->brush.submodels[i] = mod;
6904 // make the model surface list (used by shadowing/lighting)
6905 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
6906 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
6907 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
6908 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
6909 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
6910 Mod_MakeSortedSurfaces(mod);
6912 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
6913 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
6914 // enlarge the bounding box to enclose all geometry of this model,
6915 // because q3map2 sometimes lies (mostly to affect the lightgrid),
6916 // which can in turn mess up the farclip (as well as culling when
6917 // outside the level - an unimportant concern)
6919 //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]);
6920 for (j = 0;j < mod->nummodelsurfaces;j++)
6922 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
6923 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
6925 if (!surface->num_vertices)
6927 for (k = 0;k < surface->num_vertices;k++, v += 3)
6929 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
6930 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
6931 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
6932 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
6933 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
6934 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
6937 //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]);
6938 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
6939 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
6940 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
6941 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
6942 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
6943 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
6944 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
6945 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
6946 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
6947 mod->yawmins[2] = mod->normalmins[2];
6948 mod->yawmaxs[2] = mod->normalmaxs[2];
6949 mod->radius = modelradius;
6950 mod->radius2 = modelradius * modelradius;
6952 // this gets altered below if sky or water is used
6953 mod->DrawSky = NULL;
6954 mod->DrawAddWaterPlanes = NULL;
6956 for (j = 0;j < mod->nummodelsurfaces;j++)
6957 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
6959 if (j < mod->nummodelsurfaces)
6960 mod->DrawSky = R_Q1BSP_DrawSky;
6962 for (j = 0;j < mod->nummodelsurfaces;j++)
6963 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION))
6965 if (j < mod->nummodelsurfaces)
6966 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
6968 Mod_MakeCollisionBIH(mod, false);
6970 // generate VBOs and other shared data before cloning submodels
6975 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);
6978 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6980 int i = LittleLong(((int *)buffer)[1]);
6981 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
6982 Mod_Q3BSP_Load(mod,buffer, bufferend);
6983 else if (i == Q2BSPVERSION)
6984 Mod_Q2BSP_Load(mod,buffer, bufferend);
6986 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
6989 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6991 Host_Error("Mod_MAP_Load: not yet implemented");
6997 typedef struct objvertex_s
7007 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7009 const char *textbase = (char *)buffer, *text = textbase;
7013 char materialname[MAX_QPATH];
7014 int i, j, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, numsurfaces, surfacevertices, surfacetriangles, surfaceelements;
7015 int index1, index2, index3;
7016 objvertex_t vfirst, vprev, vcurrent;
7019 int numtriangles = 0;
7020 int maxtriangles = 0;
7021 objvertex_t *vertices = NULL;
7023 int maxtextures = 0, numtextures = 0, textureindex = 0;
7024 int maxv = 0, numv = 1;
7025 int maxvt = 0, numvt = 1;
7026 int maxvn = 0, numvn = 1;
7027 char *texturenames = NULL;
7028 float dist, modelradius, modelyawradius;
7034 objvertex_t *thisvertex = NULL;
7035 int vertexhashindex;
7036 int *vertexhashtable = NULL;
7037 objvertex_t *vertexhashdata = NULL;
7038 objvertex_t *vdata = NULL;
7039 int vertexhashsize = 0;
7040 int vertexhashcount = 0;
7041 skinfile_t *skinfiles = NULL;
7042 unsigned char *data = NULL;
7044 memset(&vfirst, 0, sizeof(vfirst));
7045 memset(&vprev, 0, sizeof(vprev));
7046 memset(&vcurrent, 0, sizeof(vcurrent));
7048 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7050 loadmodel->modeldatatypestring = "OBJ";
7052 loadmodel->type = mod_obj;
7053 loadmodel->soundfromcenter = true;
7054 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7055 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7056 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7057 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7058 loadmodel->brush.TraceLineOfSight = NULL;
7059 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7060 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7061 loadmodel->brush.GetPVS = NULL;
7062 loadmodel->brush.FatPVS = NULL;
7063 loadmodel->brush.BoxTouchingPVS = NULL;
7064 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7065 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7066 loadmodel->brush.FindBoxClusters = NULL;
7067 loadmodel->brush.LightPoint = NULL;
7068 loadmodel->brush.FindNonSolidLocation = NULL;
7069 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7070 loadmodel->brush.RoundUpToHullSize = NULL;
7071 loadmodel->brush.PointInLeaf = NULL;
7072 loadmodel->Draw = R_Q1BSP_Draw;
7073 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7074 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7075 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7076 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7077 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7078 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7079 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7080 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7081 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7083 skinfiles = Mod_LoadSkinFiles();
7084 if (loadmodel->numskins < 1)
7085 loadmodel->numskins = 1;
7087 // make skinscenes for the skins (no groups)
7088 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7089 for (i = 0;i < loadmodel->numskins;i++)
7091 loadmodel->skinscenes[i].firstframe = i;
7092 loadmodel->skinscenes[i].framecount = 1;
7093 loadmodel->skinscenes[i].loop = true;
7094 loadmodel->skinscenes[i].framerate = 10;
7100 // parse the OBJ text now
7107 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7108 line[linelen] = text[linelen];
7110 for (argc = 0;argc < 4;argc++)
7114 while (*s == ' ' || *s == '\t')
7124 while (*s == ' ' || *s == '\t')
7134 if (argv[0][0] == '#')
7136 if (!strcmp(argv[0], "v"))
7140 maxv = max(maxv * 2, 1024);
7141 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7143 v[numv*3+0] = atof(argv[1]);
7144 v[numv*3+2] = atof(argv[2]);
7145 v[numv*3+1] = atof(argv[3]);
7148 else if (!strcmp(argv[0], "vt"))
7152 maxvt = max(maxvt * 2, 1024);
7153 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7155 vt[numvt*2+0] = atof(argv[1]);
7156 vt[numvt*2+1] = 1-atof(argv[2]);
7159 else if (!strcmp(argv[0], "vn"))
7163 maxvn = max(maxvn * 2, 1024);
7164 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7166 vn[numvn*3+0] = atof(argv[1]);
7167 vn[numvn*3+2] = atof(argv[2]);
7168 vn[numvn*3+1] = atof(argv[3]);
7171 else if (!strcmp(argv[0], "f"))
7175 if (maxtextures <= numtextures)
7177 maxtextures = max(maxtextures * 2, 256);
7178 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7180 textureindex = numtextures++;
7181 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7183 for (j = 1;j < argc;j++)
7185 index1 = atoi(argv[j]);
7186 while(argv[j][0] && argv[j][0] != '/')
7190 index2 = atoi(argv[j]);
7191 while(argv[j][0] && argv[j][0] != '/')
7195 index3 = atoi(argv[j]);
7196 // negative refers to a recent vertex
7197 // zero means not specified
7198 // positive means an absolute vertex index
7200 index1 = numv - index1;
7202 index2 = numvt - index2;
7204 index3 = numvn - index3;
7205 vcurrent.nextindex = -1;
7206 vcurrent.textureindex = textureindex;
7207 VectorCopy(v + 3*index1, vcurrent.v);
7208 Vector2Copy(vt + 2*index2, vcurrent.vt);
7209 VectorCopy(vn + 3*index3, vcurrent.vn);
7210 if (numtriangles == 0)
7212 VectorCopy(vcurrent.v, mins);
7213 VectorCopy(vcurrent.v, maxs);
7217 mins[0] = min(mins[0], vcurrent.v[0]);
7218 mins[1] = min(mins[1], vcurrent.v[1]);
7219 mins[2] = min(mins[2], vcurrent.v[2]);
7220 maxs[0] = max(maxs[0], vcurrent.v[0]);
7221 maxs[1] = max(maxs[1], vcurrent.v[1]);
7222 maxs[2] = max(maxs[2], vcurrent.v[2]);
7228 if (maxtriangles <= numtriangles)
7230 maxtriangles = max(maxtriangles * 2, 32768);
7231 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7233 vertices[numtriangles*3+0] = vfirst;
7234 vertices[numtriangles*3+1] = vprev;
7235 vertices[numtriangles*3+2] = vcurrent;
7241 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7243 else if (!strcmp(argv[0], "usemtl"))
7245 for (i = 0;i < numtextures;i++)
7246 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7248 if (i < numtextures)
7252 if (maxtextures <= numtextures)
7254 maxtextures = max(maxtextures * 2, 256);
7255 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7257 textureindex = numtextures++;
7258 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7263 // now that we have the OBJ data loaded as-is, we can convert it
7265 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7266 VectorCopy(mins, loadmodel->normalmins);
7267 VectorCopy(maxs, loadmodel->normalmaxs);
7268 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7269 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7270 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7271 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7272 modelradius = modelyawradius + modelradius * modelradius;
7273 modelyawradius = sqrt(modelyawradius);
7274 modelradius = sqrt(modelradius);
7275 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7276 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7277 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7278 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7279 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7280 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7281 loadmodel->radius = modelradius;
7282 loadmodel->radius2 = modelradius * modelradius;
7284 // allocate storage for triangles
7285 loadmodel->num_surfaces = loadmodel->nummodelsurfaces = numsurfaces = numtextures;
7286 loadmodel->surfmesh.data_element3i = Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7287 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t));
7288 // allocate vertex hash structures to build an optimal vertex subset
7289 vertexhashsize = numtriangles*2;
7290 vertexhashtable = Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7291 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7292 vertexhashdata = Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7293 vertexhashcount = 0;
7295 // gather surface stats for assigning vertex/triangle ranges
7299 for (textureindex = 0;textureindex < numtextures;textureindex++)
7301 msurface_t *surface = loadmodel->data_surfaces + textureindex;
7302 // copy the mins/maxs of the model backwards so that the first vertex
7303 // added will set the surface bounds to a point
7304 VectorCopy(loadmodel->normalmaxs, surface->mins);
7305 VectorCopy(loadmodel->normalmins, surface->maxs);
7306 surfacevertices = 0;
7307 surfaceelements = 0;
7308 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7310 thisvertex = vertices + vertexindex;
7311 if (thisvertex->textureindex != textureindex)
7313 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7314 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7315 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7316 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7317 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7318 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7319 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7320 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7322 vdata = vertexhashdata + i;
7323 if (vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7328 i = vertexhashcount++;
7329 vdata = vertexhashdata + i;
7330 *vdata = *thisvertex;
7331 vdata->nextindex = vertexhashtable[vertexhashindex];
7332 vertexhashtable[vertexhashindex] = i;
7335 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7338 surfacetriangles = surfaceelements / 3;
7339 surface->num_vertices = surfacevertices;
7340 surface->num_triangles = surfacetriangles;
7341 surface->num_firstvertex = firstvertex;
7342 surface->num_firsttriangle = firsttriangle;
7343 firstvertex += surface->num_vertices;
7344 firsttriangle += surface->num_triangles;
7346 numvertices = firstvertex;
7348 // allocate storage for final mesh data
7349 loadmodel->num_textures = numtextures * loadmodel->numskins;
7350 loadmodel->num_texturesperskin = numtextures;
7351 data = (unsigned char *)Mem_Alloc(loadmodel->mempool, numsurfaces * sizeof(int) + numsurfaces * loadmodel->numskins * sizeof(texture_t) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0) + numvertices * sizeof(float[14]));
7352 loadmodel->sortedmodelsurfaces = (int *)data;data += numsurfaces * sizeof(int);
7353 loadmodel->data_textures = (texture_t *)data;data += numsurfaces * loadmodel->numskins * sizeof(texture_t);
7354 loadmodel->surfmesh.num_vertices = numvertices;
7355 loadmodel->surfmesh.num_triangles = numtriangles;
7356 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7357 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7358 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7359 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7360 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7361 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7362 if (loadmodel->surfmesh.num_vertices <= 65536)
7363 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7365 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7367 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7368 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7369 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7372 // load the textures
7373 for (textureindex = 0;textureindex < numtextures;textureindex++)
7374 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7375 Mod_FreeSkinFiles(skinfiles);
7377 // set the surface textures
7378 for (textureindex = 0;textureindex < numtextures;textureindex++)
7380 msurface_t *surface = loadmodel->data_surfaces + textureindex;
7381 surface->texture = loadmodel->data_textures + textureindex;
7386 Mem_Free(texturenames);
7390 Mem_Free(vertexhashtable);
7391 Mem_Free(vertexhashdata);
7393 // compute all the mesh information that was not loaded from the file
7394 Mod_MakeSortedSurfaces(loadmodel);
7395 if (loadmodel->surfmesh.data_element3s)
7396 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7397 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7398 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7399 // generate normals if the file did not have them
7400 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7401 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
7402 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);
7403 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7405 Mod_MakeCollisionBIH(loadmodel, true);
7420 typedef struct objvertex_s
7428 typedef struct objtriangle_s
7430 objvertex_t vertex[3];
7432 // these fields are used only in conversion to surfaces
7435 int surfacevertexindex[3];
7436 float edgeplane[3][4];
7442 struct objnode_s *children[2];
7443 struct objnode_s *parent;
7444 objtriangle_t *triangles;
7453 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)
7459 float bestnormal[3];
7464 int numfronttriangles;
7465 int numbacktriangles;
7470 float outfrontpoints[5][3];
7471 float outbackpoints[5][3];
7472 int neededfrontpoints;
7473 int neededbackpoints;
7477 node = (objnode_t *)Mem_ExpandableArray_AllocRecord(array);
7478 node->parent = parent;
7481 VectorCopy(triangles[0].vertex[0].v, mins);
7482 VectorCopy(triangles[0].vertex[0].v, maxs);
7484 else if (parent && parent->children[0] == node)
7486 VectorCopy(parent->mins, mins);
7487 Vectorcopy(parent->maxs, maxs);
7489 else if (parent && parent->children[1] == node)
7491 VectorCopy(parent->mins, mins);
7492 Vectorcopy(parent->maxs, maxs);
7499 for (i = 0;i < numtriangles;i++)
7501 for (j = 0;j < 3;j++)
7503 mins[0] = min(mins[0], triangles[i].vertex[j].v[0]);
7504 mins[1] = min(mins[1], triangles[i].vertex[j].v[1]);
7505 mins[2] = min(mins[2], triangles[i].vertex[j].v[2]);
7506 maxs[0] = max(maxs[0], triangles[i].vertex[j].v[0]);
7507 maxs[1] = max(maxs[1], triangles[i].vertex[j].v[1]);
7508 maxs[2] = max(maxs[2], triangles[i].vertex[j].v[2]);
7511 VectorCopy(mins, node->mins);
7512 VectorCopy(maxs, node->maxs);
7513 if (numtriangles <= mod_obj_leaftriangles.integer)
7516 loadmodel->brush.num_leafs++;
7517 node->triangles = triangles;
7518 node->numtriangles = numtriangles;
7523 loadmodel->brush.num_nodes++;
7524 // pick a splitting plane from the various choices available to us...
7525 // early splits simply halve the interval
7527 VectorClear(bestnormal);
7529 if (numtriangles <= mod_obj_splitterlimit.integer)
7530 limit = numtriangles;
7533 for (i = -3;i < limit;i++)
7537 // first we try 3 axial splits (kdtree-like)
7539 VectorClear(normal);
7541 dist = (mins[j] + maxs[j]) * 0.5f;
7545 // then we try each triangle plane
7546 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7547 VectorNormalize(normal);
7548 dist = DotProduct(normal, triangles[i].vertex[0].v);
7549 // use positive axial values whenever possible
7550 if (normal[0] == -1)
7552 if (normal[1] == -1)
7554 if (normal[2] == -1)
7556 // skip planes that match the current best
7557 if (VectorCompare(normal, bestnormal) && dist == bestdist)
7564 for (j = 0;j < numtriangles;j++)
7566 dists[0] = DotProduct(normal, triangles[j].vertex[0].v) - dist;
7567 dists[1] = DotProduct(normal, triangles[j].vertex[1].v) - dist;
7568 dists[2] = DotProduct(normal, triangles[j].vertex[2].v) - dist;
7569 if (dists[0] < -DIST_EPSILON || dists[1] < -DIST_EPSILON || dists[2] < -DIST_EPSILON)
7571 if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7576 else if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7581 // score is supposed to:
7582 // prefer axial splits
7583 // prefer evenly dividing the input triangles
7584 // prefer triangles on the plane
7585 // avoid triangles crossing the plane
7586 score = count_on*count_on - count_both*count_both + min(count_front, count_back)*(count_front+count_back);
7587 if (normal[0] == 1 || normal[1] == 1 || normal[2] == 1)
7589 if (i == -3 || bestscore < score)
7591 VectorCopy(normal, bestnormal);
7597 // now we have chosen an optimal split plane...
7599 // divide triangles by the splitting plane
7600 numfronttriangles = 0;
7601 numbacktriangles = 0;
7602 for (i = 0;i < numtriangles;i++)
7604 neededfrontpoints = 0;
7605 neededbackpoints = 0;
7607 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);
7608 if (countonpoints > 1)
7610 // triangle lies on plane, assign it to one child only
7611 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7612 if (DotProduct(bestnormal, normal) >= 0)
7614 // assign to front side child
7615 obj_fronttriangles[numfronttriangles++] = triangles[i];
7619 // assign to back side child
7620 obj_backtriangles[numbacktriangles++] = triangles[i];
7625 // convert clipped polygons to triangles
7626 for (j = 0;j < neededfrontpoints-2;j++)
7628 obj_fronttriangles[numfronttriangles] = triangles[i];
7629 VectorCopy(outfrontpoints[0], obj_fronttriangles[numfronttriangles].vertex[0].v);
7630 VectorCopy(outfrontpoints[j+1], obj_fronttriangles[numfronttriangles].vertex[1].v);
7631 VectorCopy(outfrontpoints[j+2], obj_fronttriangles[numfronttriangles].vertex[2].v);
7632 numfronttriangles++;
7634 for (j = 0;j < neededbackpoints-2;j++)
7636 obj_backtriangles[numbacktriangles] = triangles[i];
7637 VectorCopy(outbackpoints[0], obj_backtriangles[numbacktriangles].vertex[0].v);
7638 VectorCopy(outbackpoints[j+1], obj_backtriangles[numbacktriangles].vertex[1].v);
7639 VectorCopy(outbackpoints[j+2], obj_backtriangles[numbacktriangles].vertex[2].v);
7645 // now copy the triangles out of the big buffer
7646 if (numfronttriangles)
7648 fronttriangles = Mem_Alloc(loadmodel->mempool, fronttriangles * sizeof(*fronttriangles));
7649 memcpy(fronttriangles, obj_fronttriangles, numfronttriangles * sizeof(*fronttriangles));
7652 fronttriangles = NULL;
7653 if (numbacktriangles)
7655 backtriangles = Mem_Alloc(loadmodel->mempool, backtriangles * sizeof(*backtriangles));
7656 memcpy(backtriangles, obj_backtriangles, numbacktriangles * sizeof(*backtriangles));
7659 backtriangles = NULL;
7661 // free the original triangles we were given
7663 Mem_Free(triangles);
7667 // now create the children...
7668 node->children[0] = Mod_OBJ_BSPNodeForTriangles(node, fronttriangles, numfronttriangles, frontmins, frontmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
7669 node->children[1] = Mod_OBJ_BSPNodeForTriangles(node, backtriangles, numbacktriangles, backmins, backmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
7673 void Mod_OBJ_SnapVertex(float *v)
7676 float a = mod_obj_vertexprecision.value;
7678 v[0] -= floor(v[0] * a + 0.5f) * b;
7679 v[1] -= floor(v[1] * a + 0.5f) * b;
7680 v[2] -= floor(v[2] * a + 0.5f) * b;
7683 void Mod_OBJ_ConvertBSPNode(objnode_t *objnode, mnode_t *mnodeparent)
7685 if (objnode->children[0])
7687 // convert to mnode_t
7688 mnode_t *mnode = loadmodel->brush.data_nodes + loadmodel->brush.num_nodes++;
7689 mnode->parent = mnodeparent;
7690 mnode->plane = loadmodel->brush.data_planes + loadmodel->brush.num_planes++;
7691 VectorCopy(objnode->normal, mnode->plane->normal);
7692 mnode->plane->dist = objnode->dist;
7693 PlaneClassify(mnode->plane);
7694 VectorCopy(objnode->mins, mnode->mins);
7695 VectorCopy(objnode->maxs, mnode->maxs);
7696 // push combinedsupercontents up to the parent
7698 mnodeparent->combinedsupercontents |= mnode->combinedsupercontents;
7699 mnode->children[0] = Mod_OBJ_ConvertBSPNode(objnode->children[0], mnode);
7700 mnode->children[1] = Mod_OBJ_ConvertBSPNode(objnode->children[1], mnode);
7704 // convert to mleaf_t
7705 mleaf_t *mleaf = loadmodel->brush.data_leafs + loadmodel->brush.num_leafs++;
7706 mleaf->parent = mnodeparent;
7707 VectorCopy(objnode->mins, mleaf->mins);
7708 VectorCopy(objnode->maxs, mleaf->maxs);
7709 mleaf->clusterindex = loadmodel->brush.num_leafs - 1;
7710 if (objnode->numtriangles)
7712 objtriangle_t *triangles = objnode->triangles;
7713 int numtriangles = objnode->numtriangles;
7717 objvertex_t vertex[3];
7719 maxsurfaces = numtriangles;
7721 // calculate some more data on each triangle for surface gathering
7722 for (i = 0;i < numtriangles;i++)
7724 triangle = triangles + i;
7725 texture = loadmodel->data_textures + triangle->textureindex;
7726 Mod_OBJ_SnapVertex(triangle->vertex[0].v);
7727 Mod_OBJ_SnapVertex(triangle->vertex[1].v);
7728 Mod_OBJ_SnapVertex(triangle->vertex[2].v);
7729 TriangleNormal(triangle->vertex[0].v, triangle->vertex[1].v, triangle->vertex[2].v, normal);
7731 if (fabs(normal[axis]) < fabs(normal[1]))
7733 if (fabs(normal[axis]) < fabs(normal[2]))
7735 VectorClear(normal);
7737 triangle->axis = axis;
7738 VectorSubtract(triangle->vertex[1].v, triangle->vertex[0].v, edge[0]);
7739 VectorSubtract(triangle->vertex[2].v, triangle->vertex[1].v, edge[1]);
7740 VectorSubtract(triangle->vertex[0].v, triangle->vertex[2].v, edge[2]);
7741 CrossProduct(edge[0], normal, triangle->edgeplane[0]);
7742 CrossProduct(edge[1], normal, triangle->edgeplane[1]);
7743 CrossProduct(edge[2], normal, triangle->edgeplane[2]);
7744 VectorNormalize(triangle->edgeplane[0]);
7745 VectorNormalize(triangle->edgeplane[1]);
7746 VectorNormalize(triangle->edgeplane[2]);
7747 triangle->edgeplane[0][3] = DotProduct(triangle->edgeplane[0], triangle->vertex[0].v);
7748 triangle->edgeplane[1][3] = DotProduct(triangle->edgeplane[1], triangle->vertex[1].v);
7749 triangle->edgeplane[2][3] = DotProduct(triangle->edgeplane[2], triangle->vertex[2].v);
7750 triangle->surfaceindex = 0;
7751 // add to the combined supercontents while we're here...
7752 mleaf->combinedsupercontents |= texture->supercontents;
7755 for (i = 0;i < numtriangles;i++)
7757 // skip already-assigned triangles
7758 if (triangles[i].surfaceindex)
7760 texture = loadmodel->data_textures + triangles[i].textureindex;
7761 // assign a new surface to this triangle
7762 triangles[i].surfaceindex = surfaceindex++;
7763 axis = triangles[i].axis;
7765 // find the triangle's neighbors, this can take multiple passes
7770 for (j = i+1;j < numtriangles;j++)
7772 if (triangles[j].surfaceindex || triangles[j].axis != axis || triangles[j].texture != texture)
7774 triangle = triangles + j;
7775 for (k = i;k < j;k++)
7777 if (triangles[k].surfaceindex != surfaceindex)
7779 if (VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[0].v)
7780 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[1].v)
7781 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[2].v)
7782 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[0].v)
7783 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[1].v)
7784 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[2].v)
7785 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[0].v)
7786 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[1].v)
7787 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[2].v))
7789 // shares a vertex position
7793 for (k = 0;k < numvertices;k++)
7794 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))
7796 if (k == numvertices)
7797 break; // not a neighbor
7798 // this triangle is a neighbor and has the same axis and texture
7799 // check now if it overlaps in lightmap projection space
7800 triangles[j].surfaceindex;
7804 //triangles[i].surfaceindex = surfaceindex++;
7805 for (surfaceindex = 0;surfaceindex < numsurfaces;surfaceindex++)
7807 if (surfaces[surfaceindex].texture != texture)
7809 // check if any triangles already in this surface overlap in lightmap projection space
7816 // let the collision code simply use the surfaces
7817 mleaf->containscollisionsurfaces = mleaf->combinedsupercontents != 0;
7818 mleaf->numleafsurfaces = ?;
7819 mleaf->firstleafsurface = ?;
7821 // push combinedsupercontents up to the parent
7823 mnodeparent->combinedsupercontents |= mleaf->combinedsupercontents;
7828 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7831 const char *textbase = (char *)buffer, *text = textbase;
7835 char materialname[MAX_QPATH];
7836 int j, index1, index2, index3, first, prev, index;
7839 int numtriangles = 0;
7840 int maxtriangles = 131072;
7841 objtriangle_t *triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
7843 int maxtextures = 256, numtextures = 0, textureindex = 0;
7844 int maxv = 1024, numv = 0;
7845 int maxvt = 1024, numvt = 0;
7846 int maxvn = 1024, numvn = 0;
7847 char **texturenames;
7848 float *v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
7849 float *vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
7850 float *vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
7851 objvertex_t vfirst, vprev, vcurrent;
7856 int maxverthash = 65536, numverthash = 0;
7857 int numhashindex = 65536;
7858 struct objverthash_s
7860 struct objverthash_s *next;
7866 *hash, **verthash = Mem_Alloc(tempmempool, numhashindex * sizeof(*verthash)), *verthashdata = Mem_Alloc(tempmempool, maxverthash * sizeof(*verthashdata)), *oldverthashdata;
7869 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7871 loadmodel->modeldatatypestring = "OBJ";
7873 loadmodel->type = mod_obj;
7874 loadmodel->soundfromcenter = true;
7875 loadmodel->TraceBox = Mod_OBJ_TraceBox;
7876 loadmodel->TraceLine = Mod_OBJ_TraceLine;
7877 loadmodel->TracePoint = Mod_OBJ_TracePoint;
7878 loadmodel->PointSuperContents = Mod_OBJ_PointSuperContents;
7879 loadmodel->brush.TraceLineOfSight = Mod_OBJ_TraceLineOfSight;
7880 loadmodel->brush.SuperContentsFromNativeContents = Mod_OBJ_SuperContentsFromNativeContents;
7881 loadmodel->brush.NativeContentsFromSuperContents = Mod_OBJ_NativeContentsFromSuperContents;
7882 loadmodel->brush.GetPVS = Mod_OBJ_GetPVS;
7883 loadmodel->brush.FatPVS = Mod_OBJ_FatPVS;
7884 loadmodel->brush.BoxTouchingPVS = Mod_OBJ_BoxTouchingPVS;
7885 loadmodel->brush.BoxTouchingLeafPVS = Mod_OBJ_BoxTouchingLeafPVS;
7886 loadmodel->brush.BoxTouchingVisibleLeafs = Mod_OBJ_BoxTouchingVisibleLeafs;
7887 loadmodel->brush.FindBoxClusters = Mod_OBJ_FindBoxClusters;
7888 loadmodel->brush.LightPoint = Mod_OBJ_LightPoint;
7889 loadmodel->brush.FindNonSolidLocation = Mod_OBJ_FindNonSolidLocation;
7890 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7891 loadmodel->brush.RoundUpToHullSize = NULL;
7892 loadmodel->brush.PointInLeaf = Mod_OBJ_PointInLeaf;
7893 loadmodel->Draw = R_Q1BSP_Draw;
7894 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7895 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7896 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7897 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7898 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7899 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7900 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7901 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7902 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7907 // parse the OBJ text now
7914 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7915 line[linelen] = text[linelen];
7917 for (argc = 0;argc < (int)(sizeof(argv)/sizeof(argv[0]));argc++)
7921 while (*s == ' ' || *s == '\t')
7931 while (*s == ' ' || *s == '\t')
7936 if (argv[0][0] == '#')
7938 if (!strcmp(argv[0], "v"))
7944 v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
7947 memcpy(v, oldv, numv * sizeof(float[3]));
7951 v[numv*3+0] = atof(argv[1]);
7952 v[numv*3+1] = atof(argv[2]);
7953 v[numv*3+2] = atof(argv[3]);
7956 else if (!strcmp(argv[0], "vt"))
7962 vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
7965 memcpy(vt, oldvt, numvt * sizeof(float[2]));
7969 vt[numvt*2+0] = atof(argv[1]);
7970 vt[numvt*2+1] = atof(argv[2]);
7973 else if (!strcmp(argv[0], "vn"))
7979 vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
7982 memcpy(vn, oldvn, numvn * sizeof(float[3]));
7986 vn[numvn*3+0] = atof(argv[1]);
7987 vn[numvn*3+1] = atof(argv[2]);
7988 vn[numvn*3+2] = atof(argv[3]);
7991 else if (!strcmp(argv[0], "f"))
7993 for (j = 1;j < argc;j++)
7995 index1 = atoi(argv[j]);
7996 while(argv[j][0] && argv[j][0] != '/')
8000 index2 = atoi(argv[j]);
8001 while(argv[j][0] && argv[j][0] != '/')
8005 index3 = atoi(argv[j]);
8006 // negative refers to a recent vertex
8007 // zero means not specified
8008 // positive means an absolute vertex index
8010 index1 = numv - index1;
8012 index2 = numvt - index2;
8014 index3 = numvn - index3;
8015 VectorCopy(v + 3*index1, vcurrent.v);
8016 Vector2Copy(vt + 2*index2, vcurrent.vt);
8017 VectorCopy(vn + 3*index3, vcurrent.vn);
8018 if (numtriangles == 0)
8020 VectorCopy(vcurrent.v, mins);
8021 VectorCopy(vcurrent.v, maxs);
8025 mins[0] = min(mins[0], vcurrent.v[0]);
8026 mins[1] = min(mins[1], vcurrent.v[1]);
8027 mins[2] = min(mins[2], vcurrent.v[2]);
8028 maxs[0] = max(maxs[0], vcurrent.v[0]);
8029 maxs[1] = max(maxs[1], vcurrent.v[1]);
8030 maxs[2] = max(maxs[2], vcurrent.v[2]);
8036 if (maxtriangles <= numtriangles)
8038 objtriangle_t *oldtriangles = triangles;
8040 triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8043 memcpy(triangles, oldtriangles, maxtriangles * sizeof(*triangles));
8044 Mem_Free(oldtriangles);
8047 triangles[numtriangles].textureindex = textureindex;
8048 triangles[numtriangles].vertex[0] = vfirst;
8049 triangles[numtriangles].vertex[1] = vprev;
8050 triangles[numtriangles].vertex[2] = vcurrent;
8057 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8059 else if (!!strcmp(argv[0], "usemtl"))
8061 for (i = 0;i < numtextures;i++)
8062 if (!strcmp(texturenames[numtextures], argv[1]))
8064 if (i < numtextures)
8065 texture = textures + i;
8068 if (maxtextures <= numtextures)
8070 texture_t *oldtextures = textures;
8072 textures = Mem_Alloc(tempmempool, maxtextures * sizeof(*textures));
8075 memcpy(textures, oldtextures, numtextures * sizeof(*textures));
8076 Mem_Free(oldtextures);
8079 textureindex = numtextures++;
8080 texturenames[textureindex] = Mem_Alloc(tempmempool, strlen(argv[1]) + 1);
8081 memcpy(texturenames[textureindex], argv[1], strlen(argv[1]) + 1);
8091 // now that we have the OBJ data loaded as-is, we can convert it
8093 // load the textures
8094 loadmodel->num_textures = numtextures;
8095 loadmodel->data_textures = Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
8096 for (i = 0;i < numtextures;i++)
8097 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, texturenames[i], true, true, TEXF_MIPMAP | TEXF_ALPHA | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS);
8099 // free the texturenames array since we are now done with it
8100 for (i = 0;i < numtextures;i++)
8102 Mem_Free(texturenames[i]);
8103 texturenames[i] = NULL;
8105 Mem_Free(texturenames);
8106 texturenames = NULL;
8108 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8109 VectorCopy(mins, loadmodel->normalmins);
8110 VectorCopy(maxs, loadmodel->normalmaxs);
8111 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8112 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8113 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8114 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8115 modelradius = modelyawradius + modelradius * modelradius;
8116 modelyawradius = sqrt(modelyawradius);
8117 modelradius = sqrt(modelradius);
8118 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8119 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8120 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8121 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8122 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8123 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8124 loadmodel->radius = modelradius;
8125 loadmodel->radius2 = modelradius * modelradius;
8127 // make sure the temp triangle buffer is big enough for BSP building
8128 maxclippedtriangles = numtriangles*4;
8129 if (numtriangles > 0)
8131 clippedfronttriangles = Mem_Alloc(loadmodel->mempool, maxclippedtriangles * 2 * sizeof(objtriangle_t));
8132 clippedbacktriangles = clippedfronttriangles + maxclippedtriangles;
8135 // 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
8136 loadmodel->brush.num_leafs = 0;
8137 loadmodel->brush.num_nodes = 0;
8138 Mem_ExpandableArray_NewArray(&nodesarray, loadmodel->mempool, sizeof(objnode_t), 1024);
8139 rootnode = Mod_OBJ_BSPNodeForTriangles(triangles, numtriangles, mins, maxs, &nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8141 // convert the BSP tree to mnode_t and mleaf_t structures and convert the triangles to msurface_t...
8142 loadmodel->brush.data_leafs = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8143 loadmodel->brush.data_nodes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mnode_t));
8144 loadmodel->brush.data_planes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mplane_t));
8145 loadmodel->brush.num_leafs = 0;
8146 loadmodel->brush.num_nodes = 0;
8147 loadmodel->brush.num_planes = 0;
8148 Mod_OBJ_ConvertAndFreeBSPNode(rootnode);
8150 if (clippedfronttriangles)
8151 Mem_Free(clippedfronttriangles);
8152 maxclippedtriangles = 0;
8153 clippedfronttriangles = NULL;
8154 clippedbacktriangles = NULL;
8156 --- NOTHING DONE PAST THIS POINT ---
8158 loadmodel->numskins = LittleLong(pinmodel->num_skins);
8159 numxyz = LittleLong(pinmodel->num_xyz);
8160 numst = LittleLong(pinmodel->num_st);
8161 loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->num_tris);
8162 loadmodel->numframes = LittleLong(pinmodel->num_frames);
8163 loadmodel->surfmesh.num_morphframes = loadmodel->numframes;
8164 loadmodel->num_poses = loadmodel->surfmesh.num_morphframes;
8165 skinwidth = LittleLong(pinmodel->skinwidth);
8166 skinheight = LittleLong(pinmodel->skinheight);
8167 iskinwidth = 1.0f / skinwidth;
8168 iskinheight = 1.0f / skinheight;
8170 loadmodel->num_surfaces = 1;
8171 loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
8172 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]));
8173 loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
8174 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8175 loadmodel->sortedmodelsurfaces[0] = 0;
8176 loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
8177 loadmodel->surfmesh.data_morphmd2framesize6f = (float *)data;data += loadmodel->numframes * sizeof(float[6]);
8178 loadmodel->surfmesh.data_element3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8179 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8181 loadmodel->synctype = ST_RAND;
8184 inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
8185 skinfiles = Mod_LoadSkinFiles();
8188 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8189 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8190 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8191 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
8192 Mod_FreeSkinFiles(skinfiles);
8194 else if (loadmodel->numskins)
8196 // skins found (most likely not a player model)
8197 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8198 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8199 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8200 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
8201 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i * loadmodel->num_surfaces, inskin, true, true, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP | TEXF_COMPRESS);
8205 // no skins (most likely a player model)
8206 loadmodel->numskins = 1;
8207 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8208 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8209 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8210 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
8213 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8214 for (i = 0;i < loadmodel->numskins;i++)
8216 loadmodel->skinscenes[i].firstframe = i;
8217 loadmodel->skinscenes[i].framecount = 1;
8218 loadmodel->skinscenes[i].loop = true;
8219 loadmodel->skinscenes[i].framerate = 10;
8222 // load the triangles and stvert data
8223 inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
8224 intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
8225 md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 65536 * sizeof(hash));
8226 md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->surfmesh.num_triangles * 3 * sizeof(*hash));
8227 // swap the triangle list
8228 loadmodel->surfmesh.num_vertices = 0;
8229 for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
8231 for (j = 0;j < 3;j++)
8233 xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
8234 st = (unsigned short) LittleShort (intri[i].index_st[j]);
8237 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
8242 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
8245 hashindex = (xyz * 256 + st) & 65535;
8246 for (hash = md2verthash[hashindex];hash;hash = hash->next)
8247 if (hash->xyz == xyz && hash->st == st)
8251 hash = md2verthashdata + loadmodel->surfmesh.num_vertices++;
8254 hash->next = md2verthash[hashindex];
8255 md2verthash[hashindex] = hash;
8257 loadmodel->surfmesh.data_element3i[i*3+j] = (hash - md2verthashdata);
8261 vertremap = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(int));
8262 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));
8263 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
8264 loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)data;data += loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t);
8265 for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
8268 hash = md2verthashdata + i;
8269 vertremap[i] = hash->xyz;
8270 sts = LittleShort(inst[hash->st*2+0]);
8271 stt = LittleShort(inst[hash->st*2+1]);
8272 if (sts < 0 || sts >= skinwidth || stt < 0 || stt >= skinheight)
8274 Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, sts, stt, i);
8278 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = sts * iskinwidth;
8279 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = stt * iskinheight;
8282 Mem_Free(md2verthash);
8283 Mem_Free(md2verthashdata);
8285 // generate ushort elements array if possible
8286 if (loadmodel->surfmesh.num_vertices <= 65536)
8287 loadmodel->surfmesh.data_element3s = (unsigned short *)Mem_Alloc(loadmodel->mempool, sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles);
8290 datapointer = (base + LittleLong(pinmodel->ofs_frames));
8291 for (i = 0;i < loadmodel->surfmesh.num_morphframes;i++)
8296 pinframe = (md2frame_t *)datapointer;
8297 datapointer += sizeof(md2frame_t);
8298 // store the frame scale/translate into the appropriate array
8299 for (j = 0;j < 3;j++)
8301 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+j] = LittleFloat(pinframe->scale[j]);
8302 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+3+j] = LittleFloat(pinframe->translate[j]);
8304 // convert the vertices
8305 v = (trivertx_t *)datapointer;
8306 out = loadmodel->surfmesh.data_morphmdlvertex + i * loadmodel->surfmesh.num_vertices;
8307 for (k = 0;k < loadmodel->surfmesh.num_vertices;k++)
8308 out[k] = v[vertremap[k]];
8309 datapointer += numxyz * sizeof(trivertx_t);
8311 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
8312 loadmodel->animscenes[i].firstframe = i;
8313 loadmodel->animscenes[i].framecount = 1;
8314 loadmodel->animscenes[i].framerate = 10;
8315 loadmodel->animscenes[i].loop = true;
8318 Mem_Free(vertremap);
8320 Mod_MakeSortedSurfaces(loadmodel);
8321 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8322 Mod_Alias_CalculateBoundingBox();
8323 Mod_Alias_MorphMesh_CompileFrames();
8325 surface = loadmodel->data_surfaces;
8326 surface->texture = loadmodel->data_textures;
8327 surface->num_firsttriangle = 0;
8328 surface->num_triangles = loadmodel->surfmesh.num_triangles;
8329 surface->num_firstvertex = 0;
8330 surface->num_vertices = loadmodel->surfmesh.num_vertices;
8332 loadmodel->surfmesh.isanimated = false;
8334 if (loadmodel->surfmesh.data_element3s)
8335 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8336 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8339 #endif // !OBJASMODEL
8341 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
8343 // we already have done PVS culling at this point...
8344 // so we don't need to do it again.
8347 vec3_t testorigin, mins, maxs;
8349 testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
8350 testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
8351 testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
8353 if(model->brush.TraceLineOfSight(model, eye, testorigin))
8356 // expand the box a little
8357 mins[0] = (t+1) * minsX[0] - t * maxsX[0];
8358 maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
8359 mins[1] = (t+1) * minsX[1] - t * maxsX[1];
8360 maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
8361 mins[2] = (t+1) * minsX[2] - t * maxsX[2];
8362 maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
8364 for(i = 0; i != numsamples; ++i)
8366 testorigin[0] = lhrandom(mins[0], maxs[0]);
8367 testorigin[1] = lhrandom(mins[1], maxs[1]);
8368 testorigin[2] = lhrandom(mins[2], maxs[2]);
8370 if(model->brush.TraceLineOfSight(model, eye, testorigin))