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"};
52 static texture_t mod_q1bsp_texture_solid;
53 static texture_t mod_q1bsp_texture_sky;
54 static texture_t mod_q1bsp_texture_lava;
55 static texture_t mod_q1bsp_texture_slime;
56 static texture_t mod_q1bsp_texture_water;
58 void Mod_BrushInit(void)
60 // Cvar_RegisterVariable(&r_subdivide_size);
61 Cvar_RegisterVariable(&r_novis);
62 Cvar_RegisterVariable(&r_picmipworld);
63 Cvar_RegisterVariable(&r_nosurftextures);
64 Cvar_RegisterVariable(&r_subdivisions_tolerance);
65 Cvar_RegisterVariable(&r_subdivisions_mintess);
66 Cvar_RegisterVariable(&r_subdivisions_maxtess);
67 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
68 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
69 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
70 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
71 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
72 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
73 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
74 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
75 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
76 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
77 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
78 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
79 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
80 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
81 Cvar_RegisterVariable(&mod_collision_bih);
83 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
84 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
85 mod_q1bsp_texture_solid.surfaceflags = 0;
86 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
88 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
89 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
90 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
91 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
93 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
94 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
95 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
96 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
98 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
99 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
100 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
101 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
103 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
104 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
105 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
106 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
109 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
116 // LordHavoc: modified to start at first clip node,
117 // in other words: first node of the (sub)model
118 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
120 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
122 return (mleaf_t *)node;
125 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
129 leaf = Mod_Q1BSP_PointInLeaf(model, p);
132 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
135 memcpy(out, leaf->ambient_sound_level, i);
141 memset(out, 0, outsize);
144 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
147 int nodestackindex = 0;
148 mnode_t *node, *nodestack[1024];
149 if (!model->brush.num_pvsclusters)
151 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
157 // node - recurse down the BSP tree
158 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
162 return -1; // ERROR: NAN bounding box!
163 // box is on one side of plane, take that path
164 node = node->children[sides-1];
168 // box crosses plane, take one path and remember the other
169 if (nodestackindex < 1024)
170 nodestack[nodestackindex++] = node->children[0];
171 node = node->children[1];
177 // leaf - add clusterindex to list
178 if (numclusters < maxclusters)
179 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
183 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
187 if (nodestackindex < 1024)
188 nodestack[nodestackindex++] = node->children[0];
189 node = node->children[1];
194 // leaf - add clusterindex to list
195 if (numclusters < maxclusters)
196 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
201 // try another path we didn't take earlier
202 if (nodestackindex == 0)
204 node = nodestack[--nodestackindex];
206 // return number of clusters found (even if more than the maxclusters)
210 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
212 int nodestackindex = 0;
213 mnode_t *node, *nodestack[1024];
214 if (!model->brush.num_pvsclusters)
216 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
222 // node - recurse down the BSP tree
223 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
227 return -1; // ERROR: NAN bounding box!
228 // box is on one side of plane, take that path
229 node = node->children[sides-1];
233 // box crosses plane, take one path and remember the other
234 if (nodestackindex < 1024)
235 nodestack[nodestackindex++] = node->children[0];
236 node = node->children[1];
242 // leaf - check cluster bit
243 int clusterindex = ((mleaf_t *)node)->clusterindex;
244 if (CHECKPVSBIT(pvs, clusterindex))
246 // it is visible, return immediately with the news
251 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
255 if (nodestackindex < 1024)
256 nodestack[nodestackindex++] = node->children[0];
257 node = node->children[1];
262 // leaf - check cluster bit
263 int clusterindex = ((mleaf_t *)node)->clusterindex;
264 if (CHECKPVSBIT(pvs, clusterindex))
266 // it is visible, return immediately with the news
272 // nothing to see here, try another path we didn't take earlier
273 if (nodestackindex == 0)
275 node = nodestack[--nodestackindex];
281 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
283 int nodestackindex = 0;
284 mnode_t *node, *nodestack[1024];
285 if (!model->brush.num_leafs)
287 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
293 // node - recurse down the BSP tree
294 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
298 return -1; // ERROR: NAN bounding box!
299 // box is on one side of plane, take that path
300 node = node->children[sides-1];
304 // box crosses plane, take one path and remember the other
305 if (nodestackindex < 1024)
306 nodestack[nodestackindex++] = node->children[0];
307 node = node->children[1];
313 // leaf - check cluster bit
314 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
315 if (CHECKPVSBIT(pvs, clusterindex))
317 // it is visible, return immediately with the news
322 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
326 if (nodestackindex < 1024)
327 nodestack[nodestackindex++] = node->children[0];
328 node = node->children[1];
333 // leaf - check cluster bit
334 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
335 if (CHECKPVSBIT(pvs, clusterindex))
337 // it is visible, return immediately with the news
343 // nothing to see here, try another path we didn't take earlier
344 if (nodestackindex == 0)
346 node = nodestack[--nodestackindex];
352 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
354 int nodestackindex = 0;
355 mnode_t *node, *nodestack[1024];
356 if (!model->brush.num_leafs)
358 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
364 // node - recurse down the BSP tree
365 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
369 return -1; // ERROR: NAN bounding box!
370 // box is on one side of plane, take that path
371 node = node->children[sides-1];
375 // box crosses plane, take one path and remember the other
376 if (nodestackindex < 1024)
377 nodestack[nodestackindex++] = node->children[0];
378 node = node->children[1];
384 // leaf - check if it is visible
385 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
387 // it is visible, return immediately with the news
392 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
396 if (nodestackindex < 1024)
397 nodestack[nodestackindex++] = node->children[0];
398 node = node->children[1];
403 // leaf - check if it is visible
404 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
406 // it is visible, return immediately with the news
412 // nothing to see here, try another path we didn't take earlier
413 if (nodestackindex == 0)
415 node = nodestack[--nodestackindex];
421 typedef struct findnonsolidlocationinfo_s
424 vec3_t absmin, absmax;
430 findnonsolidlocationinfo_t;
432 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
435 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
437 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
438 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
439 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
440 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
441 VectorSubtract(vert[1], vert[0], edge[0]);
442 VectorSubtract(vert[2], vert[1], edge[1]);
443 CrossProduct(edge[1], edge[0], facenormal);
444 if (facenormal[0] || facenormal[1] || facenormal[2])
446 VectorNormalize(facenormal);
447 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
448 if (f <= info->bestdist && f >= -info->bestdist)
450 VectorSubtract(vert[0], vert[2], edge[2]);
451 VectorNormalize(edge[0]);
452 VectorNormalize(edge[1]);
453 VectorNormalize(edge[2]);
454 CrossProduct(facenormal, edge[0], edgenormal[0]);
455 CrossProduct(facenormal, edge[1], edgenormal[1]);
456 CrossProduct(facenormal, edge[2], edgenormal[2]);
458 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
459 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
460 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
462 // we got lucky, the center is within the face
463 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
467 if (info->bestdist > dist)
469 info->bestdist = dist;
470 VectorScale(facenormal, (info->radius - -dist), info->nudge);
475 if (info->bestdist > dist)
477 info->bestdist = dist;
478 VectorScale(facenormal, (info->radius - dist), info->nudge);
484 // check which edge or vertex the center is nearest
485 for (i = 0;i < 3;i++)
487 f = DotProduct(info->center, edge[i]);
488 if (f >= DotProduct(vert[0], edge[i])
489 && f <= DotProduct(vert[1], edge[i]))
492 VectorMA(info->center, -f, edge[i], point);
493 dist = sqrt(DotProduct(point, point));
494 if (info->bestdist > dist)
496 info->bestdist = dist;
497 VectorScale(point, (info->radius / dist), info->nudge);
499 // skip both vertex checks
500 // (both are further away than this edge)
505 // not on edge, check first vertex of edge
506 VectorSubtract(info->center, vert[i], point);
507 dist = sqrt(DotProduct(point, point));
508 if (info->bestdist > dist)
510 info->bestdist = dist;
511 VectorScale(point, (info->radius / dist), info->nudge);
520 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
522 int surfacenum, k, *mark;
524 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
526 surface = info->model->data_surfaces + *mark;
527 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
529 if(surface->deprecatedq3num_bboxstride > 0)
532 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
533 for(i = 0; i < cnt; ++i)
535 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
537 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
539 tri = i * surface->deprecatedq3num_bboxstride + k;
540 if(tri >= surface->num_triangles)
542 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
549 for (k = 0;k < surface->num_triangles;k++)
551 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
558 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
562 float f = PlaneDiff(info->center, node->plane);
563 if (f >= -info->bestdist)
564 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
565 if (f <= info->bestdist)
566 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
570 if (((mleaf_t *)node)->numleafsurfaces)
571 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
575 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
578 findnonsolidlocationinfo_t info;
584 VectorCopy(in, info.center);
585 info.radius = radius;
590 VectorClear(info.nudge);
591 info.bestdist = radius;
592 VectorCopy(info.center, info.absmin);
593 VectorCopy(info.center, info.absmax);
594 info.absmin[0] -= info.radius + 1;
595 info.absmin[1] -= info.radius + 1;
596 info.absmin[2] -= info.radius + 1;
597 info.absmax[0] += info.radius + 1;
598 info.absmax[1] += info.radius + 1;
599 info.absmax[2] += info.radius + 1;
600 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
601 VectorAdd(info.center, info.nudge, info.center);
603 while (info.bestdist < radius && ++i < 10);
604 VectorCopy(info.center, out);
607 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
609 switch(nativecontents)
614 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
616 return SUPERCONTENTS_WATER;
618 return SUPERCONTENTS_SLIME;
620 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
622 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
627 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
629 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
630 return CONTENTS_SOLID;
631 if (supercontents & SUPERCONTENTS_SKY)
633 if (supercontents & SUPERCONTENTS_LAVA)
634 return CONTENTS_LAVA;
635 if (supercontents & SUPERCONTENTS_SLIME)
636 return CONTENTS_SLIME;
637 if (supercontents & SUPERCONTENTS_WATER)
638 return CONTENTS_WATER;
639 return CONTENTS_EMPTY;
642 typedef struct RecursiveHullCheckTraceInfo_s
644 // the hull we're tracing through
647 // the trace structure to fill in
650 // start, end, and end - start (in model space)
655 RecursiveHullCheckTraceInfo_t;
657 // 1/32 epsilon to keep floating point happy
658 #define DIST_EPSILON (0.03125)
660 #define HULLCHECKSTATE_EMPTY 0
661 #define HULLCHECKSTATE_SOLID 1
662 #define HULLCHECKSTATE_DONE 2
664 extern cvar_t collision_prefernudgedfraction;
665 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
667 // status variables, these don't need to be saved on the stack when
668 // recursing... but are because this should be thread-safe
669 // (note: tracing against a bbox is not thread-safe, yet)
674 // variables that need to be stored on the stack when recursing
679 // LordHavoc: a goto! everyone flee in terror... :)
684 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
685 if (!t->trace->startfound)
687 t->trace->startfound = true;
688 t->trace->startsupercontents |= num;
690 if (num & SUPERCONTENTS_LIQUIDSMASK)
691 t->trace->inwater = true;
693 t->trace->inopen = true;
694 if (num & SUPERCONTENTS_SOLID)
695 t->trace->hittexture = &mod_q1bsp_texture_solid;
696 else if (num & SUPERCONTENTS_SKY)
697 t->trace->hittexture = &mod_q1bsp_texture_sky;
698 else if (num & SUPERCONTENTS_LAVA)
699 t->trace->hittexture = &mod_q1bsp_texture_lava;
700 else if (num & SUPERCONTENTS_SLIME)
701 t->trace->hittexture = &mod_q1bsp_texture_slime;
703 t->trace->hittexture = &mod_q1bsp_texture_water;
704 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
705 t->trace->hitsupercontents = num;
706 if (num & t->trace->hitsupercontentsmask)
708 // if the first leaf is solid, set startsolid
709 if (t->trace->allsolid)
710 t->trace->startsolid = true;
711 #if COLLISIONPARANOID >= 3
714 return HULLCHECKSTATE_SOLID;
718 t->trace->allsolid = false;
719 #if COLLISIONPARANOID >= 3
722 return HULLCHECKSTATE_EMPTY;
726 // find the point distances
727 node = t->hull->clipnodes + num;
729 plane = t->hull->planes + node->planenum;
732 t1 = p1[plane->type] - plane->dist;
733 t2 = p2[plane->type] - plane->dist;
737 t1 = DotProduct (plane->normal, p1) - plane->dist;
738 t2 = DotProduct (plane->normal, p2) - plane->dist;
745 #if COLLISIONPARANOID >= 3
748 num = node->children[1];
757 #if COLLISIONPARANOID >= 3
760 num = node->children[0];
766 // the line intersects, find intersection point
767 // LordHavoc: this uses the original trace for maximum accuracy
768 #if COLLISIONPARANOID >= 3
773 t1 = t->start[plane->type] - plane->dist;
774 t2 = t->end[plane->type] - plane->dist;
778 t1 = DotProduct (plane->normal, t->start) - plane->dist;
779 t2 = DotProduct (plane->normal, t->end) - plane->dist;
782 midf = t1 / (t1 - t2);
783 midf = bound(p1f, midf, p2f);
784 VectorMA(t->start, midf, t->dist, mid);
786 // recurse both sides, front side first
787 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
788 // if this side is not empty, return what it is (solid or done)
789 if (ret != HULLCHECKSTATE_EMPTY)
792 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
793 // if other side is not solid, return what it is (empty or done)
794 if (ret != HULLCHECKSTATE_SOLID)
797 // front is air and back is solid, this is the impact point...
800 t->trace->plane.dist = -plane->dist;
801 VectorNegate (plane->normal, t->trace->plane.normal);
805 t->trace->plane.dist = plane->dist;
806 VectorCopy (plane->normal, t->trace->plane.normal);
809 // calculate the true fraction
810 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
811 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
812 midf = t1 / (t1 - t2);
813 t->trace->realfraction = bound(0, midf, 1);
815 // calculate the return fraction which is nudged off the surface a bit
816 midf = (t1 - DIST_EPSILON) / (t1 - t2);
817 t->trace->fraction = bound(0, midf, 1);
819 if (collision_prefernudgedfraction.integer)
820 t->trace->realfraction = t->trace->fraction;
822 #if COLLISIONPARANOID >= 3
825 return HULLCHECKSTATE_DONE;
828 //#if COLLISIONPARANOID < 2
829 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
832 mclipnode_t *nodes = t->hull->clipnodes;
833 mplane_t *planes = t->hull->planes;
835 VectorCopy(t->start, point);
838 plane = planes + nodes[num].planenum;
839 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
841 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
842 t->trace->startsupercontents |= num;
843 if (num & SUPERCONTENTS_LIQUIDSMASK)
844 t->trace->inwater = true;
846 t->trace->inopen = true;
847 if (num & t->trace->hitsupercontentsmask)
849 t->trace->allsolid = t->trace->startsolid = true;
850 return HULLCHECKSTATE_SOLID;
854 t->trace->allsolid = t->trace->startsolid = false;
855 return HULLCHECKSTATE_EMPTY;
860 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)
862 RecursiveHullCheckTraceInfo_t rhc;
864 memset(&rhc, 0, sizeof(rhc));
865 memset(trace, 0, sizeof(trace_t));
867 rhc.trace->fraction = 1;
868 rhc.trace->realfraction = 1;
869 rhc.trace->allsolid = true;
870 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
871 VectorCopy(start, rhc.start);
872 VectorCopy(start, rhc.end);
873 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
876 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)
878 RecursiveHullCheckTraceInfo_t rhc;
880 if (VectorCompare(start, end))
882 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
886 memset(&rhc, 0, sizeof(rhc));
887 memset(trace, 0, sizeof(trace_t));
889 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
890 rhc.trace->fraction = 1;
891 rhc.trace->realfraction = 1;
892 rhc.trace->allsolid = true;
893 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
894 VectorCopy(start, rhc.start);
895 VectorCopy(end, rhc.end);
896 VectorSubtract(rhc.end, rhc.start, rhc.dist);
897 #if COLLISIONPARANOID >= 2
898 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]);
899 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
904 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
905 memset(&testtrace, 0, sizeof(trace_t));
906 rhc.trace = &testtrace;
907 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
908 rhc.trace->fraction = 1;
909 rhc.trace->realfraction = 1;
910 rhc.trace->allsolid = true;
911 VectorCopy(test, rhc.start);
912 VectorCopy(test, rhc.end);
913 VectorClear(rhc.dist);
914 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
915 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
916 if (!trace->startsolid && testtrace.startsolid)
917 Con_Printf(" - ended in solid!\n");
921 if (VectorLength2(rhc.dist))
922 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
924 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
928 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)
930 // this function currently only supports same size start and end
932 RecursiveHullCheckTraceInfo_t rhc;
934 if (VectorCompare(boxmins, boxmaxs))
936 if (VectorCompare(start, end))
937 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
939 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
943 memset(&rhc, 0, sizeof(rhc));
944 memset(trace, 0, sizeof(trace_t));
946 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
947 rhc.trace->fraction = 1;
948 rhc.trace->realfraction = 1;
949 rhc.trace->allsolid = true;
950 VectorSubtract(boxmaxs, boxmins, boxsize);
952 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
953 else if (model->brush.ishlbsp)
955 // LordHavoc: this has to have a minor tolerance (the .1) because of
956 // minor float precision errors from the box being transformed around
957 if (boxsize[0] < 32.1)
959 if (boxsize[2] < 54) // pick the nearest of 36 or 72
960 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
962 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
965 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
969 // LordHavoc: this has to have a minor tolerance (the .1) because of
970 // minor float precision errors from the box being transformed around
971 if (boxsize[0] < 32.1)
972 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
974 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
976 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
977 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
978 VectorSubtract(rhc.end, rhc.start, rhc.dist);
979 #if COLLISIONPARANOID >= 2
980 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]);
981 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
986 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
987 memset(&testtrace, 0, sizeof(trace_t));
988 rhc.trace = &testtrace;
989 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
990 rhc.trace->fraction = 1;
991 rhc.trace->realfraction = 1;
992 rhc.trace->allsolid = true;
993 VectorCopy(test, rhc.start);
994 VectorCopy(test, rhc.end);
995 VectorClear(rhc.dist);
996 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
997 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
998 if (!trace->startsolid && testtrace.startsolid)
999 Con_Printf(" - ended in solid!\n");
1003 if (VectorLength2(rhc.dist))
1004 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1006 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1010 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1012 int num = model->brushq1.hulls[0].firstclipnode;
1014 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1015 mplane_t *planes = model->brushq1.hulls[0].planes;
1018 plane = planes + nodes[num].planenum;
1019 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1021 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1024 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)
1028 colplanef_t cbox_planes[6];
1030 cbox.hasaabbplanes = true;
1031 cbox.supercontents = boxsupercontents;
1034 cbox.numtriangles = 0;
1035 cbox.planes = cbox_planes;
1037 cbox.elements = NULL;
1045 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];
1046 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];
1047 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];
1048 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];
1049 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];
1050 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];
1051 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1052 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1053 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1054 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1055 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1056 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1057 memset(trace, 0, sizeof(trace_t));
1058 trace->hitsupercontentsmask = hitsupercontentsmask;
1059 trace->fraction = 1;
1060 trace->realfraction = 1;
1061 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1063 RecursiveHullCheckTraceInfo_t rhc;
1064 static hull_t box_hull;
1065 static mclipnode_t box_clipnodes[6];
1066 static mplane_t box_planes[6];
1067 // fill in a default trace
1068 memset(&rhc, 0, sizeof(rhc));
1069 memset(trace, 0, sizeof(trace_t));
1070 //To keep everything totally uniform, bounding boxes are turned into small
1071 //BSP trees instead of being compared directly.
1072 // create a temp hull from bounding box sizes
1073 box_planes[0].dist = cmaxs[0] - mins[0];
1074 box_planes[1].dist = cmins[0] - maxs[0];
1075 box_planes[2].dist = cmaxs[1] - mins[1];
1076 box_planes[3].dist = cmins[1] - maxs[1];
1077 box_planes[4].dist = cmaxs[2] - mins[2];
1078 box_planes[5].dist = cmins[2] - maxs[2];
1079 #if COLLISIONPARANOID >= 3
1080 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]);
1083 if (box_hull.clipnodes == NULL)
1087 //Set up the planes and clipnodes so that the six floats of a bounding box
1088 //can just be stored out and get a proper hull_t structure.
1090 box_hull.clipnodes = box_clipnodes;
1091 box_hull.planes = box_planes;
1092 box_hull.firstclipnode = 0;
1093 box_hull.lastclipnode = 5;
1095 for (i = 0;i < 6;i++)
1097 box_clipnodes[i].planenum = i;
1101 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1103 box_clipnodes[i].children[side^1] = i + 1;
1105 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1107 box_planes[i].type = i>>1;
1108 box_planes[i].normal[i>>1] = 1;
1112 // trace a line through the generated clipping hull
1113 //rhc.boxsupercontents = boxsupercontents;
1114 rhc.hull = &box_hull;
1116 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1117 rhc.trace->fraction = 1;
1118 rhc.trace->realfraction = 1;
1119 rhc.trace->allsolid = true;
1120 VectorCopy(start, rhc.start);
1121 VectorCopy(end, rhc.end);
1122 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1123 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1124 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1125 if (rhc.trace->startsupercontents)
1126 rhc.trace->startsupercontents = boxsupercontents;
1130 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)
1132 memset(trace, 0, sizeof(trace_t));
1133 trace->fraction = 1;
1134 trace->realfraction = 1;
1135 if (BoxesOverlap(start, start, cmins, cmaxs))
1137 trace->startsupercontents |= boxsupercontents;
1138 if (hitsupercontentsmask & boxsupercontents)
1140 trace->startsolid = true;
1141 trace->allsolid = true;
1146 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1149 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1150 return trace.fraction == 1;
1153 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)
1157 float mid, distz = endz - startz;
1161 return false; // didn't hit anything
1163 switch (node->plane->type)
1166 node = node->children[x < node->plane->dist];
1169 node = node->children[y < node->plane->dist];
1172 side = startz < node->plane->dist;
1173 if ((endz < node->plane->dist) == side)
1175 node = node->children[side];
1178 // found an intersection
1179 mid = node->plane->dist;
1182 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1183 front += startz * node->plane->normal[2];
1184 back += endz * node->plane->normal[2];
1185 side = front < node->plane->dist;
1186 if ((back < node->plane->dist) == side)
1188 node = node->children[side];
1191 // found an intersection
1192 mid = startz + distz * (front - node->plane->dist) / (front - back);
1196 // go down front side
1197 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1198 return true; // hit something
1201 // check for impact on this node
1202 if (node->numsurfaces)
1204 int i, dsi, dti, lmwidth, lmheight;
1206 msurface_t *surface;
1207 unsigned char *lightmap;
1208 int maps, line3, size3;
1211 float scale, w, w00, w01, w10, w11;
1213 surface = model->data_surfaces + node->firstsurface;
1214 for (i = 0;i < node->numsurfaces;i++, surface++)
1216 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1217 continue; // no lightmaps
1219 // location we want to sample in the lightmap
1220 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;
1221 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;
1226 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1227 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1230 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1232 // calculate bilinear interpolation factors
1233 // and also multiply by fixedpoint conversion factors
1236 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1237 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1238 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1239 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1241 // values for pointer math
1242 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1243 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1245 // look up the pixel
1246 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1248 // bilinear filter each lightmap style, and sum them
1249 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1251 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1252 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1253 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1254 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1255 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1259 return true; // success
1264 // go down back side
1265 node = node->children[side ^ 1];
1267 distz = endz - startz;
1272 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1274 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1275 VectorSet(diffusenormal, 0, 0, 1);
1277 if (!model->brushq1.lightdata)
1279 VectorSet(ambientcolor, 1, 1, 1);
1280 VectorSet(diffusecolor, 0, 0, 0);
1284 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);
1287 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1290 unsigned char *outstart = out;
1291 while (out < outend)
1295 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));
1305 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));
1308 for (c = *in++;c > 0;c--)
1312 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));
1323 R_Q1BSP_LoadSplitSky
1325 A sky texture is 256*128, with the right side being a masked overlay
1328 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1333 unsigned *solidpixels = Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1334 unsigned *alphapixels = Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1336 // allocate a texture pool if we need it
1337 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1338 loadmodel->texturepool = R_AllocTexturePool();
1340 if (bytesperpixel == 4)
1342 for (y = 0;y < h;y++)
1344 for (x = 0;x < w;x++)
1346 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1347 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1353 // make an average value for the back to avoid
1354 // a fringe on the top level
1363 for (y = 0;y < h;y++)
1365 for (x = 0;x < w;x++)
1367 p = src[x*width+y+w];
1368 r += palette_rgb[p][0];
1369 g += palette_rgb[p][1];
1370 b += palette_rgb[p][2];
1373 bgra.b[2] = r/(w*h);
1374 bgra.b[1] = g/(w*h);
1375 bgra.b[0] = b/(w*h);
1377 for (y = 0;y < h;y++)
1379 for (x = 0;x < w;x++)
1381 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1383 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1388 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h);
1389 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h);
1390 Mem_Free(solidpixels);
1391 Mem_Free(alphapixels);
1394 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1396 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1397 skinframe_t *skinframe;
1399 texture_t *tx, *tx2, *anims[10], *altanims[10];
1401 unsigned char *data, *mtdata;
1403 char mapname[MAX_QPATH], name[MAX_QPATH];
1404 unsigned char zero[4];
1406 memset(zero, 0, sizeof(zero));
1408 loadmodel->data_textures = NULL;
1410 // add two slots for notexture walls and notexture liquids
1413 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1414 m->nummiptex = LittleLong (m->nummiptex);
1415 loadmodel->num_textures = m->nummiptex + 2;
1416 loadmodel->num_texturesperskin = loadmodel->num_textures;
1421 loadmodel->num_textures = 2;
1422 loadmodel->num_texturesperskin = loadmodel->num_textures;
1425 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1427 // fill out all slots with notexture
1428 if (cls.state != ca_dedicated)
1429 skinframe = R_SkinFrame_LoadMissing();
1432 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1434 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1437 if (cls.state != ca_dedicated)
1439 tx->numskinframes = 1;
1440 tx->skinframerate = 1;
1441 tx->skinframes[0] = skinframe;
1442 tx->currentskinframe = tx->skinframes[0];
1444 tx->basematerialflags = MATERIALFLAG_WALL;
1445 if (i == loadmodel->num_textures - 1)
1447 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1448 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1449 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1453 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1454 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1456 tx->currentframe = tx;
1458 // clear water settings
1461 tx->refractfactor = 1;
1462 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1463 tx->reflectfactor = 1;
1464 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1465 tx->r_water_wateralpha = 1;
1466 tx->specularscalemod = 1;
1467 tx->specularpowermod = 1;
1472 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1476 s = loadmodel->name;
1477 if (!strncasecmp(s, "maps/", 5))
1479 FS_StripExtension(s, mapname, sizeof(mapname));
1481 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1483 // LordHavoc: mostly rewritten map texture loader
1484 for (i = 0;i < m->nummiptex;i++)
1486 dofs[i] = LittleLong(dofs[i]);
1487 if (r_nosurftextures.integer)
1491 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1494 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1496 // copy name, but only up to 16 characters
1497 // (the output buffer can hold more than this, but the input buffer is
1499 for (j = 0;j < 16 && dmiptex->name[j];j++)
1500 name[j] = dmiptex->name[j];
1505 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1506 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1509 mtwidth = LittleLong(dmiptex->width);
1510 mtheight = LittleLong(dmiptex->height);
1512 j = LittleLong(dmiptex->offsets[0]);
1516 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1518 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1521 mtdata = (unsigned char *)dmiptex + j;
1524 if ((mtwidth & 15) || (mtheight & 15))
1525 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1527 // LordHavoc: force all names to lowercase
1528 for (j = 0;name[j];j++)
1529 if (name[j] >= 'A' && name[j] <= 'Z')
1530 name[j] += 'a' - 'A';
1532 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1535 tx = loadmodel->data_textures + i;
1536 strlcpy(tx->name, name, sizeof(tx->name));
1537 tx->width = mtwidth;
1538 tx->height = mtheight;
1540 if (tx->name[0] == '*')
1542 if (!strncmp(tx->name, "*lava", 5))
1544 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1545 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1547 else if (!strncmp(tx->name, "*slime", 6))
1549 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1550 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1554 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1555 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1558 else if (!strncmp(tx->name, "sky", 3))
1560 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1561 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1565 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1566 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1569 if (cls.state != ca_dedicated)
1571 // LordHavoc: HL sky textures are entirely different than quake
1572 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1574 data = loadimagepixelsbgra(tx->name, false, false, r_texture_convertsRGB_skin.integer);
1575 if (data && image_width == image_height * 2)
1577 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1580 else if (mtdata != NULL)
1581 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1585 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);
1587 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);
1590 // did not find external texture, load it from the bsp or wad3
1591 if (loadmodel->brush.ishlbsp)
1593 // internal texture overrides wad
1594 unsigned char *pixels, *freepixels;
1595 pixels = freepixels = NULL;
1597 pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1599 pixels = freepixels = W_GetTextureBGRA(tx->name);
1602 tx->width = image_width;
1603 tx->height = image_height;
1604 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0), pixels, image_width, image_height);
1607 Mem_Free(freepixels);
1609 else if (mtdata) // texture included
1610 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0), false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1612 // if skinframe is still NULL the "missing" texture will be used
1614 tx->skinframes[0] = skinframe;
1617 tx->basematerialflags = MATERIALFLAG_WALL;
1618 if (tx->name[0] == '*')
1620 // LordHavoc: some turbulent textures should not be affected by wateralpha
1621 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1623 // replace the texture with transparent black
1624 Vector4Set(zero, 128, 128, 128, 128);
1625 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zero, 1, 1);
1626 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1628 else if (!strncmp(tx->name,"*lava",5)
1629 || !strncmp(tx->name,"*teleport",9)
1630 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1631 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1633 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1634 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1635 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1637 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1639 // replace the texture with black
1640 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zero, 1, 1);
1641 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1643 else if (!strncmp(tx->name, "sky", 3))
1644 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1645 else if (!strcmp(tx->name, "caulk"))
1646 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1647 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1648 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1650 // start out with no animation
1651 tx->currentframe = tx;
1652 tx->currentskinframe = tx->skinframes[0];
1656 // sequence the animations
1657 for (i = 0;i < m->nummiptex;i++)
1659 tx = loadmodel->data_textures + i;
1660 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1662 if (tx->anim_total[0] || tx->anim_total[1])
1663 continue; // already sequenced
1665 // find the number of frames in the animation
1666 memset(anims, 0, sizeof(anims));
1667 memset(altanims, 0, sizeof(altanims));
1669 for (j = i;j < m->nummiptex;j++)
1671 tx2 = loadmodel->data_textures + j;
1672 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1676 if (num >= '0' && num <= '9')
1677 anims[num - '0'] = tx2;
1678 else if (num >= 'a' && num <= 'j')
1679 altanims[num - 'a'] = tx2;
1681 Con_Printf("Bad animating texture %s\n", tx->name);
1685 for (j = 0;j < 10;j++)
1692 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1695 for (j = 0;j < max;j++)
1699 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1703 for (j = 0;j < altmax;j++)
1707 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1716 // if there is no alternate animation, duplicate the primary
1717 // animation into the alternate
1719 for (k = 0;k < 10;k++)
1720 altanims[k] = anims[k];
1723 // link together the primary animation
1724 for (j = 0;j < max;j++)
1727 tx2->animated = true;
1728 tx2->anim_total[0] = max;
1729 tx2->anim_total[1] = altmax;
1730 for (k = 0;k < 10;k++)
1732 tx2->anim_frames[0][k] = anims[k];
1733 tx2->anim_frames[1][k] = altanims[k];
1737 // if there really is an alternate anim...
1738 if (anims[0] != altanims[0])
1740 // link together the alternate animation
1741 for (j = 0;j < altmax;j++)
1744 tx2->animated = true;
1745 // the primary/alternate are reversed here
1746 tx2->anim_total[0] = altmax;
1747 tx2->anim_total[1] = max;
1748 for (k = 0;k < 10;k++)
1750 tx2->anim_frames[0][k] = altanims[k];
1751 tx2->anim_frames[1][k] = anims[k];
1758 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1761 unsigned char *in, *out, *data, d;
1762 char litfilename[MAX_QPATH];
1763 char dlitfilename[MAX_QPATH];
1764 fs_offset_t filesize;
1765 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1767 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1768 for (i=0; i<l->filelen; i++)
1769 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1771 else // LordHavoc: bsp version 29 (normal white lighting)
1773 // LordHavoc: hope is not lost yet, check for a .lit file to load
1774 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1775 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1776 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1777 strlcat (litfilename, ".lit", sizeof (litfilename));
1778 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1779 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1782 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1784 i = LittleLong(((int *)data)[1]);
1787 if (developer_loading.integer)
1788 Con_Printf("loaded %s\n", litfilename);
1789 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1790 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1792 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1795 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1797 i = LittleLong(((int *)data)[1]);
1800 if (developer_loading.integer)
1801 Con_Printf("loaded %s\n", dlitfilename);
1802 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1803 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
1804 loadmodel->brushq3.deluxemapping_modelspace = false;
1805 loadmodel->brushq3.deluxemapping = true;
1814 Con_Printf("Unknown .lit file version (%d)\n", i);
1816 else if (filesize == 8)
1817 Con_Print("Empty .lit file, ignoring\n");
1819 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
1826 // LordHavoc: oh well, expand the white lighting data
1829 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1830 in = mod_base + l->fileofs;
1831 out = loadmodel->brushq1.lightdata;
1832 for (i = 0;i < l->filelen;i++)
1842 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1844 loadmodel->brushq1.num_compressedpvs = 0;
1845 loadmodel->brushq1.data_compressedpvs = NULL;
1848 loadmodel->brushq1.num_compressedpvs = l->filelen;
1849 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1850 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1853 // used only for HalfLife maps
1854 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1856 char key[128], value[4096];
1860 if (!COM_ParseToken_Simple(&data, false, false))
1862 if (com_token[0] != '{')
1866 if (!COM_ParseToken_Simple(&data, false, false))
1868 if (com_token[0] == '}')
1869 break; // end of worldspawn
1870 if (com_token[0] == '_')
1871 strlcpy(key, com_token + 1, sizeof(key));
1873 strlcpy(key, com_token, sizeof(key));
1874 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1875 key[strlen(key)-1] = 0;
1876 if (!COM_ParseToken_Simple(&data, false, false))
1878 dpsnprintf(value, sizeof(value), "%s", com_token);
1879 if (!strcmp("wad", key)) // for HalfLife maps
1881 if (loadmodel->brush.ishlbsp)
1884 for (i = 0;i < (int)sizeof(value);i++)
1885 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1889 for (;i < (int)sizeof(value);i++)
1891 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1892 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1894 else if (value[i] == ';' || value[i] == 0)
1898 W_LoadTextureWadFile(&value[j], false);
1910 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1912 loadmodel->brush.entities = NULL;
1915 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
1916 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1917 loadmodel->brush.entities[l->filelen] = 0;
1918 if (loadmodel->brush.ishlbsp)
1919 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1923 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1929 in = (dvertex_t *)(mod_base + l->fileofs);
1930 if (l->filelen % sizeof(*in))
1931 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1932 count = l->filelen / sizeof(*in);
1933 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1935 loadmodel->brushq1.vertexes = out;
1936 loadmodel->brushq1.numvertexes = count;
1938 for ( i=0 ; i<count ; i++, in++, out++)
1940 out->position[0] = LittleFloat(in->point[0]);
1941 out->position[1] = LittleFloat(in->point[1]);
1942 out->position[2] = LittleFloat(in->point[2]);
1946 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1947 // can be used for this
1949 int SB_ReadInt (unsigned char **buffer)
1952 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1958 float SB_ReadFloat (unsigned char **buffer)
1966 u.i = SB_ReadInt (buffer);
1970 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1972 unsigned char *index;
1976 index = (unsigned char *)(mod_base + l->fileofs);
1977 if (l->filelen % (48+4*hullinfo->filehulls))
1978 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1980 count = l->filelen / (48+4*hullinfo->filehulls);
1981 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1983 loadmodel->brushq1.submodels = out;
1984 loadmodel->brush.numsubmodels = count;
1986 for (i = 0; i < count; i++, out++)
1988 // spread out the mins / maxs by a pixel
1989 out->mins[0] = SB_ReadFloat (&index) - 1;
1990 out->mins[1] = SB_ReadFloat (&index) - 1;
1991 out->mins[2] = SB_ReadFloat (&index) - 1;
1992 out->maxs[0] = SB_ReadFloat (&index) + 1;
1993 out->maxs[1] = SB_ReadFloat (&index) + 1;
1994 out->maxs[2] = SB_ReadFloat (&index) + 1;
1995 out->origin[0] = SB_ReadFloat (&index);
1996 out->origin[1] = SB_ReadFloat (&index);
1997 out->origin[2] = SB_ReadFloat (&index);
1998 for (j = 0; j < hullinfo->filehulls; j++)
1999 out->headnode[j] = SB_ReadInt (&index);
2000 out->visleafs = SB_ReadInt (&index);
2001 out->firstface = SB_ReadInt (&index);
2002 out->numfaces = SB_ReadInt (&index);
2006 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2012 in = (dedge_t *)(mod_base + l->fileofs);
2013 if (l->filelen % sizeof(*in))
2014 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2015 count = l->filelen / sizeof(*in);
2016 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2018 loadmodel->brushq1.edges = out;
2019 loadmodel->brushq1.numedges = count;
2021 for ( i=0 ; i<count ; i++, in++, out++)
2023 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2024 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2025 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2027 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);
2028 if(!loadmodel->brushq1.numvertexes)
2029 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2037 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2041 int i, j, k, count, miptex;
2043 in = (texinfo_t *)(mod_base + l->fileofs);
2044 if (l->filelen % sizeof(*in))
2045 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2046 count = l->filelen / sizeof(*in);
2047 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2049 loadmodel->brushq1.texinfo = out;
2050 loadmodel->brushq1.numtexinfo = count;
2052 for (i = 0;i < count;i++, in++, out++)
2054 for (k = 0;k < 2;k++)
2055 for (j = 0;j < 4;j++)
2056 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2058 miptex = LittleLong(in->miptex);
2059 out->flags = LittleLong(in->flags);
2061 out->texture = NULL;
2062 if (loadmodel->data_textures)
2064 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2065 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2067 out->texture = loadmodel->data_textures + miptex;
2069 if (out->flags & TEX_SPECIAL)
2071 // if texture chosen is NULL or the shader needs a lightmap,
2072 // force to notexture water shader
2073 if (out->texture == NULL)
2074 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2078 // if texture chosen is NULL, force to notexture
2079 if (out->texture == NULL)
2080 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2086 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2091 mins[0] = mins[1] = mins[2] = 9999;
2092 maxs[0] = maxs[1] = maxs[2] = -9999;
2094 for (i = 0;i < numverts;i++)
2096 for (j = 0;j < 3;j++, v++)
2106 #define MAX_SUBDIVPOLYTRIANGLES 4096
2107 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2109 static int subdivpolyverts, subdivpolytriangles;
2110 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2111 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2113 static int subdivpolylookupvert(vec3_t v)
2116 for (i = 0;i < subdivpolyverts;i++)
2117 if (subdivpolyvert[i][0] == v[0]
2118 && subdivpolyvert[i][1] == v[1]
2119 && subdivpolyvert[i][2] == v[2])
2121 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2122 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2123 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2124 return subdivpolyverts++;
2127 static void SubdividePolygon(int numverts, float *verts)
2129 int i, i1, i2, i3, f, b, c, p;
2130 vec3_t mins, maxs, front[256], back[256];
2131 float m, *pv, *cv, dist[256], frac;
2134 Host_Error("SubdividePolygon: ran out of verts in buffer");
2136 BoundPoly(numverts, verts, mins, maxs);
2138 for (i = 0;i < 3;i++)
2140 m = (mins[i] + maxs[i]) * 0.5;
2141 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2142 if (maxs[i] - m < 8)
2144 if (m - mins[i] < 8)
2148 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2149 dist[c] = cv[i] - m;
2152 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2156 VectorCopy(pv, front[f]);
2161 VectorCopy(pv, back[b]);
2164 if (dist[p] == 0 || dist[c] == 0)
2166 if ((dist[p] > 0) != (dist[c] > 0) )
2169 frac = dist[p] / (dist[p] - dist[c]);
2170 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2171 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2172 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2178 SubdividePolygon(f, front[0]);
2179 SubdividePolygon(b, back[0]);
2183 i1 = subdivpolylookupvert(verts);
2184 i2 = subdivpolylookupvert(verts + 3);
2185 for (i = 2;i < numverts;i++)
2187 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2189 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2193 i3 = subdivpolylookupvert(verts + i * 3);
2194 subdivpolyindex[subdivpolytriangles][0] = i1;
2195 subdivpolyindex[subdivpolytriangles][1] = i2;
2196 subdivpolyindex[subdivpolytriangles][2] = i3;
2198 subdivpolytriangles++;
2202 //Breaks a polygon up along axial 64 unit
2203 //boundaries so that turbulent and sky warps
2204 //can be done reasonably.
2205 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2211 subdivpolytriangles = 0;
2212 subdivpolyverts = 0;
2213 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2214 if (subdivpolytriangles < 1)
2215 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2217 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2218 mesh->num_vertices = subdivpolyverts;
2219 mesh->num_triangles = subdivpolytriangles;
2220 mesh->vertex = (surfvertex_t *)(mesh + 1);
2221 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2222 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2224 for (i = 0;i < mesh->num_triangles;i++)
2225 for (j = 0;j < 3;j++)
2226 mesh->index[i*3+j] = subdivpolyindex[i][j];
2228 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2230 VectorCopy(subdivpolyvert[i], v->v);
2231 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2232 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2237 extern cvar_t gl_max_lightmapsize;
2238 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2241 msurface_t *surface;
2242 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2243 float texmins[2], texmaxs[2], val;
2244 rtexture_t *lightmaptexture, *deluxemaptexture;
2246 in = (dface_t *)(mod_base + l->fileofs);
2247 if (l->filelen % sizeof(*in))
2248 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2249 count = l->filelen / sizeof(*in);
2250 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2251 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2253 loadmodel->num_surfaces = count;
2255 loadmodel->brushq1.firstrender = true;
2256 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2260 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2262 numedges = (unsigned short)LittleShort(in->numedges);
2263 totalverts += numedges;
2264 totaltris += numedges - 2;
2267 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2269 lightmaptexture = NULL;
2270 deluxemaptexture = r_texture_blanknormalmap;
2272 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2273 totallightmapsamples = 0;
2277 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2279 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2281 // FIXME: validate edges, texinfo, etc?
2282 firstedge = LittleLong(in->firstedge);
2283 numedges = (unsigned short)LittleShort(in->numedges);
2284 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)
2285 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2286 i = (unsigned short)LittleShort(in->texinfo);
2287 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2288 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2289 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2290 surface->texture = surface->lightmapinfo->texinfo->texture;
2292 planenum = (unsigned short)LittleShort(in->planenum);
2293 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2294 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2296 //surface->flags = surface->texture->flags;
2297 //if (LittleShort(in->side))
2298 // surface->flags |= SURF_PLANEBACK;
2299 //surface->plane = loadmodel->brush.data_planes + planenum;
2301 surface->num_firstvertex = totalverts;
2302 surface->num_vertices = numedges;
2303 surface->num_firsttriangle = totaltris;
2304 surface->num_triangles = numedges - 2;
2305 totalverts += numedges;
2306 totaltris += numedges - 2;
2308 // convert edges back to a normal polygon
2309 for (i = 0;i < surface->num_vertices;i++)
2311 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2313 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2315 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2317 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2318 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2319 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2320 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2321 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2322 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2323 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2324 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2327 for (i = 0;i < surface->num_triangles;i++)
2329 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2330 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2331 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2334 // compile additional data about the surface geometry
2335 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);
2336 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);
2337 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2339 // generate surface extents information
2340 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2341 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2342 for (i = 1;i < surface->num_vertices;i++)
2344 for (j = 0;j < 2;j++)
2346 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2347 texmins[j] = min(texmins[j], val);
2348 texmaxs[j] = max(texmaxs[j], val);
2351 for (i = 0;i < 2;i++)
2353 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2354 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2357 smax = surface->lightmapinfo->extents[0] >> 4;
2358 tmax = surface->lightmapinfo->extents[1] >> 4;
2359 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2360 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2363 for (i = 0;i < MAXLIGHTMAPS;i++)
2364 surface->lightmapinfo->styles[i] = in->styles[i];
2365 surface->lightmaptexture = NULL;
2366 surface->deluxemaptexture = r_texture_blanknormalmap;
2367 i = LittleLong(in->lightofs);
2370 surface->lightmapinfo->samples = NULL;
2372 // give non-lightmapped water a 1x white lightmap
2373 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2375 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2376 surface->lightmapinfo->styles[0] = 0;
2377 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2381 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2382 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2383 else // LordHavoc: white lighting (bsp version 29)
2385 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2386 if (loadmodel->brushq1.nmaplightdata)
2387 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2390 // check if we should apply a lightmap to this
2391 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2393 if (ssize > 256 || tsize > 256)
2394 Host_Error("Bad surface extents");
2396 if (lightmapsize < ssize)
2397 lightmapsize = ssize;
2398 if (lightmapsize < tsize)
2399 lightmapsize = tsize;
2401 totallightmapsamples += ssize*tsize;
2403 // force lightmap upload on first time seeing the surface
2405 // additionally this is used by the later code to see if a
2406 // lightmap is needed on this surface (rather than duplicating the
2408 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2412 // small maps (such as ammo boxes especially) don't need big lightmap
2413 // textures, so this code tries to guess a good size based on
2414 // totallightmapsamples (size of the lightmaps lump basically), as well as
2415 // trying to max out the size if there is a lot of lightmap data to store
2416 // additionally, never choose a lightmapsize that is smaller than the
2417 // largest surface encountered (as it would fail)
2419 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2422 // now that we've decided the lightmap texture size, we can do the rest
2423 if (cls.state != ca_dedicated)
2425 int stainmapsize = 0;
2426 mod_alloclightmap_state_t allocState;
2428 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2429 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2431 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2432 float u, v, ubase, vbase, uscale, vscale;
2434 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2437 smax = surface->lightmapinfo->extents[0] >> 4;
2438 tmax = surface->lightmapinfo->extents[1] >> 4;
2439 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2440 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2441 stainmapsize += ssize * tsize * 3;
2443 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2445 // allocate a texture pool if we need it
2446 if (loadmodel->texturepool == NULL)
2447 loadmodel->texturepool = R_AllocTexturePool();
2448 // could not find room, make a new lightmap
2449 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2450 loadmodel->brushq3.data_lightmaps = Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2451 loadmodel->brushq3.data_deluxemaps = Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2452 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, NULL);
2453 if (loadmodel->brushq1.nmaplightdata)
2454 loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, NULL);
2456 Mod_AllocLightmap_Reset(&allocState);
2457 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2459 surface->lightmaptexture = lightmaptexture;
2460 surface->deluxemaptexture = deluxemaptexture;
2461 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2462 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2464 uscale = 1.0f / (float)lightmapsize;
2465 vscale = 1.0f / (float)lightmapsize;
2466 ubase = lightmapx * uscale;
2467 vbase = lightmapy * vscale;
2469 for (i = 0;i < surface->num_vertices;i++)
2471 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);
2472 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);
2473 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2474 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2475 // LordHavoc: calc lightmap data offset for vertex lighting to use
2478 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2482 if (cl_stainmaps.integer)
2484 // allocate stainmaps for permanent marks on walls and clear white
2485 unsigned char *stainsamples = NULL;
2486 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2487 memset(stainsamples, 255, stainmapsize);
2489 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2491 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2493 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2494 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2495 surface->lightmapinfo->stainsamples = stainsamples;
2496 stainsamples += ssize * tsize * 3;
2501 // generate ushort elements array if possible
2502 if (loadmodel->surfmesh.data_element3s)
2503 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2504 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2507 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2510 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2511 node->parent = parent;
2514 // this is a node, recurse to children
2515 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2516 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2517 // combine supercontents of children
2518 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2523 mleaf_t *leaf = (mleaf_t *)node;
2524 // if this is a leaf, calculate supercontents mask from all collidable
2525 // primitives in the leaf (brushes and collision surfaces)
2526 // also flag if the leaf contains any collision surfaces
2527 leaf->combinedsupercontents = 0;
2528 // combine the supercontents values of all brushes in this leaf
2529 for (j = 0;j < leaf->numleafbrushes;j++)
2530 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2531 // check if this leaf contains any collision surfaces (q3 patches)
2532 for (j = 0;j < leaf->numleafsurfaces;j++)
2534 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2535 if (surface->num_collisiontriangles)
2537 leaf->containscollisionsurfaces = true;
2538 leaf->combinedsupercontents |= surface->texture->supercontents;
2544 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2550 in = (dnode_t *)(mod_base + l->fileofs);
2551 if (l->filelen % sizeof(*in))
2552 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2553 count = l->filelen / sizeof(*in);
2554 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2556 loadmodel->brush.data_nodes = out;
2557 loadmodel->brush.num_nodes = count;
2559 for ( i=0 ; i<count ; i++, in++, out++)
2561 for (j=0 ; j<3 ; j++)
2563 out->mins[j] = LittleShort(in->mins[j]);
2564 out->maxs[j] = LittleShort(in->maxs[j]);
2567 p = LittleLong(in->planenum);
2568 out->plane = loadmodel->brush.data_planes + p;
2570 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2571 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2573 for (j=0 ; j<2 ; j++)
2575 // LordHavoc: this code supports broken bsp files produced by
2576 // arguire qbsp which can produce more than 32768 nodes, any value
2577 // below count is assumed to be a node number, any other value is
2578 // assumed to be a leaf number
2579 p = (unsigned short)LittleShort(in->children[j]);
2582 if (p < loadmodel->brush.num_nodes)
2583 out->children[j] = loadmodel->brush.data_nodes + p;
2586 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2587 // map it to the solid leaf
2588 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2593 // note this uses 65535 intentionally, -1 is leaf 0
2595 if (p < loadmodel->brush.num_leafs)
2596 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2599 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2600 // map it to the solid leaf
2601 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2607 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2610 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2616 in = (dleaf_t *)(mod_base + l->fileofs);
2617 if (l->filelen % sizeof(*in))
2618 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2619 count = l->filelen / sizeof(*in);
2620 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2622 loadmodel->brush.data_leafs = out;
2623 loadmodel->brush.num_leafs = count;
2624 // get visleafs from the submodel data
2625 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2626 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2627 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2628 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2630 for ( i=0 ; i<count ; i++, in++, out++)
2632 for (j=0 ; j<3 ; j++)
2634 out->mins[j] = LittleShort(in->mins[j]);
2635 out->maxs[j] = LittleShort(in->maxs[j]);
2638 // FIXME: this function could really benefit from some error checking
2640 out->contents = LittleLong(in->contents);
2642 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2643 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2644 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2646 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);
2647 out->firstleafsurface = NULL;
2648 out->numleafsurfaces = 0;
2651 out->clusterindex = i - 1;
2652 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2653 out->clusterindex = -1;
2655 p = LittleLong(in->visofs);
2656 // ignore visofs errors on leaf 0 (solid)
2657 if (p >= 0 && out->clusterindex >= 0)
2659 if (p >= loadmodel->brushq1.num_compressedpvs)
2660 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2662 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);
2665 for (j = 0;j < 4;j++)
2666 out->ambient_sound_level[j] = in->ambient_level[j];
2668 // FIXME: Insert caustics here
2672 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2676 const unsigned char *pvs;
2677 // if there's no vis data, assume supported (because everything is visible all the time)
2678 if (!loadmodel->brush.data_pvsclusters)
2680 // check all liquid leafs to see if they can see into empty leafs, if any
2681 // can we can assume this map supports r_wateralpha
2682 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2684 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2686 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2687 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2688 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2695 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2702 in = (dclipnode_t *)(mod_base + l->fileofs);
2703 if (l->filelen % sizeof(*in))
2704 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2705 count = l->filelen / sizeof(*in);
2706 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2708 loadmodel->brushq1.clipnodes = out;
2709 loadmodel->brushq1.numclipnodes = count;
2711 for (i = 1; i < MAX_MAP_HULLS; i++)
2713 hull = &loadmodel->brushq1.hulls[i];
2714 hull->clipnodes = out;
2715 hull->firstclipnode = 0;
2716 hull->lastclipnode = count-1;
2717 hull->planes = loadmodel->brush.data_planes;
2718 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2719 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2720 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2721 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2722 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2723 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2724 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2727 for (i=0 ; i<count ; i++, out++, in++)
2729 out->planenum = LittleLong(in->planenum);
2730 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2731 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2732 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2733 if (out->children[0] >= count)
2734 out->children[0] -= 65536;
2735 if (out->children[1] >= count)
2736 out->children[1] -= 65536;
2737 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2738 Host_Error("Corrupt clipping hull(out of range planenum)");
2742 //Duplicate the drawing hull structure as a clipping hull
2743 static void Mod_Q1BSP_MakeHull0(void)
2750 hull = &loadmodel->brushq1.hulls[0];
2752 in = loadmodel->brush.data_nodes;
2753 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2755 hull->clipnodes = out;
2756 hull->firstclipnode = 0;
2757 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2758 hull->planes = loadmodel->brush.data_planes;
2760 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2762 out->planenum = in->plane - loadmodel->brush.data_planes;
2763 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2764 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2768 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2773 in = (short *)(mod_base + l->fileofs);
2774 if (l->filelen % sizeof(*in))
2775 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2776 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2777 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2779 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2781 j = (unsigned short) LittleShort(in[i]);
2782 if (j >= loadmodel->num_surfaces)
2783 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2784 loadmodel->brush.data_leafsurfaces[i] = j;
2788 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2793 in = (int *)(mod_base + l->fileofs);
2794 if (l->filelen % sizeof(*in))
2795 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2796 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2797 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2799 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2800 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2804 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2810 in = (dplane_t *)(mod_base + l->fileofs);
2811 if (l->filelen % sizeof(*in))
2812 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2814 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2815 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2817 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2819 out->normal[0] = LittleFloat(in->normal[0]);
2820 out->normal[1] = LittleFloat(in->normal[1]);
2821 out->normal[2] = LittleFloat(in->normal[2]);
2822 out->dist = LittleFloat(in->dist);
2828 static void Mod_Q1BSP_LoadMapBrushes(void)
2832 int submodel, numbrushes;
2833 qboolean firstbrush;
2834 char *text, *maptext;
2835 char mapfilename[MAX_QPATH];
2836 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2837 strlcat (mapfilename, ".map", sizeof (mapfilename));
2838 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
2842 if (!COM_ParseToken_Simple(&data, false, false))
2847 if (!COM_ParseToken_Simple(&data, false, false))
2849 if (com_token[0] != '{')
2855 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2858 if (!COM_ParseToken_Simple(&data, false, false))
2860 if (com_token[0] == '}')
2861 break; // end of entity
2862 if (com_token[0] == '{')
2869 if (submodel > loadmodel->brush.numsubmodels)
2871 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2875 model = loadmodel->brush.submodels[submodel];
2882 if (!COM_ParseToken_Simple(&data, false, false))
2884 if (com_token[0] == '}')
2885 break; // end of brush
2886 // each brush face should be this format:
2887 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2888 // FIXME: support hl .map format
2889 for (pointnum = 0;pointnum < 3;pointnum++)
2891 COM_ParseToken_Simple(&data, false, false);
2892 for (componentnum = 0;componentnum < 3;componentnum++)
2894 COM_ParseToken_Simple(&data, false, false);
2895 point[pointnum][componentnum] = atof(com_token);
2897 COM_ParseToken_Simple(&data, false, false);
2899 COM_ParseToken_Simple(&data, false, false);
2900 strlcpy(facetexture, com_token, sizeof(facetexture));
2901 COM_ParseToken_Simple(&data, false, false);
2902 //scroll_s = atof(com_token);
2903 COM_ParseToken_Simple(&data, false, false);
2904 //scroll_t = atof(com_token);
2905 COM_ParseToken_Simple(&data, false, false);
2906 //rotate = atof(com_token);
2907 COM_ParseToken_Simple(&data, false, false);
2908 //scale_s = atof(com_token);
2909 COM_ParseToken_Simple(&data, false, false);
2910 //scale_t = atof(com_token);
2911 TriangleNormal(point[0], point[1], point[2], planenormal);
2912 VectorNormalizeDouble(planenormal);
2913 planedist = DotProduct(point[0], planenormal);
2914 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2924 #define MAX_PORTALPOINTS 64
2926 typedef struct portal_s
2929 mnode_t *nodes[2]; // [0] = front side of plane
2930 struct portal_s *next[2];
2932 double points[3*MAX_PORTALPOINTS];
2933 struct portal_s *chain; // all portals are linked into a list
2937 static memexpandablearray_t portalarray;
2939 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2941 // process only nodes (leafs already had their box calculated)
2945 // calculate children first
2946 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2947 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2949 // make combined bounding box from children
2950 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2951 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2952 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2953 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2954 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2955 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2958 static void Mod_Q1BSP_FinalizePortals(void)
2960 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
2964 mleaf_t *leaf, *endleaf;
2966 // tally up portal and point counts and recalculate bounding boxes for all
2967 // leafs (because qbsp is very sloppy)
2968 leaf = loadmodel->brush.data_leafs;
2969 endleaf = leaf + loadmodel->brush.num_leafs;
2970 for (;leaf < endleaf;leaf++)
2972 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
2973 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2977 for (portalindex = 0;portalindex < portalrange;portalindex++)
2979 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
2982 // note: this check must match the one below or it will usually corrupt memory
2983 // 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
2984 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2987 numpoints += p->numpoints * 2;
2990 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
2991 loadmodel->brush.num_portals = numportals;
2992 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
2993 loadmodel->brush.num_portalpoints = numpoints;
2994 // clear all leaf portal chains
2995 for (i = 0;i < loadmodel->brush.num_leafs;i++)
2996 loadmodel->brush.data_leafs[i].portals = NULL;
2997 // process all portals in the global portal chain, while freeing them
2998 portal = loadmodel->brush.data_portals;
2999 point = loadmodel->brush.data_portalpoints;
3000 for (portalindex = 0;portalindex < portalrange;portalindex++)
3002 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3005 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3007 // note: this check must match the one above or it will usually corrupt memory
3008 // 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
3009 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3011 // first make the back to front portal(forward portal)
3012 portal->points = point;
3013 portal->numpoints = p->numpoints;
3014 portal->plane.dist = p->plane.dist;
3015 VectorCopy(p->plane.normal, portal->plane.normal);
3016 portal->here = (mleaf_t *)p->nodes[1];
3017 portal->past = (mleaf_t *)p->nodes[0];
3019 for (j = 0;j < portal->numpoints;j++)
3021 VectorCopy(p->points + j*3, point->position);
3024 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3025 PlaneClassify(&portal->plane);
3027 // link into leaf's portal chain
3028 portal->next = portal->here->portals;
3029 portal->here->portals = portal;
3031 // advance to next portal
3034 // then make the front to back portal(backward portal)
3035 portal->points = point;
3036 portal->numpoints = p->numpoints;
3037 portal->plane.dist = -p->plane.dist;
3038 VectorNegate(p->plane.normal, portal->plane.normal);
3039 portal->here = (mleaf_t *)p->nodes[0];
3040 portal->past = (mleaf_t *)p->nodes[1];
3042 for (j = portal->numpoints - 1;j >= 0;j--)
3044 VectorCopy(p->points + j*3, point->position);
3047 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3048 PlaneClassify(&portal->plane);
3050 // link into leaf's portal chain
3051 portal->next = portal->here->portals;
3052 portal->here->portals = portal;
3054 // advance to next portal
3057 // add the portal's polygon points to the leaf bounding boxes
3058 for (i = 0;i < 2;i++)
3060 leaf = (mleaf_t *)p->nodes[i];
3061 for (j = 0;j < p->numpoints;j++)
3063 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3064 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3065 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3066 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3067 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3068 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3073 // now recalculate the node bounding boxes from the leafs
3074 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3082 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3085 Host_Error("AddPortalToNodes: NULL front node");
3087 Host_Error("AddPortalToNodes: NULL back node");
3088 if (p->nodes[0] || p->nodes[1])
3089 Host_Error("AddPortalToNodes: already included");
3090 // 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
3092 p->nodes[0] = front;
3093 p->next[0] = (portal_t *)front->portals;
3094 front->portals = (mportal_t *)p;
3097 p->next[1] = (portal_t *)back->portals;
3098 back->portals = (mportal_t *)p;
3103 RemovePortalFromNode
3106 static void RemovePortalFromNodes(portal_t *portal)
3110 void **portalpointer;
3112 for (i = 0;i < 2;i++)
3114 node = portal->nodes[i];
3116 portalpointer = (void **) &node->portals;
3119 t = (portal_t *)*portalpointer;
3121 Host_Error("RemovePortalFromNodes: portal not in leaf");
3125 if (portal->nodes[0] == node)
3127 *portalpointer = portal->next[0];
3128 portal->nodes[0] = NULL;
3130 else if (portal->nodes[1] == node)
3132 *portalpointer = portal->next[1];
3133 portal->nodes[1] = NULL;
3136 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3140 if (t->nodes[0] == node)
3141 portalpointer = (void **) &t->next[0];
3142 else if (t->nodes[1] == node)
3143 portalpointer = (void **) &t->next[1];
3145 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3150 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3151 static double *portalpointsbuffer;
3152 static int portalpointsbufferoffset;
3153 static int portalpointsbuffersize;
3154 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3157 mnode_t *front, *back, *other_node;
3158 mplane_t clipplane, *plane;
3159 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3160 int numfrontpoints, numbackpoints;
3161 double *frontpoints, *backpoints;
3163 // if a leaf, we're done
3167 // get some space for our clipping operations to use
3168 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3170 portalpointsbuffersize = portalpointsbufferoffset * 2;
3171 portalpointsbuffer = Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3173 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3174 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3175 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3176 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3178 plane = node->plane;
3180 front = node->children[0];
3181 back = node->children[1];
3183 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3185 // create the new portal by generating a polygon for the node plane,
3186 // and clipping it by all of the other portals(which came from nodes above this one)
3187 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3188 nodeportal->plane = *plane;
3190 // 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)
3191 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);
3192 nodeportal->numpoints = 4;
3193 side = 0; // shut up compiler warning
3194 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3196 clipplane = portal->plane;
3197 if (portal->nodes[0] == portal->nodes[1])
3198 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3199 if (portal->nodes[0] == node)
3201 else if (portal->nodes[1] == node)
3203 clipplane.dist = -clipplane.dist;
3204 VectorNegate(clipplane.normal, clipplane.normal);
3208 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3210 for (i = 0;i < nodeportal->numpoints*3;i++)
3211 frontpoints[i] = nodeportal->points[i];
3212 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);
3213 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3217 if (nodeportal->numpoints < 3)
3219 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3220 nodeportal->numpoints = 0;
3222 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3224 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3225 nodeportal->numpoints = 0;
3228 AddPortalToNodes(nodeportal, front, back);
3230 // split the portals of this node along this node's plane and assign them to the children of this node
3231 // (migrating the portals downward through the tree)
3232 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3234 if (portal->nodes[0] == portal->nodes[1])
3235 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3236 if (portal->nodes[0] == node)
3238 else if (portal->nodes[1] == node)
3241 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3242 nextportal = portal->next[side];
3243 if (!portal->numpoints)
3246 other_node = portal->nodes[!side];
3247 RemovePortalFromNodes(portal);
3249 // cut the portal into two portals, one on each side of the node plane
3250 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);
3252 if (!numfrontpoints)
3255 AddPortalToNodes(portal, back, other_node);
3257 AddPortalToNodes(portal, other_node, back);
3263 AddPortalToNodes(portal, front, other_node);
3265 AddPortalToNodes(portal, other_node, front);
3269 // the portal is split
3270 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3271 temp = splitportal->chain;
3272 *splitportal = *portal;
3273 splitportal->chain = temp;
3274 for (i = 0;i < numbackpoints*3;i++)
3275 splitportal->points[i] = backpoints[i];
3276 splitportal->numpoints = numbackpoints;
3277 for (i = 0;i < numfrontpoints*3;i++)
3278 portal->points[i] = frontpoints[i];
3279 portal->numpoints = numfrontpoints;
3283 AddPortalToNodes(portal, front, other_node);
3284 AddPortalToNodes(splitportal, back, other_node);
3288 AddPortalToNodes(portal, other_node, front);
3289 AddPortalToNodes(splitportal, other_node, back);
3293 Mod_Q1BSP_RecursiveNodePortals(front);
3294 Mod_Q1BSP_RecursiveNodePortals(back);
3296 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3299 static void Mod_Q1BSP_MakePortals(void)
3301 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3302 portalpointsbufferoffset = 0;
3303 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3304 portalpointsbuffer = Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3305 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3306 Mem_Free(portalpointsbuffer);
3307 portalpointsbuffer = NULL;
3308 portalpointsbufferoffset = 0;
3309 portalpointsbuffersize = 0;
3310 Mod_Q1BSP_FinalizePortals();
3311 Mem_ExpandableArray_FreeArray(&portalarray);
3314 //Returns PVS data for a given point
3315 //(note: can return NULL)
3316 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3319 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3321 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3322 if (((mleaf_t *)node)->clusterindex >= 0)
3323 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3328 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)
3332 float d = PlaneDiff(org, node->plane);
3334 node = node->children[0];
3335 else if (d < -radius)
3336 node = node->children[1];
3339 // go down both sides
3340 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3341 node = node->children[1];
3344 // if this leaf is in a cluster, accumulate the pvs bits
3345 if (((mleaf_t *)node)->clusterindex >= 0)
3348 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3349 for (i = 0;i < pvsbytes;i++)
3350 pvsbuffer[i] |= pvs[i];
3354 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3355 //of the given point.
3356 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3358 int bytes = model->brush.num_pvsclusterbytes;
3359 bytes = min(bytes, pvsbufferlength);
3360 if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3362 memset(pvsbuffer, 0xFF, bytes);
3366 memset(pvsbuffer, 0, bytes);
3367 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3371 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3376 VectorSubtract(inmaxs, inmins, size);
3377 if (cmodel->brush.ishlbsp)
3380 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3381 else if (size[0] <= 32)
3383 if (size[2] < 54) // pick the nearest of 36 or 72
3384 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3386 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3389 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3394 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3395 else if (size[0] <= 32)
3396 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3398 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3400 VectorCopy(inmins, outmins);
3401 VectorAdd(inmins, hull->clip_size, outmaxs);
3404 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3409 float dist, modelyawradius, modelradius;
3410 msurface_t *surface;
3411 int numshadowmeshtriangles;
3412 hullinfo_t hullinfo;
3413 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3414 model_brush_lightstyleinfo_t styleinfo[256];
3415 unsigned char *datapointer;
3417 mod->modeldatatypestring = "Q1BSP";
3419 mod->type = mod_brushq1;
3421 header = (dheader_t *)buffer;
3423 i = LittleLong(header->version);
3424 if (i != BSPVERSION && i != 30)
3425 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3426 mod->brush.ishlbsp = i == 30;
3428 // fill in hull info
3429 VectorClear (hullinfo.hullsizes[0][0]);
3430 VectorClear (hullinfo.hullsizes[0][1]);
3431 if (mod->brush.ishlbsp)
3433 mod->modeldatatypestring = "HLBSP";
3435 hullinfo.filehulls = 4;
3436 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3437 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3438 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3439 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3440 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3441 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3445 hullinfo.filehulls = 4;
3446 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3447 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3448 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3449 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3453 mod_base = (unsigned char*)buffer;
3454 for (i = 0; i < HEADER_LUMPS; i++)
3456 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3457 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3460 mod->soundfromcenter = true;
3461 mod->TraceBox = Mod_Q1BSP_TraceBox;
3462 mod->TraceLine = Mod_Q1BSP_TraceLine;
3463 mod->TracePoint = Mod_Q1BSP_TracePoint;
3464 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3465 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3466 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3467 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3468 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3469 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3470 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3471 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3472 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3473 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3474 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3475 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3476 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3477 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3478 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3479 mod->Draw = R_Q1BSP_Draw;
3480 mod->DrawDepth = R_Q1BSP_DrawDepth;
3481 mod->DrawDebug = R_Q1BSP_DrawDebug;
3482 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3483 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3484 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3485 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3486 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3487 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3488 mod->DrawLight = R_Q1BSP_DrawLight;
3492 mod->brush.qw_md4sum = 0;
3493 mod->brush.qw_md4sum2 = 0;
3494 for (i = 0;i < HEADER_LUMPS;i++)
3497 if (i == LUMP_ENTITIES)
3499 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3500 mod->brush.qw_md4sum ^= LittleLong(temp);
3501 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3503 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3504 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3507 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3508 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3509 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3510 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3511 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3512 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3513 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3514 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3515 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3516 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3517 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3518 // load submodels before leafs because they contain the number of vis leafs
3519 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3520 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3521 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3522 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3524 // check if the map supports transparent water rendering
3525 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3527 if (mod->brushq1.data_compressedpvs)
3528 Mem_Free(mod->brushq1.data_compressedpvs);
3529 mod->brushq1.data_compressedpvs = NULL;
3530 mod->brushq1.num_compressedpvs = 0;
3532 Mod_Q1BSP_MakeHull0();
3533 Mod_Q1BSP_MakePortals();
3535 mod->numframes = 2; // regular and alternate animation
3538 // make a single combined shadow mesh to allow optimized shadow volume creation
3539 numshadowmeshtriangles = 0;
3540 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3542 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3543 numshadowmeshtriangles += surface->num_triangles;
3545 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3546 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3547 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));
3548 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true, false);
3549 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
3551 if (loadmodel->brush.numsubmodels)
3552 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3554 // LordHavoc: to clear the fog around the original quake submodel code, I
3556 // first of all, some background info on the submodels:
3557 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3558 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3559 // now the weird for loop itself:
3560 // the loop functions in an odd way, on each iteration it sets up the
3561 // current 'mod' model (which despite the confusing code IS the model of
3562 // the number i), at the end of the loop it duplicates the model to become
3563 // the next submodel, and loops back to set up the new submodel.
3565 // LordHavoc: now the explanation of my sane way (which works identically):
3566 // set up the world model, then on each submodel copy from the world model
3567 // and set up the submodel with the respective model info.
3568 totalstylesurfaces = 0;
3570 for (i = 0;i < mod->brush.numsubmodels;i++)
3572 memset(stylecounts, 0, sizeof(stylecounts));
3573 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3575 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3576 for (j = 0;j < MAXLIGHTMAPS;j++)
3577 stylecounts[surface->lightmapinfo->styles[j]]++;
3579 for (k = 0;k < 255;k++)
3583 totalstylesurfaces += stylecounts[k];
3586 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3587 for (i = 0;i < mod->brush.numsubmodels;i++)
3589 // LordHavoc: this code was originally at the end of this loop, but
3590 // has been transformed to something more readable at the start here.
3595 // duplicate the basic information
3596 dpsnprintf(name, sizeof(name), "*%i", i);
3597 mod = Mod_FindName(name, loadmodel->name);
3598 // copy the base model to this one
3600 // rename the clone back to its proper name
3601 strlcpy(mod->name, name, sizeof(mod->name));
3602 mod->brush.parentmodel = loadmodel;
3603 // textures and memory belong to the main model
3604 mod->texturepool = NULL;
3605 mod->mempool = NULL;
3606 mod->brush.GetPVS = NULL;
3607 mod->brush.FatPVS = NULL;
3608 mod->brush.BoxTouchingPVS = NULL;
3609 mod->brush.BoxTouchingLeafPVS = NULL;
3610 mod->brush.BoxTouchingVisibleLeafs = NULL;
3611 mod->brush.FindBoxClusters = NULL;
3612 mod->brush.LightPoint = NULL;
3613 mod->brush.AmbientSoundLevelsForPoint = NULL;
3616 mod->brush.submodel = i;
3618 if (loadmodel->brush.submodels)
3619 loadmodel->brush.submodels[i] = mod;
3621 bm = &mod->brushq1.submodels[i];
3623 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3624 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3626 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3627 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3630 mod->firstmodelsurface = bm->firstface;
3631 mod->nummodelsurfaces = bm->numfaces;
3633 // set node/leaf parents for this submodel
3634 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3636 // make the model surface list (used by shadowing/lighting)
3637 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3638 Mod_MakeSortedSurfaces(mod);
3640 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3641 // (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)
3642 VectorCopy(bm->mins, mod->normalmins);
3643 VectorCopy(bm->maxs, mod->normalmaxs);
3644 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3645 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3646 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3647 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3648 modelradius = modelyawradius + modelradius * modelradius;
3649 modelyawradius = sqrt(modelyawradius);
3650 modelradius = sqrt(modelradius);
3651 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3652 mod->yawmins[2] = mod->normalmins[2];
3653 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3654 mod->yawmaxs[2] = mod->normalmaxs[2];
3655 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3656 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3657 mod->radius = modelradius;
3658 mod->radius2 = modelradius * modelradius;
3660 // this gets altered below if sky or water is used
3661 mod->DrawSky = NULL;
3662 mod->DrawAddWaterPlanes = NULL;
3664 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3665 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3666 if (mod->nummodelsurfaces)
3668 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3669 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3671 if (j < mod->nummodelsurfaces)
3672 mod->DrawSky = R_Q1BSP_DrawSky;
3674 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3675 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION))
3677 if (j < mod->nummodelsurfaces)
3678 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3680 // build lightstyle update chains
3681 // (used to rapidly mark lightmapupdateflags on many surfaces
3682 // when d_lightstylevalue changes)
3683 memset(stylecounts, 0, sizeof(stylecounts));
3684 for (k = 0;k < mod->nummodelsurfaces;k++)
3686 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3687 for (j = 0;j < MAXLIGHTMAPS;j++)
3688 stylecounts[surface->lightmapinfo->styles[j]]++;
3690 mod->brushq1.num_lightstyles = 0;
3691 for (k = 0;k < 255;k++)
3695 styleinfo[mod->brushq1.num_lightstyles].style = k;
3696 styleinfo[mod->brushq1.num_lightstyles].value = 0;
3697 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3698 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3699 remapstyles[k] = mod->brushq1.num_lightstyles;
3700 mod->brushq1.num_lightstyles++;
3703 for (k = 0;k < mod->nummodelsurfaces;k++)
3705 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3706 for (j = 0;j < MAXLIGHTMAPS;j++)
3708 if (surface->lightmapinfo->styles[j] != 255)
3710 int r = remapstyles[surface->lightmapinfo->styles[j]];
3711 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3715 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3716 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3720 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3721 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3723 //mod->brushq1.num_visleafs = bm->visleafs;
3725 if (mod_q1bsp_polygoncollisions.integer)
3727 Mod_MakeCollisionBIH(mod, true);
3728 // point traces and contents checks still use the bsp tree
3729 mod->TraceLine = Mod_CollisionBIH_TraceLine;
3730 mod->TraceBox = Mod_CollisionBIH_TraceBox;
3733 // generate VBOs and other shared data before cloning submodels
3737 Mod_Q1BSP_LoadMapBrushes();
3738 //Mod_Q1BSP_ProcessLightList();
3742 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);
3745 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3749 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3756 in = (void *)(mod_base + l->fileofs);
3757 if (l->filelen % sizeof(*in))
3758 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3759 count = l->filelen / sizeof(*in);
3760 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3763 loadmodel->num = count;
3765 for (i = 0;i < count;i++, in++, out++)
3771 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3778 in = (void *)(mod_base + l->fileofs);
3779 if (l->filelen % sizeof(*in))
3780 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3781 count = l->filelen / sizeof(*in);
3782 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3785 loadmodel->num = count;
3787 for (i = 0;i < count;i++, in++, out++)
3793 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3800 in = (void *)(mod_base + l->fileofs);
3801 if (l->filelen % sizeof(*in))
3802 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3803 count = l->filelen / sizeof(*in);
3804 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3807 loadmodel->num = count;
3809 for (i = 0;i < count;i++, in++, out++)
3815 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3822 in = (void *)(mod_base + l->fileofs);
3823 if (l->filelen % sizeof(*in))
3824 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3825 count = l->filelen / sizeof(*in);
3826 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3829 loadmodel->num = count;
3831 for (i = 0;i < count;i++, in++, out++)
3837 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3844 in = (void *)(mod_base + l->fileofs);
3845 if (l->filelen % sizeof(*in))
3846 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3847 count = l->filelen / sizeof(*in);
3848 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3851 loadmodel->num = count;
3853 for (i = 0;i < count;i++, in++, out++)
3859 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3866 in = (void *)(mod_base + l->fileofs);
3867 if (l->filelen % sizeof(*in))
3868 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3869 count = l->filelen / sizeof(*in);
3870 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3873 loadmodel->num = count;
3875 for (i = 0;i < count;i++, in++, out++)
3881 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3888 in = (void *)(mod_base + l->fileofs);
3889 if (l->filelen % sizeof(*in))
3890 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3891 count = l->filelen / sizeof(*in);
3892 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3895 loadmodel->num = count;
3897 for (i = 0;i < count;i++, in++, out++)
3903 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3910 in = (void *)(mod_base + l->fileofs);
3911 if (l->filelen % sizeof(*in))
3912 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3913 count = l->filelen / sizeof(*in);
3914 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3917 loadmodel->num = count;
3919 for (i = 0;i < count;i++, in++, out++)
3925 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3932 in = (void *)(mod_base + l->fileofs);
3933 if (l->filelen % sizeof(*in))
3934 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3935 count = l->filelen / sizeof(*in);
3936 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3939 loadmodel->num = count;
3941 for (i = 0;i < count;i++, in++, out++)
3947 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3954 in = (void *)(mod_base + l->fileofs);
3955 if (l->filelen % sizeof(*in))
3956 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3957 count = l->filelen / sizeof(*in);
3958 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3961 loadmodel->num = count;
3963 for (i = 0;i < count;i++, in++, out++)
3969 static void Mod_Q2BSP_LoadEdges(lump_t *l)
3976 in = (void *)(mod_base + l->fileofs);
3977 if (l->filelen % sizeof(*in))
3978 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
3979 count = l->filelen / sizeof(*in);
3980 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3983 loadmodel->num = count;
3985 for (i = 0;i < count;i++, in++, out++)
3991 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
3998 in = (void *)(mod_base + l->fileofs);
3999 if (l->filelen % sizeof(*in))
4000 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4001 count = l->filelen / sizeof(*in);
4002 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4005 loadmodel->num = count;
4007 for (i = 0;i < count;i++, in++, out++)
4013 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4020 in = (void *)(mod_base + l->fileofs);
4021 if (l->filelen % sizeof(*in))
4022 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4023 count = l->filelen / sizeof(*in);
4024 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4027 loadmodel->num = count;
4029 for (i = 0;i < count;i++, in++, out++)
4035 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4042 in = (void *)(mod_base + l->fileofs);
4043 if (l->filelen % sizeof(*in))
4044 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4045 count = l->filelen / sizeof(*in);
4046 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4049 loadmodel->num = count;
4051 for (i = 0;i < count;i++, in++, out++)
4057 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4064 in = (void *)(mod_base + l->fileofs);
4065 if (l->filelen % sizeof(*in))
4066 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4067 count = l->filelen / sizeof(*in);
4068 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4071 loadmodel->num = count;
4073 for (i = 0;i < count;i++, in++, out++)
4079 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4086 in = (void *)(mod_base + l->fileofs);
4087 if (l->filelen % sizeof(*in))
4088 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4089 count = l->filelen / sizeof(*in);
4090 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4093 loadmodel->num = count;
4095 for (i = 0;i < count;i++, in++, out++)
4101 static void Mod_Q2BSP_LoadModels(lump_t *l)
4108 in = (void *)(mod_base + l->fileofs);
4109 if (l->filelen % sizeof(*in))
4110 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4111 count = l->filelen / sizeof(*in);
4112 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4115 loadmodel->num = count;
4117 for (i = 0;i < count;i++, in++, out++)
4123 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4126 q2dheader_t *header;
4128 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4130 mod->modeldatatypestring = "Q2BSP";
4132 mod->type = mod_brushq2;
4134 header = (q2dheader_t *)buffer;
4136 i = LittleLong(header->version);
4137 if (i != Q2BSPVERSION)
4138 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4140 mod_base = (unsigned char *)header;
4142 // swap all the lumps
4143 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4144 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4146 mod->brush.qw_md4sum = 0;
4147 mod->brush.qw_md4sum2 = 0;
4148 for (i = 0;i < Q2HEADER_LUMPS;i++)
4150 if (i == Q2LUMP_ENTITIES)
4152 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4153 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4155 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4158 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4159 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4160 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4161 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4162 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4163 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4164 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4165 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4166 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4167 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4168 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4169 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4170 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4171 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4172 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4173 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4174 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4175 // LordHavoc: must go last because this makes the submodels
4176 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4179 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4180 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4182 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4185 char key[128], value[MAX_INPUTLINE];
4187 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4188 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4189 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4192 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4193 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4194 loadmodel->brush.entities[l->filelen] = 0;
4195 data = loadmodel->brush.entities;
4196 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4197 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4198 loadmodel->brushq3.deluxemapping = false;
4199 if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4203 if (!COM_ParseToken_Simple(&data, false, false))
4205 if (com_token[0] == '}')
4206 break; // end of worldspawn
4207 if (com_token[0] == '_')
4208 strlcpy(key, com_token + 1, sizeof(key));
4210 strlcpy(key, com_token, sizeof(key));
4211 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4212 key[strlen(key)-1] = 0;
4213 if (!COM_ParseToken_Simple(&data, false, false))
4215 strlcpy(value, com_token, sizeof(value));
4216 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4218 #if _MSC_VER >= 1400
4219 #define sscanf sscanf_s
4222 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4223 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4225 VectorSet(v, 64, 64, 128);
4226 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4227 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]);
4228 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4229 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4232 else if (!strcmp("deluxeMaps", key))
4234 if (!strcmp(com_token, "1"))
4236 loadmodel->brushq3.deluxemapping = true;
4237 loadmodel->brushq3.deluxemapping_modelspace = true;
4239 else if (!strcmp(com_token, "2"))
4241 loadmodel->brushq3.deluxemapping = true;
4242 loadmodel->brushq3.deluxemapping_modelspace = false;
4249 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4255 in = (q3dtexture_t *)(mod_base + l->fileofs);
4256 if (l->filelen % sizeof(*in))
4257 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4258 count = l->filelen / sizeof(*in);
4259 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4261 loadmodel->data_textures = out;
4262 loadmodel->num_textures = count;
4263 loadmodel->num_texturesperskin = loadmodel->num_textures;
4265 for (i = 0;i < count;i++)
4267 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4268 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4269 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4272 if (cls.state == ca_dedicated)
4275 for (i = 0;i < count;i++, in++, out++)
4276 Mod_LoadTextureFromQ3Shader(out, out->name, true, true, TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS);
4279 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4285 in = (q3dplane_t *)(mod_base + l->fileofs);
4286 if (l->filelen % sizeof(*in))
4287 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4288 count = l->filelen / sizeof(*in);
4289 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4291 loadmodel->brush.data_planes = out;
4292 loadmodel->brush.num_planes = count;
4294 for (i = 0;i < count;i++, in++, out++)
4296 out->normal[0] = LittleFloat(in->normal[0]);
4297 out->normal[1] = LittleFloat(in->normal[1]);
4298 out->normal[2] = LittleFloat(in->normal[2]);
4299 out->dist = LittleFloat(in->dist);
4304 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4307 q3mbrushside_t *out;
4310 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4311 if (l->filelen % sizeof(*in))
4312 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4313 count = l->filelen / sizeof(*in);
4314 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4316 loadmodel->brush.data_brushsides = out;
4317 loadmodel->brush.num_brushsides = count;
4319 for (i = 0;i < count;i++, in++, out++)
4321 n = LittleLong(in->planeindex);
4322 if (n < 0 || n >= loadmodel->brush.num_planes)
4323 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4324 out->plane = loadmodel->brush.data_planes + n;
4325 n = LittleLong(in->textureindex);
4326 if (n < 0 || n >= loadmodel->num_textures)
4327 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4328 out->texture = loadmodel->data_textures + n;
4332 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4334 q3dbrushside_ig_t *in;
4335 q3mbrushside_t *out;
4338 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4339 if (l->filelen % sizeof(*in))
4340 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4341 count = l->filelen / sizeof(*in);
4342 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4344 loadmodel->brush.data_brushsides = out;
4345 loadmodel->brush.num_brushsides = count;
4347 for (i = 0;i < count;i++, in++, out++)
4349 n = LittleLong(in->planeindex);
4350 if (n < 0 || n >= loadmodel->brush.num_planes)
4351 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4352 out->plane = loadmodel->brush.data_planes + n;
4353 n = LittleLong(in->textureindex);
4354 if (n < 0 || n >= loadmodel->num_textures)
4355 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4356 out->texture = loadmodel->data_textures + n;
4360 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4364 int i, j, n, c, count, maxplanes, q3surfaceflags;
4365 colplanef_t *planes;
4367 in = (q3dbrush_t *)(mod_base + l->fileofs);
4368 if (l->filelen % sizeof(*in))
4369 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4370 count = l->filelen / sizeof(*in);
4371 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4373 loadmodel->brush.data_brushes = out;
4374 loadmodel->brush.num_brushes = count;
4379 for (i = 0;i < count;i++, in++, out++)
4381 n = LittleLong(in->firstbrushside);
4382 c = LittleLong(in->numbrushsides);
4383 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4384 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4385 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4386 out->numbrushsides = c;
4387 n = LittleLong(in->textureindex);
4388 if (n < 0 || n >= loadmodel->num_textures)
4389 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4390 out->texture = loadmodel->data_textures + n;
4392 // make a list of mplane_t structs to construct a colbrush from
4393 if (maxplanes < out->numbrushsides)
4395 maxplanes = out->numbrushsides;
4398 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4401 for (j = 0;j < out->numbrushsides;j++)
4403 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4404 planes[j].dist = out->firstbrushside[j].plane->dist;
4405 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4406 planes[j].texture = out->firstbrushside[j].texture;
4407 q3surfaceflags |= planes[j].q3surfaceflags;
4409 // make the colbrush from the planes
4410 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4412 // this whole loop can take a while (e.g. on redstarrepublic4)
4413 CL_KeepaliveMessage(false);
4419 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4425 in = (q3deffect_t *)(mod_base + l->fileofs);
4426 if (l->filelen % sizeof(*in))
4427 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4428 count = l->filelen / sizeof(*in);
4429 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4431 loadmodel->brushq3.data_effects = out;
4432 loadmodel->brushq3.num_effects = count;
4434 for (i = 0;i < count;i++, in++, out++)
4436 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4437 n = LittleLong(in->brushindex);
4438 if (n >= loadmodel->brush.num_brushes)
4440 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4443 out->brushindex = n;
4444 out->unknown = LittleLong(in->unknown);
4448 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4453 in = (q3dvertex_t *)(mod_base + l->fileofs);
4454 if (l->filelen % sizeof(*in))
4455 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4456 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4457 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4458 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4459 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4460 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4461 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4463 for (i = 0;i < count;i++, in++)
4465 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4466 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4467 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4468 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4469 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4470 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4471 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4472 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4473 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4474 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4475 // svector/tvector are calculated later in face loading
4476 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4477 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4478 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4479 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4483 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4489 in = (int *)(mod_base + l->fileofs);
4490 if (l->filelen % sizeof(int[3]))
4491 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4492 count = l->filelen / sizeof(*in);
4494 if(!loadmodel->brushq3.num_vertices)
4497 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4498 loadmodel->brushq3.num_triangles = 0;
4502 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4503 loadmodel->brushq3.num_triangles = count / 3;
4504 loadmodel->brushq3.data_element3i = out;
4506 for (i = 0;i < count;i++, in++, out++)
4508 *out = LittleLong(*in);
4509 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4511 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4517 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4519 q3dlightmap_t *input_pointer;
4520 int i, j, k, count, power, power2, endlightmap, mergewidth, mergeheight;
4523 unsigned char *convertedpixels;
4524 char mapname[MAX_QPATH];
4525 int size, bytesperpixel, rgbmap[3];
4527 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4529 // defaults for q3bsp
4536 loadmodel->brushq3.lightmapsize = 128;
4538 if (cls.state == ca_dedicated)
4541 if(mod_q3bsp_nolightmaps.integer)
4547 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4548 if (developer_loading.integer)
4549 Con_Printf("Using internal lightmaps\n");
4550 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4551 if (l->filelen % sizeof(*input_pointer))
4552 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4553 count = l->filelen / sizeof(*input_pointer);
4554 for(i = 0; i < count; ++i)
4555 inpixels[i] = input_pointer[i].rgb;
4559 // no internal lightmaps
4560 // try external lightmaps
4561 if (developer_loading.integer)
4562 Con_Printf("Using external lightmaps\n");
4563 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4564 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false);
4568 // using EXTERNAL lightmaps instead
4569 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4571 Mem_Free(inpixels[0]);
4572 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4582 for(count = 1; ; ++count)
4584 inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false);
4585 if(!inpixels[count])
4586 break; // we got all of them
4587 if(image_width != size || image_height != size)
4589 for(i = 0; i <= count; ++i)
4590 Mem_Free(inpixels[i]);
4591 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4596 convertedpixels = (unsigned char *) Mem_Alloc(tempmempool, size*size*4);
4597 loadmodel->brushq3.lightmapsize = size;
4598 loadmodel->brushq3.num_originallightmaps = count;
4600 // now check the surfaces to see if any of them index an odd numbered
4601 // lightmap, if so this is not a deluxemapped bsp file
4603 // also check what lightmaps are actually used, because q3map2 sometimes
4604 // (always?) makes an unused one at the end, which
4605 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4606 // reason when only one lightmap is used, which can throw off the
4607 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4608 // to see if the second lightmap is blank, if so it is not deluxemapped.
4609 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4610 // in Mod_Q3BSP_LoadEntities was failed
4611 if (!loadmodel->brushq3.deluxemapping)
4613 loadmodel->brushq3.deluxemapping = !(count & 1);
4614 loadmodel->brushq3.deluxemapping_modelspace = true;
4616 if (loadmodel->brushq3.deluxemapping)
4618 int facecount = faceslump->filelen / sizeof(q3dface_t);
4619 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4620 for (i = 0;i < facecount;i++)
4622 j = LittleLong(faces[i].lightmapindex);
4625 endlightmap = max(endlightmap, j + 1);
4626 if ((j & 1) || j + 1 >= count)
4628 loadmodel->brushq3.deluxemapping = false;
4635 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4636 // reason when only one lightmap is used, which can throw off the
4637 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4638 // to see if the second lightmap is blank, if so it is not deluxemapped.
4640 // further research has shown q3map2 sometimes creates a deluxemap and two
4641 // blank lightmaps, which must be handled properly as well
4642 if (endlightmap == 1 && count > 1)
4645 for (i = 0;i < size*size;i++)
4647 if (c[bytesperpixel*i + rgbmap[0]])
4649 if (c[bytesperpixel*i + rgbmap[1]])
4651 if (c[bytesperpixel*i + rgbmap[2]])
4656 // all pixels in the unused lightmap were black...
4657 loadmodel->brushq3.deluxemapping = false;
4662 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4664 // figure out what the most reasonable merge power is within limits
4666 loadmodel->brushq3.num_lightmapmergepower = 0;
4668 for(i = 0; (128 << i) < size; ++i)
4670 // i is now 0 for 128, 1 for 256, etc
4672 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++)
4673 loadmodel->brushq3.num_lightmapmergepower = power;
4675 loadmodel->brushq3.num_lightmapmerge = 1 << loadmodel->brushq3.num_lightmapmergepower;
4677 loadmodel->brushq3.num_mergedlightmaps = ((count >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) + (1 << (loadmodel->brushq3.num_lightmapmergepower * 2)) - 1) >> (loadmodel->brushq3.num_lightmapmergepower * 2);
4678 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4679 if (loadmodel->brushq3.deluxemapping)
4680 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4682 // allocate a texture pool if we need it
4683 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4684 loadmodel->texturepool = R_AllocTexturePool();
4686 power = loadmodel->brushq3.num_lightmapmergepower;
4688 for (i = 0;i < count;i++)
4690 // figure out which merged lightmap texture this fits into
4691 int lightmapindex = i >> (loadmodel->brushq3.deluxemapping + power2);
4692 for (k = 0;k < size*size;k++)
4694 convertedpixels[k*4+0] = inpixels[i][k*bytesperpixel+rgbmap[0]];
4695 convertedpixels[k*4+1] = inpixels[i][k*bytesperpixel+rgbmap[1]];
4696 convertedpixels[k*4+2] = inpixels[i][k*bytesperpixel+rgbmap[2]];
4697 convertedpixels[k*4+3] = 255;
4699 if (loadmodel->brushq3.num_lightmapmergepower > 0)
4701 // if the lightmap has not been allocated yet, create it
4702 if (!loadmodel->brushq3.data_lightmaps[lightmapindex])
4704 // create a lightmap only as large as necessary to hold the
4705 // remaining size*size blocks
4706 // if there are multiple merged lightmap textures then they will
4707 // all be full size except the last one which may be smaller
4708 // because it only needs to the remaining blocks, and it will often
4709 // be odd sizes like 2048x512 due to only being 25% full or so.
4710 j = (count >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) - (lightmapindex << power2);
4711 for (mergewidth = 1;mergewidth < j && mergewidth < (1 << power);mergewidth *= 2)
4713 for (mergeheight = 1;mergewidth*mergeheight < j && mergeheight < (1 << power);mergeheight *= 2)
4715 if (developer_loading.integer)
4716 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);
4717 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);
4718 if (loadmodel->brushq3.data_deluxemaps)
4719 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);
4721 mergewidth = R_TextureWidth(loadmodel->brushq3.data_lightmaps[lightmapindex]) / size;
4722 mergeheight = R_TextureHeight(loadmodel->brushq3.data_lightmaps[lightmapindex]) / size;
4723 j = (i >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) & ((1 << power2) - 1);
4724 if (loadmodel->brushq3.deluxemapping && (i & 1))
4725 R_UpdateTexture(loadmodel->brushq3.data_deluxemaps[lightmapindex], convertedpixels, (j % mergewidth) * size, (j / mergewidth) * size, size, size);
4727 R_UpdateTexture(loadmodel->brushq3.data_lightmaps [lightmapindex], convertedpixels, (j % mergewidth) * size, (j / mergewidth) * size, size, size);
4731 // figure out which merged lightmap texture this fits into
4732 if (loadmodel->brushq3.deluxemapping && (i & 1))
4733 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);
4735 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);
4739 Mem_Free(convertedpixels);
4742 for(i = 0; i < count; ++i)
4743 Mem_Free(inpixels[i]);
4747 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
4752 *collisionstride = stride;
4755 cnt = (num_triangles + stride - 1) / stride;
4756 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
4757 for(j = 0; j < cnt; ++j)
4759 mins = &((*collisionbbox6f)[6 * j + 0]);
4760 maxs = &((*collisionbbox6f)[6 * j + 3]);
4761 for(k = 0; k < stride; ++k)
4763 tri = j * stride + k;
4764 if(tri >= num_triangles)
4766 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
4767 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
4768 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
4769 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
4770 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
4771 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
4772 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
4773 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
4774 if(vert[0] < mins[0]) mins[0] = vert[0];
4775 if(vert[1] < mins[1]) mins[1] = vert[1];
4776 if(vert[2] < mins[2]) mins[2] = vert[2];
4777 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4778 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4779 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4780 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
4781 if(vert[0] < mins[0]) mins[0] = vert[0];
4782 if(vert[1] < mins[1]) mins[1] = vert[1];
4783 if(vert[2] < mins[2]) mins[2] = vert[2];
4784 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4785 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4786 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4791 *collisionbbox6f = NULL;
4794 typedef struct patchtess_s
4798 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
4801 float *originalvertex3f;
4804 #define PATCHTESS_SAME_LODGROUP(a,b) \
4806 (a).lodgroup[0] == (b).lodgroup[0] && \
4807 (a).lodgroup[1] == (b).lodgroup[1] && \
4808 (a).lodgroup[2] == (b).lodgroup[2] && \
4809 (a).lodgroup[3] == (b).lodgroup[3] && \
4810 (a).lodgroup[4] == (b).lodgroup[4] && \
4811 (a).lodgroup[5] == (b).lodgroup[5] \
4814 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4816 q3dface_t *in, *oldin;
4817 msurface_t *out, *oldout;
4818 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;
4819 float lightmaptcbase[2], lightmaptcscale[2];
4820 //int *originalelement3i;
4821 //int *originalneighbor3i;
4822 float *originalvertex3f;
4823 //float *originalsvector3f;
4824 //float *originaltvector3f;
4825 float *originalnormal3f;
4826 float *originalcolor4f;
4827 float *originaltexcoordtexture2f;
4828 float *originaltexcoordlightmap2f;
4829 float *surfacecollisionvertex3f;
4830 int *surfacecollisionelement3i;
4832 patchtess_t *patchtess = NULL;
4833 int patchtesscount = 0;
4836 in = (q3dface_t *)(mod_base + l->fileofs);
4837 if (l->filelen % sizeof(*in))
4838 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4839 count = l->filelen / sizeof(*in);
4840 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4842 loadmodel->data_surfaces = out;
4843 loadmodel->num_surfaces = count;
4846 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
4854 for (;i < count;i++, in++, out++)
4856 // check face type first
4857 type = LittleLong(in->type);
4858 if (type != Q3FACETYPE_FLAT
4859 && type != Q3FACETYPE_PATCH
4860 && type != Q3FACETYPE_MESH
4861 && type != Q3FACETYPE_FLARE)
4863 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4867 n = LittleLong(in->textureindex);
4868 if (n < 0 || n >= loadmodel->num_textures)
4870 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4873 out->texture = loadmodel->data_textures + n;
4874 n = LittleLong(in->effectindex);
4875 if (n < -1 || n >= loadmodel->brushq3.num_effects)
4877 if (developer_extra.integer)
4878 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4884 out->effect = loadmodel->brushq3.data_effects + n;
4886 if (cls.state != ca_dedicated)
4888 out->lightmaptexture = NULL;
4889 out->deluxemaptexture = r_texture_blanknormalmap;
4890 n = LittleLong(in->lightmapindex);
4893 else if (n >= loadmodel->brushq3.num_originallightmaps)
4895 if(loadmodel->brushq3.num_originallightmaps != 0)
4896 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
4901 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> (loadmodel->brushq3.num_lightmapmergepower * 2 + loadmodel->brushq3.deluxemapping)];
4902 if (loadmodel->brushq3.deluxemapping)
4903 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> (loadmodel->brushq3.num_lightmapmergepower * 2 + loadmodel->brushq3.deluxemapping)];
4907 firstvertex = LittleLong(in->firstvertex);
4908 numvertices = LittleLong(in->numvertices);
4909 firstelement = LittleLong(in->firstelement);
4910 numtriangles = LittleLong(in->numelements) / 3;
4911 if (numtriangles * 3 != LittleLong(in->numelements))
4913 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));
4916 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4918 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);
4921 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4923 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);
4928 case Q3FACETYPE_FLAT:
4929 case Q3FACETYPE_MESH:
4930 // no processing necessary
4932 case Q3FACETYPE_PATCH:
4933 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4934 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4935 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))
4937 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
4940 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4942 // convert patch to Q3FACETYPE_MESH
4943 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4944 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4945 // bound to user settings
4946 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4947 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4948 // bound to sanity settings
4949 xtess = bound(0, xtess, 1024);
4950 ytess = bound(0, ytess, 1024);
4952 // lower quality collision patches! Same procedure as before, but different cvars
4953 // convert patch to Q3FACETYPE_MESH
4954 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4955 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4956 // bound to user settings
4957 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
4958 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
4959 // bound to sanity settings
4960 cxtess = bound(0, cxtess, 1024);
4961 cytess = bound(0, cytess, 1024);
4963 // store it for the LOD grouping step
4964 patchtess[patchtesscount].info.xsize = patchsize[0];
4965 patchtess[patchtesscount].info.ysize = patchsize[1];
4966 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
4967 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
4968 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
4969 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
4971 patchtess[patchtesscount].surface_id = i;
4972 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
4973 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
4974 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
4975 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
4976 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
4977 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
4978 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
4981 case Q3FACETYPE_FLARE:
4982 if (developer_extra.integer)
4983 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
4987 out->num_vertices = numvertices;
4988 out->num_triangles = numtriangles;
4989 meshvertices += out->num_vertices;
4990 meshtriangles += out->num_triangles;
4993 // Fix patches tesselations so that they make no seams
4997 for(i = 0; i < patchtesscount; ++i)
4999 for(j = i+1; j < patchtesscount; ++j)
5001 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5004 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5011 // Calculate resulting number of triangles
5012 collisionvertices = 0;
5013 collisiontriangles = 0;
5014 for(i = 0; i < patchtesscount; ++i)
5016 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5017 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5018 numvertices = finalwidth * finalheight;
5019 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5021 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5022 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5023 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5024 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5026 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5027 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5028 numvertices = finalwidth * finalheight;
5029 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5031 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5032 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5033 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5034 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5040 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5041 if (collisiontriangles)
5043 loadmodel->brush.data_collisionvertex3f = Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5044 loadmodel->brush.data_collisionelement3i = Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5048 collisionvertices = 0;
5049 collisiontriangles = 0;
5050 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5052 if (out->num_vertices < 3 || out->num_triangles < 1)
5055 type = LittleLong(in->type);
5056 firstvertex = LittleLong(in->firstvertex);
5057 firstelement = LittleLong(in->firstelement);
5058 out->num_firstvertex = meshvertices;
5059 out->num_firsttriangle = meshtriangles;
5060 out->num_firstcollisiontriangle = collisiontriangles;
5063 case Q3FACETYPE_FLAT:
5064 case Q3FACETYPE_MESH:
5065 // no processing necessary, except for lightmap merging
5066 for (j = 0;j < out->num_vertices;j++)
5068 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5069 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5070 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5071 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5072 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5073 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5074 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5075 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5076 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5077 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5078 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5079 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5080 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5081 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5083 for (j = 0;j < out->num_triangles*3;j++)
5084 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5086 case Q3FACETYPE_PATCH:
5087 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5088 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5089 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5090 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5091 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5092 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5093 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5095 xtess = ytess = cxtess = cytess = -1;
5096 for(j = 0; j < patchtesscount; ++j)
5097 if(patchtess[j].surface_id == i)
5099 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5100 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5101 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5102 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5107 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5108 xtess = ytess = cxtess = cytess = 0;
5111 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5112 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5113 finalvertices = finalwidth * finalheight;
5114 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5115 type = Q3FACETYPE_MESH;
5116 // generate geometry
5117 // (note: normals are skipped because they get recalculated)
5118 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5119 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5120 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5121 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5122 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5123 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5125 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);
5127 if (developer_extra.integer)
5129 if (out->num_triangles < finaltriangles)
5130 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);
5132 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);
5134 // q3map does not put in collision brushes for curves... ugh
5135 // build the lower quality collision geometry
5136 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5137 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5138 finalvertices = finalwidth * finalheight;
5139 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5141 // legacy collision geometry implementation
5142 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5143 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5144 out->num_collisionvertices = finalvertices;
5145 out->num_collisiontriangles = finaltriangles;
5146 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5147 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5149 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5150 Mod_SnapVertices(3, out->num_collisionvertices, out->deprecatedq3data_collisionvertex3f, 1);
5152 oldnumtriangles = out->num_triangles;
5153 oldnumtriangles2 = out->num_collisiontriangles;
5154 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->num_collisiontriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5156 // now optimize the collision mesh by finding triangle bboxes...
5157 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5158 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);
5160 // store collision geometry for BIH collision tree
5161 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5162 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5163 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5164 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5165 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5166 oldnumtriangles = out->num_triangles;
5167 oldnumtriangles2 = out->num_collisiontriangles;
5168 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->num_collisiontriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5170 if (developer_extra.integer)
5171 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);
5173 collisionvertices += finalvertices;
5174 collisiontriangles += out->num_collisiontriangles;
5179 meshvertices += out->num_vertices;
5180 meshtriangles += out->num_triangles;
5181 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5182 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)
5184 if (invalidelements)
5186 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);
5187 for (j = 0;j < out->num_triangles * 3;j++)
5189 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5190 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)
5191 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5195 // calculate a bounding box
5196 VectorClear(out->mins);
5197 VectorClear(out->maxs);
5198 if (out->num_vertices)
5200 if (cls.state != ca_dedicated && out->lightmaptexture)
5202 // figure out which part of the merged lightmap this fits into
5203 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5204 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5205 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5206 lightmapindex &= mergewidth * mergeheight - 1;
5207 lightmaptcscale[0] = 1.0f / mergewidth;
5208 lightmaptcscale[1] = 1.0f / mergeheight;
5209 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5210 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5211 // modify the lightmap texcoords to match this region of the merged lightmap
5212 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5214 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5215 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5218 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5219 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5220 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5222 out->mins[0] = min(out->mins[0], v[0]);
5223 out->maxs[0] = max(out->maxs[0], v[0]);
5224 out->mins[1] = min(out->mins[1], v[1]);
5225 out->maxs[1] = max(out->maxs[1], v[1]);
5226 out->mins[2] = min(out->mins[2], v[2]);
5227 out->maxs[2] = max(out->maxs[2], v[2]);
5229 out->mins[0] -= 1.0f;
5230 out->mins[1] -= 1.0f;
5231 out->mins[2] -= 1.0f;
5232 out->maxs[0] += 1.0f;
5233 out->maxs[1] += 1.0f;
5234 out->maxs[2] += 1.0f;
5236 // set lightmap styles for consistency with q1bsp
5237 //out->lightmapinfo->styles[0] = 0;
5238 //out->lightmapinfo->styles[1] = 255;
5239 //out->lightmapinfo->styles[2] = 255;
5240 //out->lightmapinfo->styles[3] = 255;
5245 for (;i < count;i++, out++)
5247 if(out->num_vertices && out->num_triangles)
5249 if(out->num_vertices == 0)
5250 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d has no vertices, ignoring\n", i);
5251 if(out->num_triangles == 0)
5252 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d has no triangles, ignoring\n", i);
5255 // for per pixel lighting
5256 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);
5258 // generate ushort elements array if possible
5259 if (loadmodel->surfmesh.data_element3s)
5260 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5261 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5263 // free the no longer needed vertex data
5264 loadmodel->brushq3.num_vertices = 0;
5265 if (loadmodel->brushq3.data_vertex3f)
5266 Mem_Free(loadmodel->brushq3.data_vertex3f);
5267 loadmodel->brushq3.data_vertex3f = NULL;
5268 loadmodel->brushq3.data_normal3f = NULL;
5269 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5270 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5271 loadmodel->brushq3.data_color4f = NULL;
5272 // free the no longer needed triangle data
5273 loadmodel->brushq3.num_triangles = 0;
5274 if (loadmodel->brushq3.data_element3i)
5275 Mem_Free(loadmodel->brushq3.data_element3i);
5276 loadmodel->brushq3.data_element3i = NULL;
5279 Mem_Free(patchtess);
5282 static void Mod_Q3BSP_LoadModels(lump_t *l)
5286 int i, j, n, c, count;
5288 in = (q3dmodel_t *)(mod_base + l->fileofs);
5289 if (l->filelen % sizeof(*in))
5290 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5291 count = l->filelen / sizeof(*in);
5292 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5294 loadmodel->brushq3.data_models = out;
5295 loadmodel->brushq3.num_models = count;
5297 for (i = 0;i < count;i++, in++, out++)
5299 for (j = 0;j < 3;j++)
5301 out->mins[j] = LittleFloat(in->mins[j]);
5302 out->maxs[j] = LittleFloat(in->maxs[j]);
5304 n = LittleLong(in->firstface);
5305 c = LittleLong(in->numfaces);
5306 if (n < 0 || n + c > loadmodel->num_surfaces)
5307 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5310 n = LittleLong(in->firstbrush);
5311 c = LittleLong(in->numbrushes);
5312 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5313 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5314 out->firstbrush = n;
5315 out->numbrushes = c;
5319 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5325 in = (int *)(mod_base + l->fileofs);
5326 if (l->filelen % sizeof(*in))
5327 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5328 count = l->filelen / sizeof(*in);
5329 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5331 loadmodel->brush.data_leafbrushes = out;
5332 loadmodel->brush.num_leafbrushes = count;
5334 for (i = 0;i < count;i++, in++, out++)
5336 n = LittleLong(*in);
5337 if (n < 0 || n >= loadmodel->brush.num_brushes)
5338 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5343 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5349 in = (int *)(mod_base + l->fileofs);
5350 if (l->filelen % sizeof(*in))
5351 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5352 count = l->filelen / sizeof(*in);
5353 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5355 loadmodel->brush.data_leafsurfaces = out;
5356 loadmodel->brush.num_leafsurfaces = count;
5358 for (i = 0;i < count;i++, in++, out++)
5360 n = LittleLong(*in);
5361 if (n < 0 || n >= loadmodel->num_surfaces)
5362 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5367 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5371 int i, j, n, c, count;
5373 in = (q3dleaf_t *)(mod_base + l->fileofs);
5374 if (l->filelen % sizeof(*in))
5375 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5376 count = l->filelen / sizeof(*in);
5377 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5379 loadmodel->brush.data_leafs = out;
5380 loadmodel->brush.num_leafs = count;
5382 for (i = 0;i < count;i++, in++, out++)
5386 out->clusterindex = LittleLong(in->clusterindex);
5387 out->areaindex = LittleLong(in->areaindex);
5388 for (j = 0;j < 3;j++)
5390 // yes the mins/maxs are ints
5391 out->mins[j] = LittleLong(in->mins[j]) - 1;
5392 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5394 n = LittleLong(in->firstleafface);
5395 c = LittleLong(in->numleaffaces);
5396 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5397 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5398 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5399 out->numleafsurfaces = c;
5400 n = LittleLong(in->firstleafbrush);
5401 c = LittleLong(in->numleafbrushes);
5402 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5403 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5404 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5405 out->numleafbrushes = c;
5409 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5415 in = (q3dnode_t *)(mod_base + l->fileofs);
5416 if (l->filelen % sizeof(*in))
5417 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5418 count = l->filelen / sizeof(*in);
5419 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5421 loadmodel->brush.data_nodes = out;
5422 loadmodel->brush.num_nodes = count;
5424 for (i = 0;i < count;i++, in++, out++)
5427 n = LittleLong(in->planeindex);
5428 if (n < 0 || n >= loadmodel->brush.num_planes)
5429 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5430 out->plane = loadmodel->brush.data_planes + n;
5431 for (j = 0;j < 2;j++)
5433 n = LittleLong(in->childrenindex[j]);
5436 if (n >= loadmodel->brush.num_nodes)
5437 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5438 out->children[j] = loadmodel->brush.data_nodes + n;
5443 if (n >= loadmodel->brush.num_leafs)
5444 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5445 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5448 for (j = 0;j < 3;j++)
5450 // yes the mins/maxs are ints
5451 out->mins[j] = LittleLong(in->mins[j]) - 1;
5452 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5456 // set the parent pointers
5457 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5460 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5463 q3dlightgrid_t *out;
5466 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5467 if (l->filelen % sizeof(*in))
5468 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5469 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5470 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5471 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5472 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5473 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5474 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5475 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5476 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5477 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5478 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5479 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5480 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5481 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5482 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]);
5483 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]);
5485 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5488 if (l->filelen < count * (int)sizeof(*in))
5490 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]);
5491 return; // ignore the grid if we cannot understand it
5493 if (l->filelen != count * (int)sizeof(*in))
5494 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5495 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5496 loadmodel->brushq3.data_lightgrid = out;
5497 loadmodel->brushq3.num_lightgrid = count;
5498 // no swapping or validation necessary
5499 memcpy(out, in, count * (int)sizeof(*out));
5503 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5508 if (l->filelen == 0)
5511 // unvised maps often have cluster indices even without pvs, so check
5512 // leafs to find real number of clusters
5513 loadmodel->brush.num_pvsclusters = 1;
5514 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5515 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5518 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5519 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5520 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5521 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5525 in = (q3dpvs_t *)(mod_base + l->fileofs);
5527 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5529 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5530 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5531 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5532 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5533 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5534 if (l->filelen < totalchains + (int)sizeof(*in))
5535 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);
5537 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5538 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5541 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5543 int i, j, k, index[3];
5544 float transformed[3], blend1, blend2, blend, stylescale;
5545 q3dlightgrid_t *a, *s;
5547 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5548 stylescale = r_refdef.scene.rtlightstylevalue[0];
5550 if (!model->brushq3.num_lightgrid)
5552 ambientcolor[0] = stylescale;
5553 ambientcolor[1] = stylescale;
5554 ambientcolor[2] = stylescale;
5558 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5559 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5560 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5561 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5562 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5563 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5564 index[0] = (int)floor(transformed[0]);
5565 index[1] = (int)floor(transformed[1]);
5566 index[2] = (int)floor(transformed[2]);
5567 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5569 // now lerp the values
5570 VectorClear(diffusenormal);
5571 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5572 for (k = 0;k < 2;k++)
5574 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5575 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5577 for (j = 0;j < 2;j++)
5579 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5580 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5582 for (i = 0;i < 2;i++)
5584 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5585 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5587 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5588 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5589 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5590 // this uses the mod_md3_sin table because the values are
5591 // already in the 0-255 range, the 64+ bias fetches a cosine
5592 // instead of a sine value
5593 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5594 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5595 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5596 //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)));
5601 // normalize the light direction before turning
5602 VectorNormalize(diffusenormal);
5603 //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]);
5606 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5609 double midf, mid[3];
5615 // find the point distances
5616 mplane_t *plane = node->plane;
5617 if (plane->type < 3)
5619 t1 = p1[plane->type] - plane->dist;
5620 t2 = p2[plane->type] - plane->dist;
5624 t1 = DotProduct (plane->normal, p1) - plane->dist;
5625 t2 = DotProduct (plane->normal, p2) - plane->dist;
5632 node = node->children[1];
5641 node = node->children[0];
5647 midf = t1 / (t1 - t2);
5648 VectorLerp(p1, midf, p2, mid);
5650 // recurse both sides, front side first
5651 // return 2 if empty is followed by solid (hit something)
5652 // do not return 2 if both are solid or both empty,
5653 // or if start is solid and end is empty
5654 // as these degenerate cases usually indicate the eye is in solid and
5655 // should see the target point anyway
5656 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
5659 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5664 return ((mleaf_t *)node)->clusterindex < 0;
5667 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5669 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
5672 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
5673 return trace.fraction == 1;
5677 double tracestart[3], traceend[3];
5678 VectorCopy(start, tracestart);
5679 VectorCopy(end, traceend);
5680 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
5684 static void Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const vec3_t point)
5686 const bih_leaf_t *leaf;
5687 const bih_node_t *node;
5688 const colbrushf_t *brush;
5690 while (nodenum >= 0)
5692 node = model->collision_bih.nodes + nodenum;
5693 axis = node->type - BIH_SPLITX;
5694 if (point[axis] <= node->backmax)
5696 if (point[axis] >= node->frontmin)
5697 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, node->front, point);
5698 nodenum = node->back;
5700 else if (point[axis] >= node->frontmin)
5701 nodenum = node->front;
5702 else // no overlap with either child? just return
5705 if (!model->collision_bih.leafs)
5707 leaf = model->collision_bih.leafs + (-1-nodenum);
5712 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5713 Collision_TracePointBrushFloat(trace, point, brush);
5716 // collision triangle - skipped because they have no volume
5719 // render triangle - skipped because they have no volume
5726 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)
5728 const bih_leaf_t *leaf;
5729 const bih_node_t *node;
5730 const colbrushf_t *brush;
5732 const texture_t *texture;
5746 segmentmins[0] = min(start[0], end[0]);
5747 segmentmins[1] = min(start[1], end[1]);
5748 segmentmins[2] = min(start[2], end[2]);
5749 segmentmaxs[0] = max(start[0], end[0]);
5750 segmentmaxs[1] = max(start[1], end[1]);
5751 segmentmaxs[2] = max(start[2], end[2]);
5752 while (nodenum >= 0)
5754 node = model->collision_bih.nodes + nodenum;
5756 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
5759 axis = node->type - BIH_SPLITX;
5761 if (segmentmins[axis] <= node->backmax)
5763 if (segmentmaxs[axis] >= node->frontmin)
5764 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5765 nodenum = node->back;
5767 else if (segmentmaxs[axis] >= node->frontmin)
5768 nodenum = node->front;
5770 return; // trace falls between children
5772 frontdist1 = start[axis] - node->backmax;
5773 frontdist2 = end[axis] - node->backmax;
5774 backdist1 = start[axis] - node->frontmin;
5775 backdist2 = end[axis] - node->frontmin;
5788 // start end START END
5789 nodenum = node->front;
5792 // START end START END
5793 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5794 VectorLerp(start, frontfrac, end, clipped[0]);
5796 segmentmins[0] = min(start[0], end[0]);
5797 segmentmins[1] = min(start[1], end[1]);
5798 segmentmins[2] = min(start[2], end[2]);
5799 segmentmaxs[0] = max(start[0], end[0]);
5800 segmentmaxs[1] = max(start[1], end[1]);
5801 segmentmaxs[2] = max(start[2], end[2]);
5802 nodenum = node->front;
5805 // start END START END
5806 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5807 VectorLerp(start, frontfrac, end, clipped[0]);
5809 segmentmins[0] = min(start[0], end[0]);
5810 segmentmins[1] = min(start[1], end[1]);
5811 segmentmins[2] = min(start[2], end[2]);
5812 segmentmaxs[0] = max(start[0], end[0]);
5813 segmentmaxs[1] = max(start[1], end[1]);
5814 segmentmaxs[2] = max(start[2], end[2]);
5815 nodenum = node->front;
5818 // START END START END
5819 return; // line falls in gap between children
5821 // start end start END
5822 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5823 backfrac = backdist1 / (backdist1 - backdist2);
5824 VectorLerp(start, backfrac, end, clipped[0]);
5826 segmentmins[0] = min(start[0], end[0]);
5827 segmentmins[1] = min(start[1], end[1]);
5828 segmentmins[2] = min(start[2], end[2]);
5829 segmentmaxs[0] = max(start[0], end[0]);
5830 segmentmaxs[1] = max(start[1], end[1]);
5831 segmentmaxs[2] = max(start[2], end[2]);
5832 nodenum = node->back;
5835 // START end start END
5836 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5837 VectorLerp(start, frontfrac, end, clipped[1]);
5838 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5839 backfrac = backdist1 / (backdist1 - backdist2);
5840 VectorLerp(start, backfrac, end, clipped[0]);
5842 segmentmins[0] = min(start[0], end[0]);
5843 segmentmins[1] = min(start[1], end[1]);
5844 segmentmins[2] = min(start[2], end[2]);
5845 segmentmaxs[0] = max(start[0], end[0]);
5846 segmentmaxs[1] = max(start[1], end[1]);
5847 segmentmaxs[2] = max(start[2], end[2]);
5848 nodenum = node->back;
5851 // start END start END
5852 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5853 VectorLerp(start, frontfrac, end, clipped[1]);
5854 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5855 backfrac = backdist1 / (backdist1 - backdist2);
5856 VectorLerp(start, backfrac, end, clipped[0]);
5858 segmentmins[0] = min(start[0], end[0]);
5859 segmentmins[1] = min(start[1], end[1]);
5860 segmentmins[2] = min(start[2], end[2]);
5861 segmentmaxs[0] = max(start[0], end[0]);
5862 segmentmaxs[1] = max(start[1], end[1]);
5863 segmentmaxs[2] = max(start[2], end[2]);
5864 nodenum = node->back;
5867 // START END start END
5868 backfrac = backdist1 / (backdist1 - backdist2);
5869 VectorLerp(start, backfrac, end, clipped[0]);
5871 segmentmins[0] = min(start[0], end[0]);
5872 segmentmins[1] = min(start[1], end[1]);
5873 segmentmins[2] = min(start[2], end[2]);
5874 segmentmaxs[0] = max(start[0], end[0]);
5875 segmentmaxs[1] = max(start[1], end[1]);
5876 segmentmaxs[2] = max(start[2], end[2]);
5877 nodenum = node->back;
5880 // start end START end
5881 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5882 backfrac = backdist1 / (backdist1 - backdist2);
5883 VectorLerp(start, backfrac, end, clipped[0]);
5885 segmentmins[0] = min(start[0], end[0]);
5886 segmentmins[1] = min(start[1], end[1]);
5887 segmentmins[2] = min(start[2], end[2]);
5888 segmentmaxs[0] = max(start[0], end[0]);
5889 segmentmaxs[1] = max(start[1], end[1]);
5890 segmentmaxs[2] = max(start[2], end[2]);
5891 nodenum = node->back;
5894 // START end START end
5895 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5896 VectorLerp(start, frontfrac, end, clipped[1]);
5897 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5898 backfrac = backdist1 / (backdist1 - backdist2);
5899 VectorLerp(start, backfrac, end, clipped[0]);
5901 segmentmins[0] = min(start[0], end[0]);
5902 segmentmins[1] = min(start[1], end[1]);
5903 segmentmins[2] = min(start[2], end[2]);
5904 segmentmaxs[0] = max(start[0], end[0]);
5905 segmentmaxs[1] = max(start[1], end[1]);
5906 segmentmaxs[2] = max(start[2], end[2]);
5907 nodenum = node->back;
5910 // start END START end
5911 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5912 VectorLerp(start, frontfrac, end, clipped[1]);
5913 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5914 backfrac = backdist1 / (backdist1 - backdist2);
5915 VectorLerp(start, backfrac, end, clipped[0]);
5917 segmentmins[0] = min(start[0], end[0]);
5918 segmentmins[1] = min(start[1], end[1]);
5919 segmentmins[2] = min(start[2], end[2]);
5920 segmentmaxs[0] = max(start[0], end[0]);
5921 segmentmaxs[1] = max(start[1], end[1]);
5922 segmentmaxs[2] = max(start[2], end[2]);
5923 nodenum = node->back;
5926 // START END START end
5927 backfrac = backdist1 / (backdist1 - backdist2);
5928 VectorLerp(start, backfrac, end, clipped[0]);
5930 segmentmins[0] = min(start[0], end[0]);
5931 segmentmins[1] = min(start[1], end[1]);
5932 segmentmins[2] = min(start[2], end[2]);
5933 segmentmaxs[0] = max(start[0], end[0]);
5934 segmentmaxs[1] = max(start[1], end[1]);
5935 segmentmaxs[2] = max(start[2], end[2]);
5936 nodenum = node->back;
5939 // start end start end
5940 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5941 nodenum = node->back;
5944 // START end start end
5945 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5946 VectorLerp(start, frontfrac, end, clipped[1]);
5947 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5948 nodenum = node->back;
5951 // start END start end
5952 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5953 VectorLerp(start, frontfrac, end, clipped[1]);
5954 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5955 nodenum = node->back;
5958 // START END start end
5959 nodenum = node->back;
5964 if (!model->collision_bih.leafs)
5966 leaf = model->collision_bih.leafs + (-1-nodenum);
5968 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
5975 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5976 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
5979 // collision triangle
5980 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
5981 texture = model->data_textures + leaf->textureindex;
5982 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);
5986 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
5987 texture = model->data_textures + leaf->textureindex;
5988 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);
5995 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)
5997 const bih_leaf_t *leaf;
5998 const bih_node_t *node;
5999 const colbrushf_t *brush;
6001 const texture_t *texture;
6003 while (nodenum >= 0)
6005 node = model->collision_bih.nodes + nodenum;
6006 axis = node->type - BIH_SPLITX;
6009 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6012 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6013 nodenum = node->back;
6016 if (segmentmins[axis] <= node->backmax)
6018 if (segmentmaxs[axis] >= node->frontmin)
6019 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6020 nodenum = node->back;
6022 else if (segmentmaxs[axis] >= node->frontmin)
6023 nodenum = node->front;
6025 return; // trace falls between children
6027 if (!model->collision_bih.leafs)
6029 leaf = model->collision_bih.leafs + (-1-nodenum);
6031 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6038 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6039 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6042 // collision triangle
6043 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6044 texture = model->data_textures + leaf->textureindex;
6045 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);
6049 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6050 texture = model->data_textures + leaf->textureindex;
6051 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);
6058 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)
6060 memset(trace, 0, sizeof(*trace));
6061 trace->fraction = 1;
6062 trace->realfraction = 1;
6063 trace->hitsupercontentsmask = hitsupercontentsmask;
6064 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6067 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)
6069 if (VectorCompare(start, end))
6071 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6075 memset(trace, 0, sizeof(*trace));
6076 trace->fraction = 1;
6077 trace->realfraction = 1;
6078 trace->hitsupercontentsmask = hitsupercontentsmask;
6079 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6082 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)
6084 float segmentmins[3], segmentmaxs[3];
6085 colboxbrushf_t thisbrush_start, thisbrush_end;
6086 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6088 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6090 vec3_t shiftstart, shiftend;
6091 VectorAdd(start, boxmins, shiftstart);
6092 VectorAdd(end, boxmins, shiftend);
6093 if (VectorCompare(start, end))
6094 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6097 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6098 VectorSubtract(trace->endpos, boxmins, trace->endpos);
6103 // box trace, performed as brush trace
6104 memset(trace, 0, sizeof(*trace));
6105 trace->fraction = 1;
6106 trace->realfraction = 1;
6107 trace->hitsupercontentsmask = hitsupercontentsmask;
6108 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6109 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6110 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6111 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6112 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6113 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6114 VectorAdd(start, boxmins, boxstartmins);
6115 VectorAdd(start, boxmaxs, boxstartmaxs);
6116 VectorAdd(end, boxmins, boxendmins);
6117 VectorAdd(end, boxmaxs, boxendmaxs);
6118 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6119 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6120 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6123 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6126 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6127 return trace.startsupercontents;
6130 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)
6133 int hitsupercontents;
6134 VectorSet(end, start[0], start[1], model->normalmins[2]);
6135 memset(trace, 0, sizeof(*trace));
6136 trace->fraction = 1;
6137 trace->realfraction = 1;
6138 trace->hitsupercontentsmask = hitsupercontentsmask;
6139 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6140 hitsupercontents = trace->hitsupercontents;
6141 memset(trace, 0, sizeof(*trace));
6142 trace->fraction = 1;
6143 trace->realfraction = 1;
6144 trace->hitsupercontentsmask = hitsupercontentsmask;
6145 trace->startsupercontents = hitsupercontents;
6148 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6152 VectorSet(end, start[0], start[1], model->normalmins[2]);
6153 memset(&trace, 0, sizeof(trace));
6155 trace.realfraction = 1;
6156 trace.hitsupercontentsmask = 0;
6157 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(&trace, model, model->collision_bih.rootnode, start, end, start, end);
6158 return trace.hitsupercontents;
6161 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6166 // find which leaf the point is in
6168 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6169 // point trace the brushes
6170 leaf = (mleaf_t *)node;
6171 for (i = 0;i < leaf->numleafbrushes;i++)
6173 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6174 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6176 brush->markframe = markframe;
6177 Collision_TracePointBrushFloat(trace, point, brush);
6180 // can't do point traces on curves (they have no thickness)
6183 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)
6185 int i, startside, endside;
6186 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6188 msurface_t *surface;
6191 // walk the tree until we hit a leaf, recursing for any split cases
6194 // abort if this part of the bsp tree can not be hit by this trace
6195 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6197 plane = node->plane;
6198 // axial planes are much more common than non-axial, so an optimized
6199 // axial case pays off here
6200 if (plane->type < 3)
6202 dist1 = start[plane->type] - plane->dist;
6203 dist2 = end[plane->type] - plane->dist;
6207 dist1 = DotProduct(start, plane->normal) - plane->dist;
6208 dist2 = DotProduct(end, plane->normal) - plane->dist;
6210 startside = dist1 < 0;
6211 endside = dist2 < 0;
6212 if (startside == endside)
6214 // most of the time the line fragment is on one side of the plane
6215 node = node->children[startside];
6219 // line crosses node plane, split the line
6220 dist1 = PlaneDiff(linestart, plane);
6221 dist2 = PlaneDiff(lineend, plane);
6222 midfrac = dist1 / (dist1 - dist2);
6223 VectorLerp(linestart, midfrac, lineend, mid);
6224 // take the near side first
6225 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6226 // if we found an impact on the front side, don't waste time
6227 // exploring the far side
6228 if (midfrac <= trace->realfraction)
6229 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6233 // abort if this part of the bsp tree can not be hit by this trace
6234 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6237 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6238 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6239 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6240 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6241 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6242 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6243 // line trace the brushes
6244 leaf = (mleaf_t *)node;
6245 for (i = 0;i < leaf->numleafbrushes;i++)
6247 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6248 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6250 brush->markframe = markframe;
6251 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6254 // can't do point traces on curves (they have no thickness)
6255 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6257 // line trace the curves
6258 for (i = 0;i < leaf->numleafsurfaces;i++)
6260 surface = model->data_surfaces + leaf->firstleafsurface[i];
6261 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6263 surface->deprecatedq3collisionmarkframe = markframe;
6264 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);
6270 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)
6276 msurface_t *surface;
6278 float nodesegmentmins[3], nodesegmentmaxs[3];
6279 // walk the tree until we hit a leaf, recursing for any split cases
6282 // abort if this part of the bsp tree can not be hit by this trace
6283 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6285 plane = node->plane;
6286 // axial planes are much more common than non-axial, so an optimized
6287 // axial case pays off here
6288 if (plane->type < 3)
6290 // this is an axial plane, compare bounding box directly to it and
6291 // recurse sides accordingly
6292 // recurse down node sides
6293 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6294 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6295 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6296 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6300 // this is a non-axial plane, so check if the start and end boxes
6301 // are both on one side of the plane to handle 'diagonal' cases
6302 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6306 // segment crosses plane
6307 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6310 // if sides == 0 then the trace itself is bogus (Not A Number values),
6311 // in this case we simply pretend the trace hit nothing
6313 return; // ERROR: NAN bounding box!
6314 // take whichever side the segment box is on
6315 node = node->children[sides - 1];
6317 // abort if this part of the bsp tree can not be hit by this trace
6318 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6320 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6321 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6322 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6323 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6324 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6325 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6327 leaf = (mleaf_t *)node;
6328 for (i = 0;i < leaf->numleafbrushes;i++)
6330 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6331 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6333 brush->markframe = markframe;
6334 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6337 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6339 for (i = 0;i < leaf->numleafsurfaces;i++)
6341 surface = model->data_surfaces + leaf->firstleafsurface[i];
6342 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6344 surface->deprecatedq3collisionmarkframe = markframe;
6345 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);
6352 static int markframe = 0;
6354 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)
6358 memset(trace, 0, sizeof(*trace));
6359 trace->fraction = 1;
6360 trace->realfraction = 1;
6361 trace->hitsupercontentsmask = hitsupercontentsmask;
6362 if (mod_collision_bih.integer)
6363 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6364 else if (model->brush.submodel)
6366 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6367 if (brush->colbrushf)
6368 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6371 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6374 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)
6377 float segmentmins[3], segmentmaxs[3];
6378 msurface_t *surface;
6381 if (VectorCompare(start, end))
6383 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6387 memset(trace, 0, sizeof(*trace));
6388 trace->fraction = 1;
6389 trace->realfraction = 1;
6390 trace->hitsupercontentsmask = hitsupercontentsmask;
6391 segmentmins[0] = min(start[0], end[0]) - 1;
6392 segmentmins[1] = min(start[1], end[1]) - 1;
6393 segmentmins[2] = min(start[2], end[2]) - 1;
6394 segmentmaxs[0] = max(start[0], end[0]) + 1;
6395 segmentmaxs[1] = max(start[1], end[1]) + 1;
6396 segmentmaxs[2] = max(start[2], end[2]) + 1;
6397 if (mod_collision_bih.integer)
6398 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6399 else if (model->brush.submodel)
6401 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6402 if (brush->colbrushf)
6403 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6404 if (mod_q3bsp_curves_collisions.integer)
6405 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6406 if (surface->num_collisiontriangles)
6407 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);
6410 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6413 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)
6416 float segmentmins[3], segmentmaxs[3];
6417 msurface_t *surface;
6419 colboxbrushf_t thisbrush_start, thisbrush_end;
6420 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6422 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6424 vec3_t shiftstart, shiftend;
6425 VectorAdd(start, boxmins, shiftstart);
6426 VectorAdd(end, boxmins, shiftend);
6427 if (VectorCompare(start, end))
6428 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6431 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6432 VectorSubtract(trace->endpos, boxmins, trace->endpos);
6437 // box trace, performed as brush trace
6438 memset(trace, 0, sizeof(*trace));
6439 trace->fraction = 1;
6440 trace->realfraction = 1;
6441 trace->hitsupercontentsmask = hitsupercontentsmask;
6442 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6443 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6444 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6445 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6446 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6447 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6448 VectorAdd(start, boxmins, boxstartmins);
6449 VectorAdd(start, boxmaxs, boxstartmaxs);
6450 VectorAdd(end, boxmins, boxendmins);
6451 VectorAdd(end, boxmaxs, boxendmaxs);
6452 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6453 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6454 if (mod_collision_bih.integer)
6455 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6456 else if (model->brush.submodel)
6458 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6459 if (brush->colbrushf)
6460 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, brush->colbrushf, brush->colbrushf);
6461 if (mod_q3bsp_curves_collisions.integer)
6462 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6463 if (surface->num_collisiontriangles)
6464 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);
6467 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, &thisbrush_start.brush, &thisbrush_end.brush, ++markframe, segmentmins, segmentmaxs);
6470 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6473 int supercontents = 0;
6475 if (mod_collision_bih.integer)
6478 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6479 supercontents = trace.startsupercontents;
6481 // test if the point is inside each brush
6482 else if (model->brush.submodel)
6484 // submodels are effectively one leaf
6485 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6486 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6487 supercontents |= brush->colbrushf->supercontents;
6491 mnode_t *node = model->brush.data_nodes;
6493 // find which leaf the point is in
6495 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6496 leaf = (mleaf_t *)node;
6497 // now check the brushes in the leaf
6498 for (i = 0;i < leaf->numleafbrushes;i++)
6500 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6501 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6502 supercontents |= brush->colbrushf->supercontents;
6505 return supercontents;
6508 void Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces)
6516 int nummodelbrushes = model->nummodelbrushes;
6517 int nummodelsurfaces = model->nummodelsurfaces;
6519 const int *collisionelement3i;
6520 const float *collisionvertex3f;
6521 const int *renderelement3i;
6522 const float *rendervertex3f;
6523 bih_leaf_t *bihleafs;
6524 bih_node_t *bihnodes;
6526 int *temp_leafsortscratch;
6527 const msurface_t *surface;
6528 const q3mbrush_t *brush;
6530 // find out how many BIH leaf nodes we need
6532 if (userendersurfaces)
6534 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6535 bihnumleafs += surface->num_triangles;
6539 bihnumleafs += model->nummodelbrushes;
6540 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6541 bihnumleafs += surface->num_collisiontriangles;
6547 // allocate the memory for the BIH leaf nodes
6548 bihleafs = Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6550 // now populate the BIH leaf nodes
6552 if (userendersurfaces)
6554 // add render surfaces
6555 renderelement3i = model->surfmesh.data_element3i;
6556 rendervertex3f = model->surfmesh.data_vertex3f;
6557 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6559 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6561 bihleafs[bihleafindex].type = BIH_LEAF + 2;
6562 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6563 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6564 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6565 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6566 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6567 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6568 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6569 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6576 // add collision brushes
6577 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6579 bihleafs[bihleafindex].type = BIH_LEAF;
6580 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6581 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6582 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6583 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6587 // add collision surfaces
6588 collisionelement3i = model->brush.data_collisionelement3i;
6589 collisionvertex3f = model->brush.data_collisionvertex3f;
6590 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6592 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6594 bihleafs[bihleafindex].type = BIH_LEAF + 1;
6595 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6596 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6597 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6598 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6599 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6600 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6601 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6602 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6608 // allocate buffers for the produced and temporary data
6609 bihmaxnodes = bihnumleafs - 1;
6610 bihnodes = Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6611 temp_leafsort = Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6612 temp_leafsortscratch = temp_leafsort + bihnumleafs;
6615 BIH_Build(&model->collision_bih, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6617 // we're done with the temporary data
6618 Mem_Free(temp_leafsort);
6620 // resize the BIH nodes array if it over-allocated
6621 if (model->collision_bih.maxnodes > model->collision_bih.numnodes)
6623 model->collision_bih.maxnodes = model->collision_bih.numnodes;
6624 model->collision_bih.nodes = Mem_Realloc(loadmodel->mempool, model->collision_bih.nodes, model->collision_bih.numnodes * sizeof(bih_node_t));
6628 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6630 int supercontents = 0;
6631 if (nativecontents & CONTENTSQ3_SOLID)
6632 supercontents |= SUPERCONTENTS_SOLID;
6633 if (nativecontents & CONTENTSQ3_WATER)
6634 supercontents |= SUPERCONTENTS_WATER;
6635 if (nativecontents & CONTENTSQ3_SLIME)
6636 supercontents |= SUPERCONTENTS_SLIME;
6637 if (nativecontents & CONTENTSQ3_LAVA)
6638 supercontents |= SUPERCONTENTS_LAVA;
6639 if (nativecontents & CONTENTSQ3_BODY)
6640 supercontents |= SUPERCONTENTS_BODY;
6641 if (nativecontents & CONTENTSQ3_CORPSE)
6642 supercontents |= SUPERCONTENTS_CORPSE;
6643 if (nativecontents & CONTENTSQ3_NODROP)
6644 supercontents |= SUPERCONTENTS_NODROP;
6645 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6646 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6647 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6648 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6649 if (nativecontents & CONTENTSQ3_DONOTENTER)
6650 supercontents |= SUPERCONTENTS_DONOTENTER;
6651 if (nativecontents & CONTENTSQ3_BOTCLIP)
6652 supercontents |= SUPERCONTENTS_BOTCLIP;
6653 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6654 supercontents |= SUPERCONTENTS_OPAQUE;
6655 return supercontents;
6658 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6660 int nativecontents = 0;
6661 if (supercontents & SUPERCONTENTS_SOLID)
6662 nativecontents |= CONTENTSQ3_SOLID;
6663 if (supercontents & SUPERCONTENTS_WATER)
6664 nativecontents |= CONTENTSQ3_WATER;
6665 if (supercontents & SUPERCONTENTS_SLIME)
6666 nativecontents |= CONTENTSQ3_SLIME;
6667 if (supercontents & SUPERCONTENTS_LAVA)
6668 nativecontents |= CONTENTSQ3_LAVA;
6669 if (supercontents & SUPERCONTENTS_BODY)
6670 nativecontents |= CONTENTSQ3_BODY;
6671 if (supercontents & SUPERCONTENTS_CORPSE)
6672 nativecontents |= CONTENTSQ3_CORPSE;
6673 if (supercontents & SUPERCONTENTS_NODROP)
6674 nativecontents |= CONTENTSQ3_NODROP;
6675 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6676 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6677 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6678 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6679 if (supercontents & SUPERCONTENTS_DONOTENTER)
6680 nativecontents |= CONTENTSQ3_DONOTENTER;
6681 if (supercontents & SUPERCONTENTS_BOTCLIP)
6682 nativecontents |= CONTENTSQ3_BOTCLIP;
6683 if (!(supercontents & SUPERCONTENTS_OPAQUE))
6684 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6685 return nativecontents;
6688 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6693 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6694 node = node->children[1];
6696 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6697 if (loadmodel->brush.num_leafs < numleafs)
6698 loadmodel->brush.num_leafs = numleafs;
6701 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6703 int i, j, numshadowmeshtriangles, lumps;
6704 q3dheader_t *header;
6705 float corner[3], yawradius, modelradius;
6706 msurface_t *surface;
6708 mod->modeldatatypestring = "Q3BSP";
6710 mod->type = mod_brushq3;
6711 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6714 header = (q3dheader_t *)buffer;
6715 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6716 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6718 i = LittleLong(header->version);
6719 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
6720 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
6722 mod->soundfromcenter = true;
6723 mod->TraceBox = Mod_Q3BSP_TraceBox;
6724 mod->TraceLine = Mod_Q3BSP_TraceLine;
6725 mod->TracePoint = Mod_Q3BSP_TracePoint;
6726 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
6727 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
6728 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
6729 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
6730 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
6731 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
6732 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
6733 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
6734 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
6735 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
6736 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
6737 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
6738 mod->brush.AmbientSoundLevelsForPoint = NULL;
6739 mod->brush.RoundUpToHullSize = NULL;
6740 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
6741 mod->Draw = R_Q1BSP_Draw;
6742 mod->DrawDepth = R_Q1BSP_DrawDepth;
6743 mod->DrawDebug = R_Q1BSP_DrawDebug;
6744 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
6745 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
6746 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
6747 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
6748 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
6749 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
6750 mod->DrawLight = R_Q1BSP_DrawLight;
6752 mod_base = (unsigned char *)header;
6754 // swap all the lumps
6755 header->ident = LittleLong(header->ident);
6756 header->version = LittleLong(header->version);
6757 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
6758 for (i = 0;i < lumps;i++)
6760 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
6761 if((char *) bufferend < (char *) buffer + j)
6762 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
6763 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
6764 if((char *) bufferend < (char *) buffer + j)
6765 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
6768 * NO, do NOT clear them!
6769 * they contain actual data referenced by other stuff.
6770 * Instead, before using the advertisements lump, check header->versio
6772 * Sorry, but otherwise it breaks memory of the first lump.
6773 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
6775 header->lumps[i].fileofs = 0;
6776 header->lumps[i].filelen = 0;
6780 mod->brush.qw_md4sum = 0;
6781 mod->brush.qw_md4sum2 = 0;
6782 for (i = 0;i < lumps;i++)
6784 if (i == Q3LUMP_ENTITIES)
6786 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
6787 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
6789 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
6791 // all this checksumming can take a while, so let's send keepalives here too
6792 CL_KeepaliveMessage(false);
6795 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
6796 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
6797 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
6798 if (header->version == Q3BSPVERSION_IG)
6799 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
6801 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
6802 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
6803 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
6804 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
6805 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
6806 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
6807 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
6808 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
6809 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
6810 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
6811 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
6812 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
6813 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
6814 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
6815 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
6817 // the MakePortals code works fine on the q3bsp data as well
6818 Mod_Q1BSP_MakePortals();
6820 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
6821 loadmodel->brush.supportwateralpha = true;
6823 // make a single combined shadow mesh to allow optimized shadow volume creation
6824 numshadowmeshtriangles = 0;
6825 if (cls.state != ca_dedicated)
6827 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
6829 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
6830 numshadowmeshtriangles += surface->num_triangles;
6832 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
6833 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
6834 if (surface->num_triangles > 0)
6835 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));
6836 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true, false);
6837 if (loadmodel->brush.shadowmesh)
6838 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
6841 loadmodel->brush.num_leafs = 0;
6842 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
6844 if (loadmodel->brush.numsubmodels)
6845 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
6848 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
6853 // duplicate the basic information
6854 dpsnprintf(name, sizeof(name), "*%i", i);
6855 mod = Mod_FindName(name, loadmodel->name);
6856 // copy the base model to this one
6858 // rename the clone back to its proper name
6859 strlcpy(mod->name, name, sizeof(mod->name));
6860 mod->brush.parentmodel = loadmodel;
6861 // textures and memory belong to the main model
6862 mod->texturepool = NULL;
6863 mod->mempool = NULL;
6864 mod->brush.GetPVS = NULL;
6865 mod->brush.FatPVS = NULL;
6866 mod->brush.BoxTouchingPVS = NULL;
6867 mod->brush.BoxTouchingLeafPVS = NULL;
6868 mod->brush.BoxTouchingVisibleLeafs = NULL;
6869 mod->brush.FindBoxClusters = NULL;
6870 mod->brush.LightPoint = NULL;
6871 mod->brush.AmbientSoundLevelsForPoint = NULL;
6873 mod->brush.submodel = i;
6874 if (loadmodel->brush.submodels)
6875 loadmodel->brush.submodels[i] = mod;
6877 // make the model surface list (used by shadowing/lighting)
6878 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
6879 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
6880 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
6881 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
6882 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
6883 Mod_MakeSortedSurfaces(mod);
6885 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
6886 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
6887 // enlarge the bounding box to enclose all geometry of this model,
6888 // because q3map2 sometimes lies (mostly to affect the lightgrid),
6889 // which can in turn mess up the farclip (as well as culling when
6890 // outside the level - an unimportant concern)
6892 //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]);
6893 for (j = 0;j < mod->nummodelsurfaces;j++)
6895 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
6896 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
6898 if (!surface->num_vertices)
6900 for (k = 0;k < surface->num_vertices;k++, v += 3)
6902 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
6903 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
6904 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
6905 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
6906 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
6907 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
6910 //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]);
6911 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
6912 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
6913 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
6914 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
6915 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
6916 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
6917 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
6918 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
6919 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
6920 mod->yawmins[2] = mod->normalmins[2];
6921 mod->yawmaxs[2] = mod->normalmaxs[2];
6922 mod->radius = modelradius;
6923 mod->radius2 = modelradius * modelradius;
6925 // this gets altered below if sky or water is used
6926 mod->DrawSky = NULL;
6927 mod->DrawAddWaterPlanes = NULL;
6929 for (j = 0;j < mod->nummodelsurfaces;j++)
6930 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
6932 if (j < mod->nummodelsurfaces)
6933 mod->DrawSky = R_Q1BSP_DrawSky;
6935 for (j = 0;j < mod->nummodelsurfaces;j++)
6936 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION))
6938 if (j < mod->nummodelsurfaces)
6939 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
6941 Mod_MakeCollisionBIH(mod, false);
6943 // generate VBOs and other shared data before cloning submodels
6948 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);
6951 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6953 int i = LittleLong(((int *)buffer)[1]);
6954 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
6955 Mod_Q3BSP_Load(mod,buffer, bufferend);
6956 else if (i == Q2BSPVERSION)
6957 Mod_Q2BSP_Load(mod,buffer, bufferend);
6959 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
6962 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6964 Host_Error("Mod_MAP_Load: not yet implemented");
6970 typedef struct objvertex_s
6980 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
6982 const char *textbase = (char *)buffer, *text = textbase;
6986 char materialname[MAX_QPATH];
6987 int i, j, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, numsurfaces, surfacevertices, surfacetriangles, surfaceelements;
6988 int index1, index2, index3;
6989 objvertex_t vfirst, vprev, vcurrent;
6992 int numtriangles = 0;
6993 int maxtriangles = 0;
6994 objvertex_t *vertices = NULL;
6996 int maxtextures = 0, numtextures = 0, textureindex = 0;
6997 int maxv = 0, numv = 1;
6998 int maxvt = 0, numvt = 1;
6999 int maxvn = 0, numvn = 1;
7000 char *texturenames = NULL;
7001 float dist, modelradius, modelyawradius;
7007 objvertex_t *thisvertex = NULL;
7008 int vertexhashindex;
7009 int *vertexhashtable = NULL;
7010 objvertex_t *vertexhashdata = NULL;
7011 objvertex_t *vdata = NULL;
7012 int vertexhashsize = 0;
7013 int vertexhashcount = 0;
7014 skinfile_t *skinfiles = NULL;
7015 unsigned char *data = NULL;
7017 memset(&vfirst, 0, sizeof(vfirst));
7018 memset(&vprev, 0, sizeof(vprev));
7019 memset(&vcurrent, 0, sizeof(vcurrent));
7021 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7023 loadmodel->modeldatatypestring = "OBJ";
7025 loadmodel->type = mod_obj;
7026 loadmodel->soundfromcenter = true;
7027 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7028 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7029 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7030 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7031 loadmodel->brush.TraceLineOfSight = NULL;
7032 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7033 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7034 loadmodel->brush.GetPVS = NULL;
7035 loadmodel->brush.FatPVS = NULL;
7036 loadmodel->brush.BoxTouchingPVS = NULL;
7037 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7038 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7039 loadmodel->brush.FindBoxClusters = NULL;
7040 loadmodel->brush.LightPoint = NULL;
7041 loadmodel->brush.FindNonSolidLocation = NULL;
7042 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7043 loadmodel->brush.RoundUpToHullSize = NULL;
7044 loadmodel->brush.PointInLeaf = NULL;
7045 loadmodel->Draw = R_Q1BSP_Draw;
7046 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7047 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7048 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7049 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7050 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7051 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7052 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7053 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7054 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7056 skinfiles = Mod_LoadSkinFiles();
7057 if (loadmodel->numskins < 1)
7058 loadmodel->numskins = 1;
7060 // make skinscenes for the skins (no groups)
7061 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7062 for (i = 0;i < loadmodel->numskins;i++)
7064 loadmodel->skinscenes[i].firstframe = i;
7065 loadmodel->skinscenes[i].framecount = 1;
7066 loadmodel->skinscenes[i].loop = true;
7067 loadmodel->skinscenes[i].framerate = 10;
7073 // parse the OBJ text now
7080 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7081 line[linelen] = text[linelen];
7083 for (argc = 0;argc < 4;argc++)
7087 while (*s == ' ' || *s == '\t')
7097 while (*s == ' ' || *s == '\t')
7107 if (argv[0][0] == '#')
7109 if (!strcmp(argv[0], "v"))
7113 maxv = max(maxv * 2, 1024);
7114 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7116 v[numv*3+0] = atof(argv[1]);
7117 v[numv*3+2] = atof(argv[2]);
7118 v[numv*3+1] = atof(argv[3]);
7121 else if (!strcmp(argv[0], "vt"))
7125 maxvt = max(maxvt * 2, 1024);
7126 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7128 vt[numvt*2+0] = atof(argv[1]);
7129 vt[numvt*2+1] = 1-atof(argv[2]);
7132 else if (!strcmp(argv[0], "vn"))
7136 maxvn = max(maxvn * 2, 1024);
7137 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7139 vn[numvn*3+0] = atof(argv[1]);
7140 vn[numvn*3+2] = atof(argv[2]);
7141 vn[numvn*3+1] = atof(argv[3]);
7144 else if (!strcmp(argv[0], "f"))
7148 if (maxtextures <= numtextures)
7150 maxtextures = max(maxtextures * 2, 256);
7151 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7153 textureindex = numtextures++;
7154 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7156 for (j = 1;j < argc;j++)
7158 index1 = atoi(argv[j]);
7159 while(argv[j][0] && argv[j][0] != '/')
7163 index2 = atoi(argv[j]);
7164 while(argv[j][0] && argv[j][0] != '/')
7168 index3 = atoi(argv[j]);
7169 // negative refers to a recent vertex
7170 // zero means not specified
7171 // positive means an absolute vertex index
7173 index1 = numv - index1;
7175 index2 = numvt - index2;
7177 index3 = numvn - index3;
7178 vcurrent.nextindex = -1;
7179 vcurrent.textureindex = textureindex;
7180 VectorCopy(v + 3*index1, vcurrent.v);
7181 Vector2Copy(vt + 2*index2, vcurrent.vt);
7182 VectorCopy(vn + 3*index3, vcurrent.vn);
7183 if (numtriangles == 0)
7185 VectorCopy(vcurrent.v, mins);
7186 VectorCopy(vcurrent.v, maxs);
7190 mins[0] = min(mins[0], vcurrent.v[0]);
7191 mins[1] = min(mins[1], vcurrent.v[1]);
7192 mins[2] = min(mins[2], vcurrent.v[2]);
7193 maxs[0] = max(maxs[0], vcurrent.v[0]);
7194 maxs[1] = max(maxs[1], vcurrent.v[1]);
7195 maxs[2] = max(maxs[2], vcurrent.v[2]);
7201 if (maxtriangles <= numtriangles)
7203 maxtriangles = max(maxtriangles * 2, 32768);
7204 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7206 vertices[numtriangles*3+0] = vfirst;
7207 vertices[numtriangles*3+1] = vprev;
7208 vertices[numtriangles*3+2] = vcurrent;
7214 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7216 else if (!strcmp(argv[0], "usemtl"))
7218 for (i = 0;i < numtextures;i++)
7219 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7221 if (i < numtextures)
7225 if (maxtextures <= numtextures)
7227 maxtextures = max(maxtextures * 2, 256);
7228 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7230 textureindex = numtextures++;
7231 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7236 // now that we have the OBJ data loaded as-is, we can convert it
7238 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7239 VectorCopy(mins, loadmodel->normalmins);
7240 VectorCopy(maxs, loadmodel->normalmaxs);
7241 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7242 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7243 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7244 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7245 modelradius = modelyawradius + modelradius * modelradius;
7246 modelyawradius = sqrt(modelyawradius);
7247 modelradius = sqrt(modelradius);
7248 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7249 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7250 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7251 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7252 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7253 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7254 loadmodel->radius = modelradius;
7255 loadmodel->radius2 = modelradius * modelradius;
7257 // allocate storage for triangles
7258 loadmodel->num_surfaces = loadmodel->nummodelsurfaces = numsurfaces = numtextures;
7259 loadmodel->surfmesh.data_element3i = Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7260 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t));
7261 // allocate vertex hash structures to build an optimal vertex subset
7262 vertexhashsize = numtriangles*2;
7263 vertexhashtable = Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7264 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7265 vertexhashdata = Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7266 vertexhashcount = 0;
7268 // gather surface stats for assigning vertex/triangle ranges
7272 for (textureindex = 0;textureindex < numtextures;textureindex++)
7274 msurface_t *surface = loadmodel->data_surfaces + textureindex;
7275 // copy the mins/maxs of the model backwards so that the first vertex
7276 // added will set the surface bounds to a point
7277 VectorCopy(loadmodel->normalmaxs, surface->mins);
7278 VectorCopy(loadmodel->normalmins, surface->maxs);
7279 surfacevertices = 0;
7280 surfaceelements = 0;
7281 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7283 thisvertex = vertices + vertexindex;
7284 if (thisvertex->textureindex != textureindex)
7286 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7287 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7288 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7289 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7290 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7291 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7292 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7293 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7295 vdata = vertexhashdata + i;
7296 if (vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7301 i = vertexhashcount++;
7302 vdata = vertexhashdata + i;
7303 *vdata = *thisvertex;
7304 vdata->nextindex = vertexhashtable[vertexhashindex];
7305 vertexhashtable[vertexhashindex] = i;
7308 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7311 surfacetriangles = surfaceelements / 3;
7312 surface->num_vertices = surfacevertices;
7313 surface->num_triangles = surfacetriangles;
7314 surface->num_firstvertex = firstvertex;
7315 surface->num_firsttriangle = firsttriangle;
7316 firstvertex += surface->num_vertices;
7317 firsttriangle += surface->num_triangles;
7319 numvertices = firstvertex;
7321 // allocate storage for final mesh data
7322 loadmodel->num_textures = numtextures * loadmodel->numskins;
7323 loadmodel->num_texturesperskin = numtextures;
7324 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]));
7325 loadmodel->sortedmodelsurfaces = (int *)data;data += numsurfaces * sizeof(int);
7326 loadmodel->data_textures = (texture_t *)data;data += numsurfaces * loadmodel->numskins * sizeof(texture_t);
7327 loadmodel->surfmesh.num_vertices = numvertices;
7328 loadmodel->surfmesh.num_triangles = numtriangles;
7329 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7330 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7331 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7332 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7333 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7334 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7335 if (loadmodel->surfmesh.num_vertices <= 65536)
7336 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7338 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7340 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7341 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7342 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7345 // load the textures
7346 for (textureindex = 0;textureindex < numtextures;textureindex++)
7347 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7348 Mod_FreeSkinFiles(skinfiles);
7350 // set the surface textures
7351 for (textureindex = 0;textureindex < numtextures;textureindex++)
7353 msurface_t *surface = loadmodel->data_surfaces + textureindex;
7354 surface->texture = loadmodel->data_textures + textureindex;
7359 Mem_Free(texturenames);
7363 Mem_Free(vertexhashtable);
7364 Mem_Free(vertexhashdata);
7366 // compute all the mesh information that was not loaded from the file
7367 Mod_MakeSortedSurfaces(loadmodel);
7368 if (loadmodel->surfmesh.data_element3s)
7369 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7370 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7371 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7372 // generate normals if the file did not have them
7373 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7374 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
7375 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);
7376 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7378 Mod_MakeCollisionBIH(loadmodel, true);
7393 typedef struct objvertex_s
7401 typedef struct objtriangle_s
7403 objvertex_t vertex[3];
7405 // these fields are used only in conversion to surfaces
7408 int surfacevertexindex[3];
7409 float edgeplane[3][4];
7415 struct objnode_s *children[2];
7416 struct objnode_s *parent;
7417 objtriangle_t *triangles;
7426 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)
7432 float bestnormal[3];
7437 int numfronttriangles;
7438 int numbacktriangles;
7443 float outfrontpoints[5][3];
7444 float outbackpoints[5][3];
7445 int neededfrontpoints;
7446 int neededbackpoints;
7450 node = (objnode_t *)Mem_ExpandableArray_AllocRecord(array);
7451 node->parent = parent;
7454 VectorCopy(triangles[0].vertex[0].v, mins);
7455 VectorCopy(triangles[0].vertex[0].v, maxs);
7457 else if (parent && parent->children[0] == node)
7459 VectorCopy(parent->mins, mins);
7460 Vectorcopy(parent->maxs, maxs);
7462 else if (parent && parent->children[1] == node)
7464 VectorCopy(parent->mins, mins);
7465 Vectorcopy(parent->maxs, maxs);
7472 for (i = 0;i < numtriangles;i++)
7474 for (j = 0;j < 3;j++)
7476 mins[0] = min(mins[0], triangles[i].vertex[j].v[0]);
7477 mins[1] = min(mins[1], triangles[i].vertex[j].v[1]);
7478 mins[2] = min(mins[2], triangles[i].vertex[j].v[2]);
7479 maxs[0] = max(maxs[0], triangles[i].vertex[j].v[0]);
7480 maxs[1] = max(maxs[1], triangles[i].vertex[j].v[1]);
7481 maxs[2] = max(maxs[2], triangles[i].vertex[j].v[2]);
7484 VectorCopy(mins, node->mins);
7485 VectorCopy(maxs, node->maxs);
7486 if (numtriangles <= mod_obj_leaftriangles.integer)
7489 loadmodel->brush.num_leafs++;
7490 node->triangles = triangles;
7491 node->numtriangles = numtriangles;
7496 loadmodel->brush.num_nodes++;
7497 // pick a splitting plane from the various choices available to us...
7498 // early splits simply halve the interval
7500 VectorClear(bestnormal);
7502 if (numtriangles <= mod_obj_splitterlimit.integer)
7503 limit = numtriangles;
7506 for (i = -3;i < limit;i++)
7510 // first we try 3 axial splits (kdtree-like)
7512 VectorClear(normal);
7514 dist = (mins[j] + maxs[j]) * 0.5f;
7518 // then we try each triangle plane
7519 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7520 VectorNormalize(normal);
7521 dist = DotProduct(normal, triangles[i].vertex[0].v);
7522 // use positive axial values whenever possible
7523 if (normal[0] == -1)
7525 if (normal[1] == -1)
7527 if (normal[2] == -1)
7529 // skip planes that match the current best
7530 if (VectorCompare(normal, bestnormal) && dist == bestdist)
7537 for (j = 0;j < numtriangles;j++)
7539 dists[0] = DotProduct(normal, triangles[j].vertex[0].v) - dist;
7540 dists[1] = DotProduct(normal, triangles[j].vertex[1].v) - dist;
7541 dists[2] = DotProduct(normal, triangles[j].vertex[2].v) - dist;
7542 if (dists[0] < -DIST_EPSILON || dists[1] < -DIST_EPSILON || dists[2] < -DIST_EPSILON)
7544 if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7549 else if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7554 // score is supposed to:
7555 // prefer axial splits
7556 // prefer evenly dividing the input triangles
7557 // prefer triangles on the plane
7558 // avoid triangles crossing the plane
7559 score = count_on*count_on - count_both*count_both + min(count_front, count_back)*(count_front+count_back);
7560 if (normal[0] == 1 || normal[1] == 1 || normal[2] == 1)
7562 if (i == -3 || bestscore < score)
7564 VectorCopy(normal, bestnormal);
7570 // now we have chosen an optimal split plane...
7572 // divide triangles by the splitting plane
7573 numfronttriangles = 0;
7574 numbacktriangles = 0;
7575 for (i = 0;i < numtriangles;i++)
7577 neededfrontpoints = 0;
7578 neededbackpoints = 0;
7580 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);
7581 if (countonpoints > 1)
7583 // triangle lies on plane, assign it to one child only
7584 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7585 if (DotProduct(bestnormal, normal) >= 0)
7587 // assign to front side child
7588 obj_fronttriangles[numfronttriangles++] = triangles[i];
7592 // assign to back side child
7593 obj_backtriangles[numbacktriangles++] = triangles[i];
7598 // convert clipped polygons to triangles
7599 for (j = 0;j < neededfrontpoints-2;j++)
7601 obj_fronttriangles[numfronttriangles] = triangles[i];
7602 VectorCopy(outfrontpoints[0], obj_fronttriangles[numfronttriangles].vertex[0].v);
7603 VectorCopy(outfrontpoints[j+1], obj_fronttriangles[numfronttriangles].vertex[1].v);
7604 VectorCopy(outfrontpoints[j+2], obj_fronttriangles[numfronttriangles].vertex[2].v);
7605 numfronttriangles++;
7607 for (j = 0;j < neededbackpoints-2;j++)
7609 obj_backtriangles[numbacktriangles] = triangles[i];
7610 VectorCopy(outbackpoints[0], obj_backtriangles[numbacktriangles].vertex[0].v);
7611 VectorCopy(outbackpoints[j+1], obj_backtriangles[numbacktriangles].vertex[1].v);
7612 VectorCopy(outbackpoints[j+2], obj_backtriangles[numbacktriangles].vertex[2].v);
7618 // now copy the triangles out of the big buffer
7619 if (numfronttriangles)
7621 fronttriangles = Mem_Alloc(loadmodel->mempool, fronttriangles * sizeof(*fronttriangles));
7622 memcpy(fronttriangles, obj_fronttriangles, numfronttriangles * sizeof(*fronttriangles));
7625 fronttriangles = NULL;
7626 if (numbacktriangles)
7628 backtriangles = Mem_Alloc(loadmodel->mempool, backtriangles * sizeof(*backtriangles));
7629 memcpy(backtriangles, obj_backtriangles, numbacktriangles * sizeof(*backtriangles));
7632 backtriangles = NULL;
7634 // free the original triangles we were given
7636 Mem_Free(triangles);
7640 // now create the children...
7641 node->children[0] = Mod_OBJ_BSPNodeForTriangles(node, fronttriangles, numfronttriangles, frontmins, frontmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
7642 node->children[1] = Mod_OBJ_BSPNodeForTriangles(node, backtriangles, numbacktriangles, backmins, backmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
7646 void Mod_OBJ_SnapVertex(float *v)
7649 float a = mod_obj_vertexprecision.value;
7651 v[0] -= floor(v[0] * a + 0.5f) * b;
7652 v[1] -= floor(v[1] * a + 0.5f) * b;
7653 v[2] -= floor(v[2] * a + 0.5f) * b;
7656 void Mod_OBJ_ConvertBSPNode(objnode_t *objnode, mnode_t *mnodeparent)
7658 if (objnode->children[0])
7660 // convert to mnode_t
7661 mnode_t *mnode = loadmodel->brush.data_nodes + loadmodel->brush.num_nodes++;
7662 mnode->parent = mnodeparent;
7663 mnode->plane = loadmodel->brush.data_planes + loadmodel->brush.num_planes++;
7664 VectorCopy(objnode->normal, mnode->plane->normal);
7665 mnode->plane->dist = objnode->dist;
7666 PlaneClassify(mnode->plane);
7667 VectorCopy(objnode->mins, mnode->mins);
7668 VectorCopy(objnode->maxs, mnode->maxs);
7669 // push combinedsupercontents up to the parent
7671 mnodeparent->combinedsupercontents |= mnode->combinedsupercontents;
7672 mnode->children[0] = Mod_OBJ_ConvertBSPNode(objnode->children[0], mnode);
7673 mnode->children[1] = Mod_OBJ_ConvertBSPNode(objnode->children[1], mnode);
7677 // convert to mleaf_t
7678 mleaf_t *mleaf = loadmodel->brush.data_leafs + loadmodel->brush.num_leafs++;
7679 mleaf->parent = mnodeparent;
7680 VectorCopy(objnode->mins, mleaf->mins);
7681 VectorCopy(objnode->maxs, mleaf->maxs);
7682 mleaf->clusterindex = loadmodel->brush.num_leafs - 1;
7683 if (objnode->numtriangles)
7685 objtriangle_t *triangles = objnode->triangles;
7686 int numtriangles = objnode->numtriangles;
7690 objvertex_t vertex[3];
7692 maxsurfaces = numtriangles;
7694 // calculate some more data on each triangle for surface gathering
7695 for (i = 0;i < numtriangles;i++)
7697 triangle = triangles + i;
7698 texture = loadmodel->data_textures + triangle->textureindex;
7699 Mod_OBJ_SnapVertex(triangle->vertex[0].v);
7700 Mod_OBJ_SnapVertex(triangle->vertex[1].v);
7701 Mod_OBJ_SnapVertex(triangle->vertex[2].v);
7702 TriangleNormal(triangle->vertex[0].v, triangle->vertex[1].v, triangle->vertex[2].v, normal);
7704 if (fabs(normal[axis]) < fabs(normal[1]))
7706 if (fabs(normal[axis]) < fabs(normal[2]))
7708 VectorClear(normal);
7710 triangle->axis = axis;
7711 VectorSubtract(triangle->vertex[1].v, triangle->vertex[0].v, edge[0]);
7712 VectorSubtract(triangle->vertex[2].v, triangle->vertex[1].v, edge[1]);
7713 VectorSubtract(triangle->vertex[0].v, triangle->vertex[2].v, edge[2]);
7714 CrossProduct(edge[0], normal, triangle->edgeplane[0]);
7715 CrossProduct(edge[1], normal, triangle->edgeplane[1]);
7716 CrossProduct(edge[2], normal, triangle->edgeplane[2]);
7717 VectorNormalize(triangle->edgeplane[0]);
7718 VectorNormalize(triangle->edgeplane[1]);
7719 VectorNormalize(triangle->edgeplane[2]);
7720 triangle->edgeplane[0][3] = DotProduct(triangle->edgeplane[0], triangle->vertex[0].v);
7721 triangle->edgeplane[1][3] = DotProduct(triangle->edgeplane[1], triangle->vertex[1].v);
7722 triangle->edgeplane[2][3] = DotProduct(triangle->edgeplane[2], triangle->vertex[2].v);
7723 triangle->surfaceindex = 0;
7724 // add to the combined supercontents while we're here...
7725 mleaf->combinedsupercontents |= texture->supercontents;
7728 for (i = 0;i < numtriangles;i++)
7730 // skip already-assigned triangles
7731 if (triangles[i].surfaceindex)
7733 texture = loadmodel->data_textures + triangles[i].textureindex;
7734 // assign a new surface to this triangle
7735 triangles[i].surfaceindex = surfaceindex++;
7736 axis = triangles[i].axis;
7738 // find the triangle's neighbors, this can take multiple passes
7743 for (j = i+1;j < numtriangles;j++)
7745 if (triangles[j].surfaceindex || triangles[j].axis != axis || triangles[j].texture != texture)
7747 triangle = triangles + j;
7748 for (k = i;k < j;k++)
7750 if (triangles[k].surfaceindex != surfaceindex)
7752 if (VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[0].v)
7753 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[1].v)
7754 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[2].v)
7755 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[0].v)
7756 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[1].v)
7757 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[2].v)
7758 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[0].v)
7759 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[1].v)
7760 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[2].v))
7762 // shares a vertex position
7766 for (k = 0;k < numvertices;k++)
7767 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))
7769 if (k == numvertices)
7770 break; // not a neighbor
7771 // this triangle is a neighbor and has the same axis and texture
7772 // check now if it overlaps in lightmap projection space
7773 triangles[j].surfaceindex;
7777 //triangles[i].surfaceindex = surfaceindex++;
7778 for (surfaceindex = 0;surfaceindex < numsurfaces;surfaceindex++)
7780 if (surfaces[surfaceindex].texture != texture)
7782 // check if any triangles already in this surface overlap in lightmap projection space
7789 // let the collision code simply use the surfaces
7790 mleaf->containscollisionsurfaces = mleaf->combinedsupercontents != 0;
7791 mleaf->numleafsurfaces = ?;
7792 mleaf->firstleafsurface = ?;
7794 // push combinedsupercontents up to the parent
7796 mnodeparent->combinedsupercontents |= mleaf->combinedsupercontents;
7801 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7804 const char *textbase = (char *)buffer, *text = textbase;
7808 char materialname[MAX_QPATH];
7809 int j, index1, index2, index3, first, prev, index;
7812 int numtriangles = 0;
7813 int maxtriangles = 131072;
7814 objtriangle_t *triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
7816 int maxtextures = 256, numtextures = 0, textureindex = 0;
7817 int maxv = 1024, numv = 0;
7818 int maxvt = 1024, numvt = 0;
7819 int maxvn = 1024, numvn = 0;
7820 char **texturenames;
7821 float *v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
7822 float *vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
7823 float *vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
7824 objvertex_t vfirst, vprev, vcurrent;
7829 int maxverthash = 65536, numverthash = 0;
7830 int numhashindex = 65536;
7831 struct objverthash_s
7833 struct objverthash_s *next;
7839 *hash, **verthash = Mem_Alloc(tempmempool, numhashindex * sizeof(*verthash)), *verthashdata = Mem_Alloc(tempmempool, maxverthash * sizeof(*verthashdata)), *oldverthashdata;
7842 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7844 loadmodel->modeldatatypestring = "OBJ";
7846 loadmodel->type = mod_obj;
7847 loadmodel->soundfromcenter = true;
7848 loadmodel->TraceBox = Mod_OBJ_TraceBox;
7849 loadmodel->TraceLine = Mod_OBJ_TraceLine;
7850 loadmodel->TracePoint = Mod_OBJ_TracePoint;
7851 loadmodel->PointSuperContents = Mod_OBJ_PointSuperContents;
7852 loadmodel->brush.TraceLineOfSight = Mod_OBJ_TraceLineOfSight;
7853 loadmodel->brush.SuperContentsFromNativeContents = Mod_OBJ_SuperContentsFromNativeContents;
7854 loadmodel->brush.NativeContentsFromSuperContents = Mod_OBJ_NativeContentsFromSuperContents;
7855 loadmodel->brush.GetPVS = Mod_OBJ_GetPVS;
7856 loadmodel->brush.FatPVS = Mod_OBJ_FatPVS;
7857 loadmodel->brush.BoxTouchingPVS = Mod_OBJ_BoxTouchingPVS;
7858 loadmodel->brush.BoxTouchingLeafPVS = Mod_OBJ_BoxTouchingLeafPVS;
7859 loadmodel->brush.BoxTouchingVisibleLeafs = Mod_OBJ_BoxTouchingVisibleLeafs;
7860 loadmodel->brush.FindBoxClusters = Mod_OBJ_FindBoxClusters;
7861 loadmodel->brush.LightPoint = Mod_OBJ_LightPoint;
7862 loadmodel->brush.FindNonSolidLocation = Mod_OBJ_FindNonSolidLocation;
7863 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7864 loadmodel->brush.RoundUpToHullSize = NULL;
7865 loadmodel->brush.PointInLeaf = Mod_OBJ_PointInLeaf;
7866 loadmodel->Draw = R_Q1BSP_Draw;
7867 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7868 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7869 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7870 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7871 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7872 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7873 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7874 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7875 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7880 // parse the OBJ text now
7887 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7888 line[linelen] = text[linelen];
7890 for (argc = 0;argc < (int)(sizeof(argv)/sizeof(argv[0]));argc++)
7894 while (*s == ' ' || *s == '\t')
7904 while (*s == ' ' || *s == '\t')
7909 if (argv[0][0] == '#')
7911 if (!strcmp(argv[0], "v"))
7917 v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
7920 memcpy(v, oldv, numv * sizeof(float[3]));
7924 v[numv*3+0] = atof(argv[1]);
7925 v[numv*3+1] = atof(argv[2]);
7926 v[numv*3+2] = atof(argv[3]);
7929 else if (!strcmp(argv[0], "vt"))
7935 vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
7938 memcpy(vt, oldvt, numvt * sizeof(float[2]));
7942 vt[numvt*2+0] = atof(argv[1]);
7943 vt[numvt*2+1] = atof(argv[2]);
7946 else if (!strcmp(argv[0], "vn"))
7952 vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
7955 memcpy(vn, oldvn, numvn * sizeof(float[3]));
7959 vn[numvn*3+0] = atof(argv[1]);
7960 vn[numvn*3+1] = atof(argv[2]);
7961 vn[numvn*3+2] = atof(argv[3]);
7964 else if (!strcmp(argv[0], "f"))
7966 for (j = 1;j < argc;j++)
7968 index1 = atoi(argv[j]);
7969 while(argv[j][0] && argv[j][0] != '/')
7973 index2 = atoi(argv[j]);
7974 while(argv[j][0] && argv[j][0] != '/')
7978 index3 = atoi(argv[j]);
7979 // negative refers to a recent vertex
7980 // zero means not specified
7981 // positive means an absolute vertex index
7983 index1 = numv - index1;
7985 index2 = numvt - index2;
7987 index3 = numvn - index3;
7988 VectorCopy(v + 3*index1, vcurrent.v);
7989 Vector2Copy(vt + 2*index2, vcurrent.vt);
7990 VectorCopy(vn + 3*index3, vcurrent.vn);
7991 if (numtriangles == 0)
7993 VectorCopy(vcurrent.v, mins);
7994 VectorCopy(vcurrent.v, maxs);
7998 mins[0] = min(mins[0], vcurrent.v[0]);
7999 mins[1] = min(mins[1], vcurrent.v[1]);
8000 mins[2] = min(mins[2], vcurrent.v[2]);
8001 maxs[0] = max(maxs[0], vcurrent.v[0]);
8002 maxs[1] = max(maxs[1], vcurrent.v[1]);
8003 maxs[2] = max(maxs[2], vcurrent.v[2]);
8009 if (maxtriangles <= numtriangles)
8011 objtriangle_t *oldtriangles = triangles;
8013 triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8016 memcpy(triangles, oldtriangles, maxtriangles * sizeof(*triangles));
8017 Mem_Free(oldtriangles);
8020 triangles[numtriangles].textureindex = textureindex;
8021 triangles[numtriangles].vertex[0] = vfirst;
8022 triangles[numtriangles].vertex[1] = vprev;
8023 triangles[numtriangles].vertex[2] = vcurrent;
8030 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8032 else if (!!strcmp(argv[0], "usemtl"))
8034 for (i = 0;i < numtextures;i++)
8035 if (!strcmp(texturenames[numtextures], argv[1]))
8037 if (i < numtextures)
8038 texture = textures + i;
8041 if (maxtextures <= numtextures)
8043 texture_t *oldtextures = textures;
8045 textures = Mem_Alloc(tempmempool, maxtextures * sizeof(*textures));
8048 memcpy(textures, oldtextures, numtextures * sizeof(*textures));
8049 Mem_Free(oldtextures);
8052 textureindex = numtextures++;
8053 texturenames[textureindex] = Mem_Alloc(tempmempool, strlen(argv[1]) + 1);
8054 memcpy(texturenames[textureindex], argv[1], strlen(argv[1]) + 1);
8064 // now that we have the OBJ data loaded as-is, we can convert it
8066 // load the textures
8067 loadmodel->num_textures = numtextures;
8068 loadmodel->data_textures = Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
8069 for (i = 0;i < numtextures;i++)
8070 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, texturenames[i], true, true, TEXF_MIPMAP | TEXF_ALPHA | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS);
8072 // free the texturenames array since we are now done with it
8073 for (i = 0;i < numtextures;i++)
8075 Mem_Free(texturenames[i]);
8076 texturenames[i] = NULL;
8078 Mem_Free(texturenames);
8079 texturenames = NULL;
8081 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8082 VectorCopy(mins, loadmodel->normalmins);
8083 VectorCopy(maxs, loadmodel->normalmaxs);
8084 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8085 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8086 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8087 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8088 modelradius = modelyawradius + modelradius * modelradius;
8089 modelyawradius = sqrt(modelyawradius);
8090 modelradius = sqrt(modelradius);
8091 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8092 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8093 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8094 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8095 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8096 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8097 loadmodel->radius = modelradius;
8098 loadmodel->radius2 = modelradius * modelradius;
8100 // make sure the temp triangle buffer is big enough for BSP building
8101 maxclippedtriangles = numtriangles*4;
8102 if (numtriangles > 0)
8104 clippedfronttriangles = Mem_Alloc(loadmodel->mempool, maxclippedtriangles * 2 * sizeof(objtriangle_t));
8105 clippedbacktriangles = clippedfronttriangles + maxclippedtriangles;
8108 // 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
8109 loadmodel->brush.num_leafs = 0;
8110 loadmodel->brush.num_nodes = 0;
8111 Mem_ExpandableArray_NewArray(&nodesarray, loadmodel->mempool, sizeof(objnode_t), 1024);
8112 rootnode = Mod_OBJ_BSPNodeForTriangles(triangles, numtriangles, mins, maxs, &nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8114 // convert the BSP tree to mnode_t and mleaf_t structures and convert the triangles to msurface_t...
8115 loadmodel->brush.data_leafs = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8116 loadmodel->brush.data_nodes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mnode_t));
8117 loadmodel->brush.data_planes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mplane_t));
8118 loadmodel->brush.num_leafs = 0;
8119 loadmodel->brush.num_nodes = 0;
8120 loadmodel->brush.num_planes = 0;
8121 Mod_OBJ_ConvertAndFreeBSPNode(rootnode);
8123 if (clippedfronttriangles)
8124 Mem_Free(clippedfronttriangles);
8125 maxclippedtriangles = 0;
8126 clippedfronttriangles = NULL;
8127 clippedbacktriangles = NULL;
8129 --- NOTHING DONE PAST THIS POINT ---
8131 loadmodel->numskins = LittleLong(pinmodel->num_skins);
8132 numxyz = LittleLong(pinmodel->num_xyz);
8133 numst = LittleLong(pinmodel->num_st);
8134 loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->num_tris);
8135 loadmodel->numframes = LittleLong(pinmodel->num_frames);
8136 loadmodel->surfmesh.num_morphframes = loadmodel->numframes;
8137 loadmodel->num_poses = loadmodel->surfmesh.num_morphframes;
8138 skinwidth = LittleLong(pinmodel->skinwidth);
8139 skinheight = LittleLong(pinmodel->skinheight);
8140 iskinwidth = 1.0f / skinwidth;
8141 iskinheight = 1.0f / skinheight;
8143 loadmodel->num_surfaces = 1;
8144 loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
8145 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]));
8146 loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
8147 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8148 loadmodel->sortedmodelsurfaces[0] = 0;
8149 loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
8150 loadmodel->surfmesh.data_morphmd2framesize6f = (float *)data;data += loadmodel->numframes * sizeof(float[6]);
8151 loadmodel->surfmesh.data_element3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8152 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8154 loadmodel->synctype = ST_RAND;
8157 inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
8158 skinfiles = Mod_LoadSkinFiles();
8161 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8162 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8163 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8164 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
8165 Mod_FreeSkinFiles(skinfiles);
8167 else if (loadmodel->numskins)
8169 // skins found (most likely not a player model)
8170 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8171 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8172 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8173 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
8174 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i * loadmodel->num_surfaces, inskin, true, true, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP | TEXF_COMPRESS);
8178 // no skins (most likely a player model)
8179 loadmodel->numskins = 1;
8180 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8181 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8182 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8183 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
8186 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8187 for (i = 0;i < loadmodel->numskins;i++)
8189 loadmodel->skinscenes[i].firstframe = i;
8190 loadmodel->skinscenes[i].framecount = 1;
8191 loadmodel->skinscenes[i].loop = true;
8192 loadmodel->skinscenes[i].framerate = 10;
8195 // load the triangles and stvert data
8196 inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
8197 intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
8198 md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 65536 * sizeof(hash));
8199 md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->surfmesh.num_triangles * 3 * sizeof(*hash));
8200 // swap the triangle list
8201 loadmodel->surfmesh.num_vertices = 0;
8202 for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
8204 for (j = 0;j < 3;j++)
8206 xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
8207 st = (unsigned short) LittleShort (intri[i].index_st[j]);
8210 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
8215 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
8218 hashindex = (xyz * 256 + st) & 65535;
8219 for (hash = md2verthash[hashindex];hash;hash = hash->next)
8220 if (hash->xyz == xyz && hash->st == st)
8224 hash = md2verthashdata + loadmodel->surfmesh.num_vertices++;
8227 hash->next = md2verthash[hashindex];
8228 md2verthash[hashindex] = hash;
8230 loadmodel->surfmesh.data_element3i[i*3+j] = (hash - md2verthashdata);
8234 vertremap = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(int));
8235 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));
8236 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
8237 loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)data;data += loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t);
8238 for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
8241 hash = md2verthashdata + i;
8242 vertremap[i] = hash->xyz;
8243 sts = LittleShort(inst[hash->st*2+0]);
8244 stt = LittleShort(inst[hash->st*2+1]);
8245 if (sts < 0 || sts >= skinwidth || stt < 0 || stt >= skinheight)
8247 Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, sts, stt, i);
8251 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = sts * iskinwidth;
8252 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = stt * iskinheight;
8255 Mem_Free(md2verthash);
8256 Mem_Free(md2verthashdata);
8258 // generate ushort elements array if possible
8259 if (loadmodel->surfmesh.num_vertices <= 65536)
8260 loadmodel->surfmesh.data_element3s = (unsigned short *)Mem_Alloc(loadmodel->mempool, sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles);
8263 datapointer = (base + LittleLong(pinmodel->ofs_frames));
8264 for (i = 0;i < loadmodel->surfmesh.num_morphframes;i++)
8269 pinframe = (md2frame_t *)datapointer;
8270 datapointer += sizeof(md2frame_t);
8271 // store the frame scale/translate into the appropriate array
8272 for (j = 0;j < 3;j++)
8274 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+j] = LittleFloat(pinframe->scale[j]);
8275 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+3+j] = LittleFloat(pinframe->translate[j]);
8277 // convert the vertices
8278 v = (trivertx_t *)datapointer;
8279 out = loadmodel->surfmesh.data_morphmdlvertex + i * loadmodel->surfmesh.num_vertices;
8280 for (k = 0;k < loadmodel->surfmesh.num_vertices;k++)
8281 out[k] = v[vertremap[k]];
8282 datapointer += numxyz * sizeof(trivertx_t);
8284 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
8285 loadmodel->animscenes[i].firstframe = i;
8286 loadmodel->animscenes[i].framecount = 1;
8287 loadmodel->animscenes[i].framerate = 10;
8288 loadmodel->animscenes[i].loop = true;
8291 Mem_Free(vertremap);
8293 Mod_MakeSortedSurfaces(loadmodel);
8294 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8295 Mod_Alias_CalculateBoundingBox();
8296 Mod_Alias_MorphMesh_CompileFrames();
8298 surface = loadmodel->data_surfaces;
8299 surface->texture = loadmodel->data_textures;
8300 surface->num_firsttriangle = 0;
8301 surface->num_triangles = loadmodel->surfmesh.num_triangles;
8302 surface->num_firstvertex = 0;
8303 surface->num_vertices = loadmodel->surfmesh.num_vertices;
8305 loadmodel->surfmesh.isanimated = false;
8307 if (loadmodel->surfmesh.data_element3s)
8308 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8309 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8312 #endif // !OBJASMODEL
8314 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
8316 // we already have done PVS culling at this point...
8317 // so we don't need to do it again.
8320 vec3_t testorigin, mins, maxs;
8322 testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
8323 testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
8324 testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
8326 if(model->brush.TraceLineOfSight(model, eye, testorigin))
8329 // expand the box a little
8330 mins[0] = (t+1) * minsX[0] - t * maxsX[0];
8331 maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
8332 mins[1] = (t+1) * minsX[1] - t * maxsX[1];
8333 maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
8334 mins[2] = (t+1) * minsX[2] - t * maxsX[2];
8335 maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
8337 for(i = 0; i != numsamples; ++i)
8339 testorigin[0] = lhrandom(mins[0], maxs[0]);
8340 testorigin[1] = lhrandom(mins[1], maxs[1]);
8341 testorigin[2] = lhrandom(mins[2], maxs[2]);
8343 if(model->brush.TraceLineOfSight(model, eye, testorigin))