5 #define COLLISION_EDGEDIR_DOT_EPSILON (0.999f)
6 #define COLLISION_EDGECROSS_MINLENGTH2 (1.0f / 4194304.0f)
7 #define COLLISION_SNAPSCALE (32.0f)
8 #define COLLISION_SNAP (1.0f / COLLISION_SNAPSCALE)
9 #define COLLISION_SNAP2 (2.0f / COLLISION_SNAPSCALE)
10 #define COLLISION_PLANE_DIST_EPSILON (2.0f / COLLISION_SNAPSCALE)
12 cvar_t collision_impactnudge = {0, "collision_impactnudge", "0.03125", "how much to back off from the impact"};
13 cvar_t collision_startnudge = {0, "collision_startnudge", "0", "how much to bias collision trace start"};
14 cvar_t collision_endnudge = {0, "collision_endnudge", "0", "how much to bias collision trace end"};
15 cvar_t collision_enternudge = {0, "collision_enternudge", "0", "how much to bias collision entry fraction"};
16 cvar_t collision_leavenudge = {0, "collision_leavenudge", "0", "how much to bias collision exit fraction"};
17 cvar_t collision_prefernudgedfraction = {0, "collision_prefernudgedfraction", "1", "whether to sort collision events by nudged fraction (1) or real fraction (0)"};
18 #ifdef COLLISION_STUPID_TRACE_ENDPOS_IN_SOLID_WORKAROUND
19 cvar_t collision_endposnudge = {0, "collision_endposnudge", "0", "workaround to fix trace_endpos sometimes being returned where it would be inside solid by making that collision hit (recommended: values like 1)"};
21 cvar_t collision_debug_tracelineasbox = {0, "collision_debug_tracelineasbox", "0", "workaround for any bugs in Collision_TraceLineBrushFloat by using Collision_TraceBrushBrushFloat"};
22 cvar_t collision_cache = {0, "collision_cache", "1", "store results of collision traces for next frame to reuse if possible (optimization)"};
23 //cvar_t collision_triangle_neighborsides = {0, "collision_triangle_neighborsides", "1", "override automatic side generation if triangle has neighbors with face planes that form a convex edge (perfect solution, but can not work for all edges)"};
24 cvar_t collision_triangle_bevelsides = {0, "collision_triangle_bevelsides", "1", "generate sloped edge planes on triangles - if 0, see axialedgeplanes"};
25 cvar_t collision_triangle_axialsides = {0, "collision_triangle_axialsides", "1", "generate axially-aligned edge planes on triangles - otherwise use perpendicular edge planes"};
27 mempool_t *collision_mempool;
29 void Collision_Init (void)
31 Cvar_RegisterVariable(&collision_impactnudge);
32 Cvar_RegisterVariable(&collision_startnudge);
33 Cvar_RegisterVariable(&collision_endnudge);
34 Cvar_RegisterVariable(&collision_enternudge);
35 Cvar_RegisterVariable(&collision_leavenudge);
36 Cvar_RegisterVariable(&collision_prefernudgedfraction);
37 #ifdef COLLISION_STUPID_TRACE_ENDPOS_IN_SOLID_WORKAROUND
38 Cvar_RegisterVariable(&collision_endposnudge);
40 Cvar_RegisterVariable(&collision_debug_tracelineasbox);
41 Cvar_RegisterVariable(&collision_cache);
42 // Cvar_RegisterVariable(&collision_triangle_neighborsides);
43 Cvar_RegisterVariable(&collision_triangle_bevelsides);
44 Cvar_RegisterVariable(&collision_triangle_axialsides);
45 collision_mempool = Mem_AllocPool("collision cache", 0, NULL);
46 Collision_Cache_Init(collision_mempool);
62 static void Collision_PrintBrushAsQHull(colbrushf_t *brush, const char *name)
65 Con_Printf("3 %s\n%i\n", name, brush->numpoints);
66 for (i = 0;i < brush->numpoints;i++)
67 Con_Printf("%f %f %f\n", brush->points[i].v[0], brush->points[i].v[1], brush->points[i].v[2]);
69 Con_Printf("4\n%i\n", brush->numplanes);
70 for (i = 0;i < brush->numplanes;i++)
71 Con_Printf("%f %f %f %f\n", brush->planes[i].normal[0], brush->planes[i].normal[1], brush->planes[i].normal[2], brush->planes[i].dist);
74 static void Collision_ValidateBrush(colbrushf_t *brush)
76 int j, k, pointsoffplanes, pointonplanes, pointswithinsufficientplanes, printbrush;
79 if (!brush->numpoints)
81 Con_Print("Collision_ValidateBrush: brush with no points!\n");
85 // it's ok for a brush to have one point and no planes...
86 if (brush->numplanes == 0 && brush->numpoints != 1)
88 Con_Print("Collision_ValidateBrush: brush with no planes and more than one point!\n");
95 pointswithinsufficientplanes = 0;
96 for (k = 0;k < brush->numplanes;k++)
97 if (DotProduct(brush->planes[k].normal, brush->planes[k].normal) < 0.0001f)
98 Con_Printf("Collision_ValidateBrush: plane #%i (%f %f %f %f) is degenerate\n", k, brush->planes[k].normal[0], brush->planes[k].normal[1], brush->planes[k].normal[2], brush->planes[k].dist);
99 for (j = 0;j < brush->numpoints;j++)
102 for (k = 0;k < brush->numplanes;k++)
104 d = DotProduct(brush->points[j].v, brush->planes[k].normal) - brush->planes[k].dist;
105 if (d > COLLISION_PLANE_DIST_EPSILON)
107 Con_Printf("Collision_ValidateBrush: point #%i (%f %f %f) infront of plane #%i (%f %f %f %f)\n", j, brush->points[j].v[0], brush->points[j].v[1], brush->points[j].v[2], k, brush->planes[k].normal[0], brush->planes[k].normal[1], brush->planes[k].normal[2], brush->planes[k].dist);
110 if (fabs(d) > COLLISION_PLANE_DIST_EPSILON)
115 if (pointonplanes < 3)
116 pointswithinsufficientplanes++;
118 if (pointswithinsufficientplanes)
120 Con_Print("Collision_ValidateBrush: some points have insufficient planes, every point must be on at least 3 planes to form a corner.\n");
123 if (pointsoffplanes == 0) // all points are on all planes
125 Con_Print("Collision_ValidateBrush: all points lie on all planes (degenerate, no brush volume!)\n");
130 Collision_PrintBrushAsQHull(brush, "unnamed");
133 static float nearestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
135 float dist, bestdist;
138 bestdist = DotProduct(points->v, normal);
142 dist = DotProduct(points->v, normal);
143 bestdist = min(bestdist, dist);
149 static float furthestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
151 float dist, bestdist;
154 bestdist = DotProduct(points->v, normal);
158 dist = DotProduct(points->v, normal);
159 bestdist = max(bestdist, dist);
165 static void Collision_CalcEdgeDirsForPolygonBrushFloat(colbrushf_t *brush)
168 for (i = 0, j = brush->numpoints - 1;i < brush->numpoints;j = i, i++)
169 VectorSubtract(brush->points[i].v, brush->points[j].v, brush->edgedirs[j].v);
172 colbrushf_t *Collision_NewBrushFromPlanes(mempool_t *mempool, int numoriginalplanes, const colplanef_t *originalplanes, int supercontents, int q3surfaceflags, const texture_t *texture, int hasaabbplanes)
174 // TODO: planesbuf could be replaced by a remapping table
175 int j, k, l, m, w, xyzflags;
176 int numpointsbuf = 0, maxpointsbuf = 256, numedgedirsbuf = 0, maxedgedirsbuf = 256, numplanesbuf = 0, maxplanesbuf = 256, numelementsbuf = 0, maxelementsbuf = 256;
180 colpointf_t pointsbuf[256];
181 colpointf_t edgedirsbuf[256];
182 colplanef_t planesbuf[256];
183 int elementsbuf[1024];
184 int polypointbuf[256];
189 // enable these if debugging to avoid seeing garbage in unused data-
190 memset(pointsbuf, 0, sizeof(pointsbuf));
191 memset(edgedirsbuf, 0, sizeof(edgedirsbuf));
192 memset(planesbuf, 0, sizeof(planesbuf));
193 memset(elementsbuf, 0, sizeof(elementsbuf));
194 memset(polypointbuf, 0, sizeof(polypointbuf));
195 memset(p, 0, sizeof(p));
198 // check if there are too many planes and skip the brush
199 if (numoriginalplanes >= maxplanesbuf)
201 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many planes for buffer\n");
205 // figure out how large a bounding box we need to properly compute this brush
207 for (j = 0;j < numoriginalplanes;j++)
208 maxdist = max(maxdist, fabs(originalplanes[j].dist));
209 // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
210 maxdist = floor(maxdist * (4.0 / 1024.0) + 2) * 1024.0;
211 // construct a collision brush (points, planes, and renderable mesh) from
212 // a set of planes, this also optimizes out any unnecessary planes (ones
213 // whose polygon is clipped away by the other planes)
214 for (j = 0;j < numoriginalplanes;j++)
217 VectorCopy(originalplanes[j].normal, planesbuf[numplanesbuf].normal);
218 planesbuf[numplanesbuf].dist = originalplanes[j].dist;
219 planesbuf[numplanesbuf].q3surfaceflags = originalplanes[j].q3surfaceflags;
220 planesbuf[numplanesbuf].texture = originalplanes[j].texture;
223 // create a large polygon from the plane
225 PolygonD_QuadForPlane(p[w], originalplanes[j].normal[0], originalplanes[j].normal[1], originalplanes[j].normal[2], originalplanes[j].dist, maxdist);
227 // clip it by all other planes
228 for (k = 0;k < numoriginalplanes && pnumpoints >= 3 && pnumpoints <= pmaxpoints;k++)
230 // skip the plane this polygon
231 // (nothing happens if it is processed, this is just an optimization)
234 // we want to keep the inside of the brush plane so we flip
236 PolygonD_Divide(pnumpoints, p[w], -originalplanes[k].normal[0], -originalplanes[k].normal[1], -originalplanes[k].normal[2], -originalplanes[k].dist, COLLISION_PLANE_DIST_EPSILON, pmaxpoints, p[!w], &pnumpoints, 0, NULL, NULL, NULL);
241 // if nothing is left, skip it
244 //Con_DPrintf("Collision_NewBrushFromPlanes: warning: polygon for plane %f %f %f %f clipped away\n", originalplanes[j].normal[0], originalplanes[j].normal[1], originalplanes[j].normal[2], originalplanes[j].dist);
248 for (k = 0;k < pnumpoints;k++)
252 for (l = 0;l < numoriginalplanes;l++)
253 if (fabs(DotProduct(&p[w][k*3], originalplanes[l].normal) - originalplanes[l].dist) < COLLISION_PLANE_DIST_EPSILON)
260 Con_DPrintf("Collision_NewBrushFromPlanes: warning: polygon point does not lie on at least 3 planes\n");
264 // check if there are too many polygon vertices for buffer
265 if (pnumpoints > pmaxpoints)
267 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
271 // check if there are too many triangle elements for buffer
272 if (numelementsbuf + (pnumpoints - 2) * 3 > maxelementsbuf)
274 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many triangle elements for buffer\n");
278 // add the unique points for this polygon
279 for (k = 0;k < pnumpoints;k++)
282 // downgrade to float precision before comparing
283 VectorCopy(&p[w][k*3], v);
285 // check if there is already a matching point (no duplicates)
286 for (m = 0;m < numpointsbuf;m++)
287 if (VectorDistance2(v, pointsbuf[m].v) < COLLISION_SNAP2)
290 // if there is no match, add a new one
291 if (m == numpointsbuf)
293 // check if there are too many and skip the brush
294 if (numpointsbuf >= maxpointsbuf)
296 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
300 VectorCopy(&p[w][k*3], pointsbuf[numpointsbuf].v);
304 // store the index into a buffer
308 // add the triangles for the polygon
309 // (this particular code makes a triangle fan)
310 for (k = 0;k < pnumpoints - 2;k++)
312 elementsbuf[numelementsbuf++] = polypointbuf[0];
313 elementsbuf[numelementsbuf++] = polypointbuf[k + 1];
314 elementsbuf[numelementsbuf++] = polypointbuf[k + 2];
317 // add the unique edgedirs for this polygon
318 for (k = 0, l = pnumpoints-1;k < pnumpoints;l = k, k++)
321 // downgrade to float precision before comparing
322 VectorSubtract(&p[w][k*3], &p[w][l*3], dir);
323 VectorNormalize(dir);
325 // check if there is already a matching edgedir (no duplicates)
326 for (m = 0;m < numedgedirsbuf;m++)
327 if (DotProduct(dir, edgedirsbuf[m].v) >= COLLISION_EDGEDIR_DOT_EPSILON)
329 // skip this if there is
330 if (m < numedgedirsbuf)
333 // try again with negated edgedir
334 VectorNegate(dir, dir);
335 // check if there is already a matching edgedir (no duplicates)
336 for (m = 0;m < numedgedirsbuf;m++)
337 if (DotProduct(dir, edgedirsbuf[m].v) >= COLLISION_EDGEDIR_DOT_EPSILON)
339 // if there is no match, add a new one
340 if (m == numedgedirsbuf)
342 // check if there are too many and skip the brush
343 if (numedgedirsbuf >= maxedgedirsbuf)
345 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many edgedirs for buffer\n");
349 VectorCopy(dir, edgedirsbuf[numedgedirsbuf].v);
354 // if any normal is not purely axial, it's not an axis-aligned box
355 if (isaabb && (originalplanes[j].normal[0] == 0) + (originalplanes[j].normal[1] == 0) + (originalplanes[j].normal[2] == 0) < 2)
359 // if nothing is left, there's nothing to allocate
360 if (numplanesbuf < 4)
362 Con_DPrintf("Collision_NewBrushFromPlanes: failed to build collision brush: %i triangles, %i planes (input was %i planes), %i vertices\n", numelementsbuf / 3, numplanesbuf, numoriginalplanes, numpointsbuf);
366 // if no triangles or points could be constructed, then this routine failed but the brush is not discarded
367 if (numelementsbuf < 12 || numpointsbuf < 4)
368 Con_DPrintf("Collision_NewBrushFromPlanes: unable to rebuild triangles/points for collision brush: %i triangles, %i planes (input was %i planes), %i vertices\n", numelementsbuf / 3, numplanesbuf, numoriginalplanes, numpointsbuf);
370 // validate plane distances
371 for (j = 0;j < numplanesbuf;j++)
373 float d = furthestplanedist_float(planesbuf[j].normal, pointsbuf, numpointsbuf);
374 if (fabs(planesbuf[j].dist - d) > COLLISION_PLANE_DIST_EPSILON)
375 Con_DPrintf("plane %f %f %f %f mismatches dist %f\n", planesbuf[j].normal[0], planesbuf[j].normal[1], planesbuf[j].normal[2], planesbuf[j].dist, d);
378 // allocate the brush and copy to it
379 brush = (colbrushf_t *)Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colpointf_t) * numpointsbuf + sizeof(colpointf_t) * numedgedirsbuf + sizeof(colplanef_t) * numplanesbuf + sizeof(int) * numelementsbuf);
380 brush->isaabb = isaabb;
381 brush->hasaabbplanes = hasaabbplanes;
382 brush->supercontents = supercontents;
383 brush->numplanes = numplanesbuf;
384 brush->numedgedirs = numedgedirsbuf;
385 brush->numpoints = numpointsbuf;
386 brush->numtriangles = numelementsbuf / 3;
387 brush->planes = (colplanef_t *)(brush + 1);
388 brush->points = (colpointf_t *)(brush->planes + brush->numplanes);
389 brush->edgedirs = (colpointf_t *)(brush->points + brush->numpoints);
390 brush->elements = (int *)(brush->points + brush->numpoints);
391 brush->q3surfaceflags = q3surfaceflags;
392 brush->texture = texture;
393 for (j = 0;j < brush->numpoints;j++)
395 brush->points[j].v[0] = pointsbuf[j].v[0];
396 brush->points[j].v[1] = pointsbuf[j].v[1];
397 brush->points[j].v[2] = pointsbuf[j].v[2];
399 for (j = 0;j < brush->numedgedirs;j++)
401 brush->edgedirs[j].v[0] = edgedirsbuf[j].v[0];
402 brush->edgedirs[j].v[1] = edgedirsbuf[j].v[1];
403 brush->edgedirs[j].v[2] = edgedirsbuf[j].v[2];
405 for (j = 0;j < brush->numplanes;j++)
407 brush->planes[j].normal[0] = planesbuf[j].normal[0];
408 brush->planes[j].normal[1] = planesbuf[j].normal[1];
409 brush->planes[j].normal[2] = planesbuf[j].normal[2];
410 brush->planes[j].dist = planesbuf[j].dist;
411 brush->planes[j].q3surfaceflags = planesbuf[j].q3surfaceflags;
412 brush->planes[j].texture = planesbuf[j].texture;
414 for (j = 0;j < brush->numtriangles * 3;j++)
415 brush->elements[j] = elementsbuf[j];
418 VectorClear(brush->mins);
419 VectorClear(brush->maxs);
420 for (j = 0;j < min(6, numoriginalplanes);j++)
422 if (originalplanes[j].normal[0] == 1) {xyzflags |= 1;brush->maxs[0] = originalplanes[j].dist;}
423 else if (originalplanes[j].normal[0] == -1) {xyzflags |= 2;brush->mins[0] = -originalplanes[j].dist;}
424 else if (originalplanes[j].normal[1] == 1) {xyzflags |= 4;brush->maxs[1] = originalplanes[j].dist;}
425 else if (originalplanes[j].normal[1] == -1) {xyzflags |= 8;brush->mins[1] = -originalplanes[j].dist;}
426 else if (originalplanes[j].normal[2] == 1) {xyzflags |= 16;brush->maxs[2] = originalplanes[j].dist;}
427 else if (originalplanes[j].normal[2] == -1) {xyzflags |= 32;brush->mins[2] = -originalplanes[j].dist;}
429 // if not all xyzflags were set, then this is not a brush from q3map/q3map2, and needs reconstruction of the bounding box
430 // (this case works for any brush with valid points, but sometimes brushes are not reconstructed properly and hence the points are not valid, so this is reserved as a fallback case)
433 VectorCopy(brush->points[0].v, brush->mins);
434 VectorCopy(brush->points[0].v, brush->maxs);
435 for (j = 1;j < brush->numpoints;j++)
437 brush->mins[0] = min(brush->mins[0], brush->points[j].v[0]);
438 brush->mins[1] = min(brush->mins[1], brush->points[j].v[1]);
439 brush->mins[2] = min(brush->mins[2], brush->points[j].v[2]);
440 brush->maxs[0] = max(brush->maxs[0], brush->points[j].v[0]);
441 brush->maxs[1] = max(brush->maxs[1], brush->points[j].v[1]);
442 brush->maxs[2] = max(brush->maxs[2], brush->points[j].v[2]);
451 Collision_ValidateBrush(brush);
457 void Collision_CalcPlanesForTriangleBrushFloat(colbrushf_t *brush)
460 float edge0[3], edge1[3], edge2[3];
463 TriangleNormal(brush->points[0].v, brush->points[1].v, brush->points[2].v, brush->planes[0].normal);
464 if (DotProduct(brush->planes[0].normal, brush->planes[0].normal) < 0.0001f)
466 // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
467 // note that some of these exist in q3bsp bspline patches
468 brush->numplanes = 0;
472 // there are 5 planes (front, back, sides) and 3 edges
473 brush->numplanes = 5;
474 brush->numedgedirs = 3;
475 VectorNormalize(brush->planes[0].normal);
476 brush->planes[0].dist = DotProduct(brush->points->v, brush->planes[0].normal);
477 VectorNegate(brush->planes[0].normal, brush->planes[1].normal);
478 brush->planes[1].dist = -brush->planes[0].dist;
479 // edge directions are easy to calculate
480 VectorSubtract(brush->points[2].v, brush->points[0].v, edge0);
481 VectorSubtract(brush->points[0].v, brush->points[1].v, edge1);
482 VectorSubtract(brush->points[1].v, brush->points[2].v, edge2);
483 VectorCopy(edge0, brush->edgedirs[0].v);
484 VectorCopy(edge1, brush->edgedirs[1].v);
485 VectorCopy(edge2, brush->edgedirs[2].v);
486 // now select an algorithm to generate the side planes
487 if (collision_triangle_bevelsides.integer)
489 // use 45 degree slopes at the edges of the triangle to make a sinking trace error turn into "riding up" the slope rather than getting stuck
490 CrossProduct(edge0, brush->planes->normal, brush->planes[2].normal);
491 CrossProduct(edge1, brush->planes->normal, brush->planes[3].normal);
492 CrossProduct(edge2, brush->planes->normal, brush->planes[4].normal);
493 VectorNormalize(brush->planes[2].normal);
494 VectorNormalize(brush->planes[3].normal);
495 VectorNormalize(brush->planes[4].normal);
496 VectorAdd(brush->planes[2].normal, brush->planes[0].normal, brush->planes[2].normal);
497 VectorAdd(brush->planes[3].normal, brush->planes[0].normal, brush->planes[3].normal);
498 VectorAdd(brush->planes[4].normal, brush->planes[0].normal, brush->planes[4].normal);
499 VectorNormalize(brush->planes[2].normal);
500 VectorNormalize(brush->planes[3].normal);
501 VectorNormalize(brush->planes[4].normal);
503 else if (collision_triangle_axialsides.integer)
505 float projectionnormal[3], projectionedge0[3], projectionedge1[3], projectionedge2[3];
507 float dist, bestdist;
508 bestdist = fabs(brush->planes[0].normal[0]);
510 for (i = 1;i < 3;i++)
512 dist = fabs(brush->planes[0].normal[i]);
519 VectorClear(projectionnormal);
520 if (brush->planes[0].normal[best] < 0)
521 projectionnormal[best] = -1;
523 projectionnormal[best] = 1;
524 VectorCopy(edge0, projectionedge0);
525 VectorCopy(edge1, projectionedge1);
526 VectorCopy(edge2, projectionedge2);
527 projectionedge0[best] = 0;
528 projectionedge1[best] = 0;
529 projectionedge2[best] = 0;
530 CrossProduct(projectionedge0, projectionnormal, brush->planes[2].normal);
531 CrossProduct(projectionedge1, projectionnormal, brush->planes[3].normal);
532 CrossProduct(projectionedge2, projectionnormal, brush->planes[4].normal);
533 VectorNormalize(brush->planes[2].normal);
534 VectorNormalize(brush->planes[3].normal);
535 VectorNormalize(brush->planes[4].normal);
539 CrossProduct(edge0, brush->planes->normal, brush->planes[2].normal);
540 CrossProduct(edge1, brush->planes->normal, brush->planes[3].normal);
541 CrossProduct(edge2, brush->planes->normal, brush->planes[4].normal);
542 VectorNormalize(brush->planes[2].normal);
543 VectorNormalize(brush->planes[3].normal);
544 VectorNormalize(brush->planes[4].normal);
546 brush->planes[2].dist = DotProduct(brush->points[2].v, brush->planes[2].normal);
547 brush->planes[3].dist = DotProduct(brush->points[0].v, brush->planes[3].normal);
548 brush->planes[4].dist = DotProduct(brush->points[1].v, brush->planes[4].normal);
550 if (developer_extra.integer)
552 // validity check - will be disabled later
553 Collision_ValidateBrush(brush);
554 for (i = 0;i < brush->numplanes;i++)
557 for (j = 0, p = brush->points;j < brush->numpoints;j++, p++)
558 if (DotProduct(p->v, brush->planes[i].normal) > brush->planes[i].dist + COLLISION_PLANE_DIST_EPSILON)
559 Con_DPrintf("Error in brush plane generation, plane %i\n", i);
564 colbrushf_t *Collision_AllocBrushFromPermanentPolygonFloat(mempool_t *mempool, int numpoints, float *points, int supercontents, int q3surfaceflags, const texture_t *texture)
567 brush = (colbrushf_t *)Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colplanef_t) * (numpoints + 2) + sizeof(colpointf_t) * numpoints);
568 brush->isaabb = false;
569 brush->hasaabbplanes = false;
570 brush->supercontents = supercontents;
571 brush->numpoints = numpoints;
572 brush->numedgedirs = numpoints;
573 brush->numplanes = numpoints + 2;
574 brush->planes = (colplanef_t *)(brush + 1);
575 brush->points = (colpointf_t *)points;
576 brush->edgedirs = (colpointf_t *)(brush->planes + brush->numplanes);
577 brush->q3surfaceflags = q3surfaceflags;
578 brush->texture = texture;
579 Sys_Error("Collision_AllocBrushFromPermanentPolygonFloat: FIXME: this code needs to be updated to generate a mesh...");
583 // NOTE: start and end of each brush pair must have same numplanes/numpoints
584 void Collision_TraceBrushBrushFloat(trace_t *trace, const colbrushf_t *trace_start, const colbrushf_t *trace_end, const colbrushf_t *other_start, const colbrushf_t *other_end)
586 int nplane, nplane2, nedge1, nedge2, hitq3surfaceflags = 0;
587 int tracenumedgedirs = trace_start->numedgedirs;
588 //int othernumedgedirs = other_start->numedgedirs;
589 int tracenumpoints = trace_start->numpoints;
590 int othernumpoints = other_start->numpoints;
591 int numplanes1 = other_start->numplanes;
592 int numplanes2 = numplanes1 + trace_start->numplanes;
593 int numplanes3 = numplanes2 + trace_start->numedgedirs * other_start->numedgedirs * 2;
594 vec_t enterfrac = -1, leavefrac = 1, startdist, enddist, ie, f, imove, enterfrac2 = -1;
597 vec4_t newimpactplane;
598 const texture_t *hittexture = NULL;
599 vec_t startdepth = 1;
600 vec3_t startdepthnormal;
602 VectorClear(startdepthnormal);
603 Vector4Clear(newimpactplane);
605 // fast case for AABB vs compiled brushes (which begin with AABB planes and also have precomputed bevels for AABB collisions)
606 if (trace_start->isaabb && other_start->hasaabbplanes)
607 numplanes3 = numplanes2 = numplanes1;
609 // Separating Axis Theorem:
610 // if a supporting vector (plane normal) can be found that separates two
611 // objects, they are not colliding.
614 // reduce the size of one object to a point while enlarging the other to
615 // represent the space that point can not occupy.
617 // try every plane we can construct between the two brushes and measure
618 // the distance between them.
619 for (nplane = 0;nplane < numplanes3;nplane++)
621 if (nplane < numplanes1)
624 VectorCopy(other_start->planes[nplane2].normal, startplane);
625 VectorCopy(other_end->planes[nplane2].normal, endplane);
627 else if (nplane < numplanes2)
629 nplane2 = nplane - numplanes1;
630 VectorCopy(trace_start->planes[nplane2].normal, startplane);
631 VectorCopy(trace_end->planes[nplane2].normal, endplane);
635 // pick an edgedir from each brush and cross them
636 nplane2 = nplane - numplanes2;
637 nedge1 = nplane2 >> 1;
638 nedge2 = nedge1 / tracenumedgedirs;
639 nedge1 -= nedge2 * tracenumedgedirs;
642 CrossProduct(trace_start->edgedirs[nedge1].v, other_start->edgedirs[nedge2].v, startplane);
643 if (VectorLength2(startplane) < COLLISION_EDGECROSS_MINLENGTH2)
644 continue; // degenerate crossproduct
645 CrossProduct(trace_end->edgedirs[nedge1].v, other_end->edgedirs[nedge2].v, endplane);
646 if (VectorLength2(endplane) < COLLISION_EDGECROSS_MINLENGTH2)
647 continue; // degenerate crossproduct
651 CrossProduct(other_start->edgedirs[nedge2].v, trace_start->edgedirs[nedge1].v, startplane);
652 if (VectorLength2(startplane) < COLLISION_EDGECROSS_MINLENGTH2)
653 continue; // degenerate crossproduct
654 CrossProduct(other_end->edgedirs[nedge2].v, trace_end->edgedirs[nedge1].v, endplane);
655 if (VectorLength2(endplane) < COLLISION_EDGECROSS_MINLENGTH2)
656 continue; // degenerate crossproduct
658 VectorNormalize(startplane);
659 VectorNormalize(endplane);
661 startplane[3] = furthestplanedist_float(startplane, other_start->points, othernumpoints);
662 endplane[3] = furthestplanedist_float(startplane, other_end->points, othernumpoints);
663 startdist = nearestplanedist_float(startplane, trace_start->points, tracenumpoints) - startplane[3] - collision_startnudge.value;
664 enddist = nearestplanedist_float(endplane, trace_end->points, tracenumpoints) - endplane[3] - collision_endnudge.value;
665 //Con_Printf("%c%i: startdist = %f, enddist = %f, startdist / (startdist - enddist) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, startdist, enddist, startdist / (startdist - enddist));
667 // aside from collisions, this is also used for error correction
668 if (startdist < collision_impactnudge.value && nplane < numplanes1 && (startdepth < startdist || startdepth == 1))
670 startdepth = startdist;
671 VectorCopy(startplane, startdepthnormal);
674 if (startdist > enddist)
677 if (enddist >= collision_enternudge.value)
682 imove = 1 / (startdist - enddist);
683 f = (startdist - collision_enternudge.value) * imove;
686 // check if this will reduce the collision time range
689 // reduced collision time range
691 // if the collision time range is now empty, no collision
692 if (enterfrac > leavefrac)
694 // if the collision would be further away than the trace's
695 // existing collision data, we don't care about this
697 if (enterfrac > trace->realfraction)
699 // calculate the nudged fraction and impact normal we'll
700 // need if we accept this collision later
701 enterfrac2 = (startdist - collision_impactnudge.value) * imove;
702 ie = 1.0f - enterfrac;
703 newimpactplane[0] = startplane[0] * ie + endplane[0] * enterfrac;
704 newimpactplane[1] = startplane[1] * ie + endplane[1] * enterfrac;
705 newimpactplane[2] = startplane[2] * ie + endplane[2] * enterfrac;
706 newimpactplane[3] = startplane[3] * ie + endplane[3] * enterfrac;
707 if (nplane < numplanes1)
709 // use the plane from other
711 hitq3surfaceflags = other_start->planes[nplane2].q3surfaceflags;
712 hittexture = other_start->planes[nplane2].texture;
714 else if (nplane < numplanes2)
716 // use the plane from trace
717 nplane2 = nplane - numplanes1;
718 hitq3surfaceflags = trace_start->planes[nplane2].q3surfaceflags;
719 hittexture = trace_start->planes[nplane2].texture;
723 hitq3surfaceflags = other_start->q3surfaceflags;
724 hittexture = other_start->texture;
731 // moving out of brush
737 f = (startdist + collision_leavenudge.value) / (startdist - enddist);
740 // check if this will reduce the collision time range
743 // reduced collision time range
745 // if the collision time range is now empty, no collision
746 if (enterfrac > leavefrac)
753 // at this point we know the trace overlaps the brush because it was not
754 // rejected at any point in the loop above
756 // see if the trace started outside the brush or not
759 // started outside, and overlaps, therefore there is a collision here
760 // store out the impact information
761 if (trace->hitsupercontentsmask & other_start->supercontents)
763 trace->hitsupercontents = other_start->supercontents;
764 trace->hitq3surfaceflags = hitq3surfaceflags;
765 trace->hittexture = hittexture;
766 trace->realfraction = bound(0, enterfrac, 1);
767 trace->fraction = bound(0, enterfrac2, 1);
768 if (collision_prefernudgedfraction.integer)
769 trace->realfraction = trace->fraction;
770 VectorCopy(newimpactplane, trace->plane.normal);
771 trace->plane.dist = newimpactplane[3];
776 // started inside, update startsolid and friends
777 trace->startsupercontents |= other_start->supercontents;
778 if (trace->hitsupercontentsmask & other_start->supercontents)
780 trace->startsolid = true;
782 trace->allsolid = true;
783 VectorCopy(newimpactplane, trace->plane.normal);
784 trace->plane.dist = newimpactplane[3];
785 if (trace->startdepth > startdepth)
787 trace->startdepth = startdepth;
788 VectorCopy(startdepthnormal, trace->startdepthnormal);
794 // NOTE: start and end of each brush pair must have same numplanes/numpoints
795 void Collision_TraceLineBrushFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const colbrushf_t *other_start, const colbrushf_t *other_end)
797 int nplane, hitq3surfaceflags = 0;
798 int numplanes = other_start->numplanes;
799 vec_t enterfrac = -1, leavefrac = 1, startdist, enddist, ie, f, imove, enterfrac2 = -1;
802 vec4_t newimpactplane;
803 const texture_t *hittexture = NULL;
804 vec_t startdepth = 1;
805 vec3_t startdepthnormal;
807 if (collision_debug_tracelineasbox.integer)
809 colboxbrushf_t thisbrush_start, thisbrush_end;
810 Collision_BrushForBox(&thisbrush_start, linestart, linestart, 0, 0, NULL);
811 Collision_BrushForBox(&thisbrush_end, lineend, lineend, 0, 0, NULL);
812 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, other_start, other_end);
816 VectorClear(startdepthnormal);
817 Vector4Clear(newimpactplane);
819 // Separating Axis Theorem:
820 // if a supporting vector (plane normal) can be found that separates two
821 // objects, they are not colliding.
824 // reduce the size of one object to a point while enlarging the other to
825 // represent the space that point can not occupy.
827 // try every plane we can construct between the two brushes and measure
828 // the distance between them.
829 for (nplane = 0;nplane < numplanes;nplane++)
831 VectorCopy(other_start->planes[nplane].normal, startplane);
832 startplane[3] = other_start->planes[nplane].dist;
833 VectorCopy(other_end->planes[nplane].normal, endplane);
834 endplane[3] = other_end->planes[nplane].dist;
835 startdist = DotProduct(linestart, startplane) - startplane[3] - collision_startnudge.value;
836 enddist = DotProduct(lineend, endplane) - endplane[3] - collision_endnudge.value;
837 //Con_Printf("%c%i: startdist = %f, enddist = %f, startdist / (startdist - enddist) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, startdist, enddist, startdist / (startdist - enddist));
839 // aside from collisions, this is also used for error correction
840 if (startdist < collision_impactnudge.value && (startdepth < startdist || startdepth == 1))
842 startdepth = startdist;
843 VectorCopy(startplane, startdepthnormal);
846 if (startdist > enddist)
849 if (enddist >= collision_enternudge.value)
854 imove = 1 / (startdist - enddist);
855 f = (startdist - collision_enternudge.value) * imove;
858 // check if this will reduce the collision time range
861 // reduced collision time range
863 // if the collision time range is now empty, no collision
864 if (enterfrac > leavefrac)
866 // if the collision would be further away than the trace's
867 // existing collision data, we don't care about this
869 if (enterfrac > trace->realfraction)
871 // calculate the nudged fraction and impact normal we'll
872 // need if we accept this collision later
873 enterfrac2 = (startdist - collision_impactnudge.value) * imove;
874 ie = 1.0f - enterfrac;
875 newimpactplane[0] = startplane[0] * ie + endplane[0] * enterfrac;
876 newimpactplane[1] = startplane[1] * ie + endplane[1] * enterfrac;
877 newimpactplane[2] = startplane[2] * ie + endplane[2] * enterfrac;
878 newimpactplane[3] = startplane[3] * ie + endplane[3] * enterfrac;
879 hitq3surfaceflags = other_start->planes[nplane].q3surfaceflags;
880 hittexture = other_start->planes[nplane].texture;
886 // moving out of brush
892 f = (startdist + collision_leavenudge.value) / (startdist - enddist);
895 // check if this will reduce the collision time range
898 // reduced collision time range
900 // if the collision time range is now empty, no collision
901 if (enterfrac > leavefrac)
908 // at this point we know the trace overlaps the brush because it was not
909 // rejected at any point in the loop above
911 // see if the trace started outside the brush or not
914 // started outside, and overlaps, therefore there is a collision here
915 // store out the impact information
916 if (trace->hitsupercontentsmask & other_start->supercontents)
918 trace->hitsupercontents = other_start->supercontents;
919 trace->hitq3surfaceflags = hitq3surfaceflags;
920 trace->hittexture = hittexture;
921 trace->realfraction = bound(0, enterfrac, 1);
922 trace->fraction = bound(0, enterfrac2, 1);
923 if (collision_prefernudgedfraction.integer)
924 trace->realfraction = trace->fraction;
925 VectorCopy(newimpactplane, trace->plane.normal);
926 trace->plane.dist = newimpactplane[3];
931 // started inside, update startsolid and friends
932 trace->startsupercontents |= other_start->supercontents;
933 if (trace->hitsupercontentsmask & other_start->supercontents)
935 trace->startsolid = true;
937 trace->allsolid = true;
938 VectorCopy(newimpactplane, trace->plane.normal);
939 trace->plane.dist = newimpactplane[3];
940 if (trace->startdepth > startdepth)
942 trace->startdepth = startdepth;
943 VectorCopy(startdepthnormal, trace->startdepthnormal);
949 qboolean Collision_PointInsideBrushFloat(const vec3_t point, const colbrushf_t *brush)
952 const colplanef_t *plane;
954 if (!BoxesOverlap(point, point, brush->mins, brush->maxs))
956 for (nplane = 0, plane = brush->planes;nplane < brush->numplanes;nplane++, plane++)
957 if (DotProduct(plane->normal, point) > plane->dist)
962 void Collision_TracePointBrushFloat(trace_t *trace, const vec3_t point, const colbrushf_t *thatbrush)
964 if (!Collision_PointInsideBrushFloat(point, thatbrush))
967 trace->startsupercontents |= thatbrush->supercontents;
968 if (trace->hitsupercontentsmask & thatbrush->supercontents)
970 trace->startsolid = true;
971 trace->allsolid = true;
975 static void Collision_SnapCopyPoints(int numpoints, const colpointf_t *in, colpointf_t *out, float fractionprecision, float invfractionprecision)
978 for (i = 0;i < numpoints;i++)
980 out[i].v[0] = floor(in[i].v[0] * fractionprecision + 0.5f) * invfractionprecision;
981 out[i].v[1] = floor(in[i].v[1] * fractionprecision + 0.5f) * invfractionprecision;
982 out[i].v[2] = floor(in[i].v[2] * fractionprecision + 0.5f) * invfractionprecision;
986 void Collision_TraceBrushTriangleMeshFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int numtriangles, const int *element3i, const float *vertex3f, int stride, float *bbox6f, int supercontents, int q3surfaceflags, const texture_t *texture, const vec3_t segmentmins, const vec3_t segmentmaxs)
989 colpointf_t points[3];
990 colpointf_t edgedirs[3];
991 colplanef_t planes[5];
993 memset(&brush, 0, sizeof(brush));
994 brush.isaabb = false;
995 brush.hasaabbplanes = false;
997 brush.numedgedirs = 3;
999 brush.points = points;
1000 brush.edgedirs = edgedirs;
1001 brush.planes = planes;
1002 brush.supercontents = supercontents;
1003 brush.q3surfaceflags = q3surfaceflags;
1004 brush.texture = texture;
1005 for (i = 0;i < brush.numplanes;i++)
1007 brush.planes[i].q3surfaceflags = q3surfaceflags;
1008 brush.planes[i].texture = texture;
1013 cnt = (numtriangles + stride - 1) / stride;
1014 for(i = 0; i < cnt; ++i)
1016 if(BoxesOverlap(bbox6f + i * 6, bbox6f + i * 6 + 3, segmentmins, segmentmaxs))
1018 for(k = 0; k < stride; ++k)
1020 tri = i * stride + k;
1021 if(tri >= numtriangles)
1023 VectorCopy(vertex3f + element3i[tri * 3 + 0] * 3, points[0].v);
1024 VectorCopy(vertex3f + element3i[tri * 3 + 1] * 3, points[1].v);
1025 VectorCopy(vertex3f + element3i[tri * 3 + 2] * 3, points[2].v);
1026 Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1027 Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1028 Collision_CalcPlanesForTriangleBrushFloat(&brush);
1029 //Collision_PrintBrushAsQHull(&brush, "brush");
1030 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1035 else if(stride == 0)
1037 for (i = 0;i < numtriangles;i++, element3i += 3)
1039 if (TriangleBBoxOverlapsBox(vertex3f + element3i[0]*3, vertex3f + element3i[1]*3, vertex3f + element3i[2]*3, segmentmins, segmentmaxs))
1041 VectorCopy(vertex3f + element3i[0] * 3, points[0].v);
1042 VectorCopy(vertex3f + element3i[1] * 3, points[1].v);
1043 VectorCopy(vertex3f + element3i[2] * 3, points[2].v);
1044 Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1045 Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1046 Collision_CalcPlanesForTriangleBrushFloat(&brush);
1047 //Collision_PrintBrushAsQHull(&brush, "brush");
1048 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1054 for (i = 0;i < numtriangles;i++, element3i += 3)
1056 VectorCopy(vertex3f + element3i[0] * 3, points[0].v);
1057 VectorCopy(vertex3f + element3i[1] * 3, points[1].v);
1058 VectorCopy(vertex3f + element3i[2] * 3, points[2].v);
1059 Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1060 Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1061 Collision_CalcPlanesForTriangleBrushFloat(&brush);
1062 //Collision_PrintBrushAsQHull(&brush, "brush");
1063 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1068 void Collision_TraceLineTriangleMeshFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, int numtriangles, const int *element3i, const float *vertex3f, int stride, float *bbox6f, int supercontents, int q3surfaceflags, const texture_t *texture, const vec3_t segmentmins, const vec3_t segmentmaxs)
1071 // FIXME: snap vertices?
1075 cnt = (numtriangles + stride - 1) / stride;
1076 for(i = 0; i < cnt; ++i)
1078 if(BoxesOverlap(bbox6f + i * 6, bbox6f + i * 6 + 3, segmentmins, segmentmaxs))
1080 for(k = 0; k < stride; ++k)
1082 tri = i * stride + k;
1083 if(tri >= numtriangles)
1085 Collision_TraceLineTriangleFloat(trace, linestart, lineend, vertex3f + element3i[tri * 3 + 0] * 3, vertex3f + element3i[tri * 3 + 1] * 3, vertex3f + element3i[tri * 3 + 2] * 3, supercontents, q3surfaceflags, texture);
1092 for (i = 0;i < numtriangles;i++, element3i += 3)
1093 Collision_TraceLineTriangleFloat(trace, linestart, lineend, vertex3f + element3i[0] * 3, vertex3f + element3i[1] * 3, vertex3f + element3i[2] * 3, supercontents, q3surfaceflags, texture);
1097 void Collision_TraceBrushTriangleFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, const float *v0, const float *v1, const float *v2, int supercontents, int q3surfaceflags, const texture_t *texture)
1100 colpointf_t points[3];
1101 colpointf_t edgedirs[3];
1102 colplanef_t planes[5];
1104 memset(&brush, 0, sizeof(brush));
1105 brush.isaabb = false;
1106 brush.hasaabbplanes = false;
1107 brush.numpoints = 3;
1108 brush.numedgedirs = 3;
1109 brush.numplanes = 5;
1110 brush.points = points;
1111 brush.edgedirs = edgedirs;
1112 brush.planes = planes;
1113 brush.supercontents = supercontents;
1114 brush.q3surfaceflags = q3surfaceflags;
1115 brush.texture = texture;
1116 for (i = 0;i < brush.numplanes;i++)
1118 brush.planes[i].q3surfaceflags = q3surfaceflags;
1119 brush.planes[i].texture = texture;
1121 VectorCopy(v0, points[0].v);
1122 VectorCopy(v1, points[1].v);
1123 VectorCopy(v2, points[2].v);
1124 Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1125 Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1126 Collision_CalcPlanesForTriangleBrushFloat(&brush);
1127 //Collision_PrintBrushAsQHull(&brush, "brush");
1128 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1131 void Collision_BrushForBox(colboxbrushf_t *boxbrush, const vec3_t mins, const vec3_t maxs, int supercontents, int q3surfaceflags, const texture_t *texture)
1134 memset(boxbrush, 0, sizeof(*boxbrush));
1135 boxbrush->brush.isaabb = true;
1136 boxbrush->brush.hasaabbplanes = true;
1137 boxbrush->brush.points = boxbrush->points;
1138 boxbrush->brush.edgedirs = boxbrush->edgedirs;
1139 boxbrush->brush.planes = boxbrush->planes;
1140 boxbrush->brush.supercontents = supercontents;
1141 boxbrush->brush.q3surfaceflags = q3surfaceflags;
1142 boxbrush->brush.texture = texture;
1143 if (VectorCompare(mins, maxs))
1146 boxbrush->brush.numpoints = 1;
1147 boxbrush->brush.numedgedirs = 0;
1148 boxbrush->brush.numplanes = 0;
1149 VectorCopy(mins, boxbrush->brush.points[0].v);
1153 boxbrush->brush.numpoints = 8;
1154 boxbrush->brush.numedgedirs = 3;
1155 boxbrush->brush.numplanes = 6;
1156 // there are 8 points on a box
1157 // there are 3 edgedirs on a box (both signs are tested in collision)
1158 // there are 6 planes on a box
1159 VectorSet(boxbrush->brush.points[0].v, mins[0], mins[1], mins[2]);
1160 VectorSet(boxbrush->brush.points[1].v, maxs[0], mins[1], mins[2]);
1161 VectorSet(boxbrush->brush.points[2].v, mins[0], maxs[1], mins[2]);
1162 VectorSet(boxbrush->brush.points[3].v, maxs[0], maxs[1], mins[2]);
1163 VectorSet(boxbrush->brush.points[4].v, mins[0], mins[1], maxs[2]);
1164 VectorSet(boxbrush->brush.points[5].v, maxs[0], mins[1], maxs[2]);
1165 VectorSet(boxbrush->brush.points[6].v, mins[0], maxs[1], maxs[2]);
1166 VectorSet(boxbrush->brush.points[7].v, maxs[0], maxs[1], maxs[2]);
1167 VectorSet(boxbrush->brush.edgedirs[0].v, 1, 0, 0);
1168 VectorSet(boxbrush->brush.edgedirs[1].v, 0, 1, 0);
1169 VectorSet(boxbrush->brush.edgedirs[2].v, 0, 0, 1);
1170 VectorSet(boxbrush->brush.planes[0].normal, -1, 0, 0);boxbrush->brush.planes[0].dist = -mins[0];
1171 VectorSet(boxbrush->brush.planes[1].normal, 1, 0, 0);boxbrush->brush.planes[1].dist = maxs[0];
1172 VectorSet(boxbrush->brush.planes[2].normal, 0, -1, 0);boxbrush->brush.planes[2].dist = -mins[1];
1173 VectorSet(boxbrush->brush.planes[3].normal, 0, 1, 0);boxbrush->brush.planes[3].dist = maxs[1];
1174 VectorSet(boxbrush->brush.planes[4].normal, 0, 0, -1);boxbrush->brush.planes[4].dist = -mins[2];
1175 VectorSet(boxbrush->brush.planes[5].normal, 0, 0, 1);boxbrush->brush.planes[5].dist = maxs[2];
1176 for (i = 0;i < 6;i++)
1178 boxbrush->brush.planes[i].q3surfaceflags = q3surfaceflags;
1179 boxbrush->brush.planes[i].texture = texture;
1182 boxbrush->brush.supercontents = supercontents;
1183 boxbrush->brush.q3surfaceflags = q3surfaceflags;
1184 boxbrush->brush.texture = texture;
1185 VectorSet(boxbrush->brush.mins, mins[0] - 1, mins[1] - 1, mins[2] - 1);
1186 VectorSet(boxbrush->brush.maxs, maxs[0] + 1, maxs[1] + 1, maxs[2] + 1);
1187 //Collision_ValidateBrush(&boxbrush->brush);
1190 //pseudocode for detecting line/sphere overlap without calculating an impact point
1191 //linesphereorigin = sphereorigin - linestart;linediff = lineend - linestart;linespherefrac = DotProduct(linesphereorigin, linediff) / DotProduct(linediff, linediff);return VectorLength2(linesphereorigin - bound(0, linespherefrac, 1) * linediff) >= sphereradius*sphereradius;
1193 // LordHavoc: currently unused, but tested
1194 // note: this can be used for tracing a moving sphere vs a stationary sphere,
1195 // by simply adding the moving sphere's radius to the sphereradius parameter,
1196 // all the results are correct (impactpoint, impactnormal, and fraction)
1197 float Collision_ClipTrace_Line_Sphere(double *linestart, double *lineend, double *sphereorigin, double sphereradius, double *impactpoint, double *impactnormal)
1199 double dir[3], scale, v[3], deviationdist2, impactdist, linelength;
1200 // make sure the impactpoint and impactnormal are valid even if there is
1202 VectorCopy(lineend, impactpoint);
1203 VectorClear(impactnormal);
1204 // calculate line direction
1205 VectorSubtract(lineend, linestart, dir);
1206 // normalize direction
1207 linelength = VectorLength(dir);
1210 scale = 1.0 / linelength;
1211 VectorScale(dir, scale, dir);
1213 // this dotproduct calculates the distance along the line at which the
1214 // sphere origin is (nearest point to the sphere origin on the line)
1215 impactdist = DotProduct(sphereorigin, dir) - DotProduct(linestart, dir);
1216 // calculate point on line at that distance, and subtract the
1217 // sphereorigin from it, so we have a vector to measure for the distance
1218 // of the line from the sphereorigin (deviation, how off-center it is)
1219 VectorMA(linestart, impactdist, dir, v);
1220 VectorSubtract(v, sphereorigin, v);
1221 deviationdist2 = sphereradius * sphereradius - VectorLength2(v);
1222 // if squared offset length is outside the squared sphere radius, miss
1223 if (deviationdist2 < 0)
1224 return 1; // miss (off to the side)
1225 // nudge back to find the correct impact distance
1226 impactdist -= sqrt(deviationdist2);
1227 if (impactdist >= linelength)
1228 return 1; // miss (not close enough)
1230 return 1; // miss (linestart is past or inside sphere)
1231 // calculate new impactpoint
1232 VectorMA(linestart, impactdist, dir, impactpoint);
1233 // calculate impactnormal (surface normal at point of impact)
1234 VectorSubtract(impactpoint, sphereorigin, impactnormal);
1235 // normalize impactnormal
1236 VectorNormalize(impactnormal);
1237 // return fraction of movement distance
1238 return impactdist / linelength;
1241 void Collision_TraceLineTriangleFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const float *point0, const float *point1, const float *point2, int supercontents, int q3surfaceflags, const texture_t *texture)
1245 float d1, d2, d, f, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, faceplanenormallength2, edge01[3], edge21[3], edge02[3];
1247 // this function executes:
1248 // 32 ops when line starts behind triangle
1249 // 38 ops when line ends infront of triangle
1250 // 43 ops when line fraction is already closer than this triangle
1251 // 72 ops when line is outside edge 01
1252 // 92 ops when line is outside edge 21
1253 // 115 ops when line is outside edge 02
1254 // 123 ops when line impacts triangle and updates trace results
1256 // this code is designed for clockwise triangles, conversion to
1257 // counterclockwise would require swapping some things around...
1258 // it is easier to simply swap the point0 and point2 parameters to this
1259 // function when calling it than it is to rewire the internals.
1261 // calculate the faceplanenormal of the triangle, this represents the front side
1263 VectorSubtract(point0, point1, edge01);
1264 VectorSubtract(point2, point1, edge21);
1265 CrossProduct(edge01, edge21, faceplanenormal);
1266 // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
1268 faceplanenormallength2 = DotProduct(faceplanenormal, faceplanenormal);
1269 if (faceplanenormallength2 < 0.0001f)
1271 // calculate the distance
1273 faceplanedist = DotProduct(point0, faceplanenormal);
1275 // if start point is on the back side there is no collision
1276 // (we don't care about traces going through the triangle the wrong way)
1278 // calculate the start distance
1280 d1 = DotProduct(faceplanenormal, linestart);
1281 if (d1 <= faceplanedist)
1284 // calculate the end distance
1286 d2 = DotProduct(faceplanenormal, lineend);
1287 // if both are in front, there is no collision
1288 if (d2 >= faceplanedist)
1291 // from here on we know d1 is >= 0 and d2 is < 0
1292 // this means the line starts infront and ends behind, passing through it
1294 // calculate the recipricol of the distance delta,
1295 // so we can use it multiple times cheaply (instead of division)
1297 d = 1.0f / (d1 - d2);
1298 // calculate the impact fraction by taking the start distance (> 0)
1299 // and subtracting the face plane distance (this is the distance of the
1300 // triangle along that same normal)
1301 // then multiply by the recipricol distance delta
1303 f = (d1 - faceplanedist) * d;
1304 // skip out if this impact is further away than previous ones
1306 if (f > trace->realfraction)
1308 // calculate the perfect impact point for classification of insidedness
1310 impact[0] = linestart[0] + f * (lineend[0] - linestart[0]);
1311 impact[1] = linestart[1] + f * (lineend[1] - linestart[1]);
1312 impact[2] = linestart[2] + f * (lineend[2] - linestart[2]);
1314 // calculate the edge normal and reject if impact is outside triangle
1315 // (an edge normal faces away from the triangle, to get the desired normal
1316 // a crossproduct with the faceplanenormal is used, and because of the way
1317 // the insidedness comparison is written it does not need to be normalized)
1319 // first use the two edges from the triangle plane math
1320 // the other edge only gets calculated if the point survives that long
1323 CrossProduct(edge01, faceplanenormal, edgenormal);
1324 if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1328 CrossProduct(faceplanenormal, edge21, edgenormal);
1329 if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1333 VectorSubtract(point0, point2, edge02);
1334 CrossProduct(faceplanenormal, edge02, edgenormal);
1335 if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1340 // store the new trace fraction
1341 trace->realfraction = f;
1343 // calculate a nudged fraction to keep it out of the surface
1344 // (the main fraction remains perfect)
1345 trace->fraction = f - collision_impactnudge.value * d;
1347 if (collision_prefernudgedfraction.integer)
1348 trace->realfraction = trace->fraction;
1350 // store the new trace plane (because collisions only happen from
1351 // the front this is always simply the triangle normal, never flipped)
1352 d = 1.0 / sqrt(faceplanenormallength2);
1353 VectorScale(faceplanenormal, d, trace->plane.normal);
1354 trace->plane.dist = faceplanedist * d;
1356 trace->hitsupercontents = supercontents;
1357 trace->hitq3surfaceflags = q3surfaceflags;
1358 trace->hittexture = texture;
1360 float d1, d2, d, f, fnudged, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, edge[3];
1362 // this code is designed for clockwise triangles, conversion to
1363 // counterclockwise would require swapping some things around...
1364 // it is easier to simply swap the point0 and point2 parameters to this
1365 // function when calling it than it is to rewire the internals.
1367 // calculate the unnormalized faceplanenormal of the triangle,
1368 // this represents the front side
1369 TriangleNormal(point0, point1, point2, faceplanenormal);
1370 // there's no point in processing a degenerate triangle
1371 // (GIGO - Garbage In, Garbage Out)
1372 if (DotProduct(faceplanenormal, faceplanenormal) < 0.0001f)
1374 // calculate the unnormalized distance
1375 faceplanedist = DotProduct(point0, faceplanenormal);
1377 // calculate the unnormalized start distance
1378 d1 = DotProduct(faceplanenormal, linestart) - faceplanedist;
1379 // if start point is on the back side there is no collision
1380 // (we don't care about traces going through the triangle the wrong way)
1384 // calculate the unnormalized end distance
1385 d2 = DotProduct(faceplanenormal, lineend) - faceplanedist;
1386 // if both are in front, there is no collision
1390 // from here on we know d1 is >= 0 and d2 is < 0
1391 // this means the line starts infront and ends behind, passing through it
1393 // calculate the recipricol of the distance delta,
1394 // so we can use it multiple times cheaply (instead of division)
1395 d = 1.0f / (d1 - d2);
1396 // calculate the impact fraction by taking the start distance (> 0)
1397 // and subtracting the face plane distance (this is the distance of the
1398 // triangle along that same normal)
1399 // then multiply by the recipricol distance delta
1401 // skip out if this impact is further away than previous ones
1402 if (f > trace->realfraction)
1404 // calculate the perfect impact point for classification of insidedness
1405 impact[0] = linestart[0] + f * (lineend[0] - linestart[0]);
1406 impact[1] = linestart[1] + f * (lineend[1] - linestart[1]);
1407 impact[2] = linestart[2] + f * (lineend[2] - linestart[2]);
1409 // calculate the edge normal and reject if impact is outside triangle
1410 // (an edge normal faces away from the triangle, to get the desired normal
1411 // a crossproduct with the faceplanenormal is used, and because of the way
1412 // the insidedness comparison is written it does not need to be normalized)
1414 VectorSubtract(point2, point0, edge);
1415 CrossProduct(edge, faceplanenormal, edgenormal);
1416 if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1419 VectorSubtract(point0, point1, edge);
1420 CrossProduct(edge, faceplanenormal, edgenormal);
1421 if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1424 VectorSubtract(point1, point2, edge);
1425 CrossProduct(edge, faceplanenormal, edgenormal);
1426 if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1429 // store the new trace fraction
1430 trace->realfraction = bound(0, f, 1);
1432 // store the new trace plane (because collisions only happen from
1433 // the front this is always simply the triangle normal, never flipped)
1434 VectorNormalize(faceplanenormal);
1435 VectorCopy(faceplanenormal, trace->plane.normal);
1436 trace->plane.dist = DotProduct(point0, faceplanenormal);
1438 // calculate the normalized start and end distances
1439 d1 = DotProduct(trace->plane.normal, linestart) - trace->plane.dist;
1440 d2 = DotProduct(trace->plane.normal, lineend) - trace->plane.dist;
1442 // calculate a nudged fraction to keep it out of the surface
1443 // (the main fraction remains perfect)
1444 fnudged = (d1 - collision_impactnudge.value) / (d1 - d2);
1445 trace->fraction = bound(0, fnudged, 1);
1447 // store the new trace endpos
1448 // not needed, it's calculated later when the trace is finished
1449 //trace->endpos[0] = linestart[0] + fnudged * (lineend[0] - linestart[0]);
1450 //trace->endpos[1] = linestart[1] + fnudged * (lineend[1] - linestart[1]);
1451 //trace->endpos[2] = linestart[2] + fnudged * (lineend[2] - linestart[2]);
1452 trace->hitsupercontents = supercontents;
1453 trace->hitq3surfaceflags = q3surfaceflags;
1454 trace->hittexture = texture;
1458 void Collision_BoundingBoxOfBrushTraceSegment(const colbrushf_t *start, const colbrushf_t *end, vec3_t mins, vec3_t maxs, float startfrac, float endfrac)
1461 colpointf_t *ps, *pe;
1462 float tempstart[3], tempend[3];
1463 VectorLerp(start->points[0].v, startfrac, end->points[0].v, mins);
1464 VectorCopy(mins, maxs);
1465 for (i = 0, ps = start->points, pe = end->points;i < start->numpoints;i++, ps++, pe++)
1467 VectorLerp(ps->v, startfrac, pe->v, tempstart);
1468 VectorLerp(ps->v, endfrac, pe->v, tempend);
1469 mins[0] = min(mins[0], min(tempstart[0], tempend[0]));
1470 mins[1] = min(mins[1], min(tempstart[1], tempend[1]));
1471 mins[2] = min(mins[2], min(tempstart[2], tempend[2]));
1472 maxs[0] = min(maxs[0], min(tempstart[0], tempend[0]));
1473 maxs[1] = min(maxs[1], min(tempstart[1], tempend[1]));
1474 maxs[2] = min(maxs[2], min(tempstart[2], tempend[2]));
1484 //===========================================
1486 static void Collision_TranslateBrush(const vec3_t shift, colbrushf_t *brush)
1489 // now we can transform the data
1490 for(i = 0; i < brush->numplanes; ++i)
1492 brush->planes[i].dist += DotProduct(shift, brush->planes[i].normal);
1494 for(i = 0; i < brush->numpoints; ++i)
1496 VectorAdd(brush->points[i].v, shift, brush->points[i].v);
1498 VectorAdd(brush->mins, shift, brush->mins);
1499 VectorAdd(brush->maxs, shift, brush->maxs);
1502 static void Collision_TransformBrush(const matrix4x4_t *matrix, colbrushf_t *brush)
1506 // we're breaking any AABB properties here...
1507 brush->isaabb = false;
1508 brush->hasaabbplanes = false;
1509 // now we can transform the data
1510 for(i = 0; i < brush->numplanes; ++i)
1512 Matrix4x4_TransformPositivePlane(matrix, brush->planes[i].normal[0], brush->planes[i].normal[1], brush->planes[i].normal[2], brush->planes[i].dist, brush->planes[i].normal);
1514 for(i = 0; i < brush->numedgedirs; ++i)
1516 Matrix4x4_Transform(matrix, brush->edgedirs[i].v, v);
1517 VectorCopy(v, brush->edgedirs[i].v);
1519 for(i = 0; i < brush->numpoints; ++i)
1521 Matrix4x4_Transform(matrix, brush->points[i].v, v);
1522 VectorCopy(v, brush->points[i].v);
1524 VectorCopy(brush->points[0].v, brush->mins);
1525 VectorCopy(brush->points[0].v, brush->maxs);
1526 for(i = 1; i < brush->numpoints; ++i)
1528 if(brush->points[i].v[0] < brush->mins[0]) brush->mins[0] = brush->points[i].v[0];
1529 if(brush->points[i].v[1] < brush->mins[1]) brush->mins[1] = brush->points[i].v[1];
1530 if(brush->points[i].v[2] < brush->mins[2]) brush->mins[2] = brush->points[i].v[2];
1531 if(brush->points[i].v[0] > brush->maxs[0]) brush->maxs[0] = brush->points[i].v[0];
1532 if(brush->points[i].v[1] > brush->maxs[1]) brush->maxs[1] = brush->points[i].v[1];
1533 if(brush->points[i].v[2] > brush->maxs[2]) brush->maxs[2] = brush->points[i].v[2];
1537 typedef struct collision_cachedtrace_parameters_s
1542 int hitsupercontentsmask;
1545 collision_cachedtrace_parameters_t;
1547 typedef struct collision_cachedtrace_s
1550 collision_cachedtrace_parameters_t p;
1553 collision_cachedtrace_t;
1555 static mempool_t *collision_cachedtrace_mempool;
1556 static collision_cachedtrace_t *collision_cachedtrace_array;
1557 static int collision_cachedtrace_firstfree;
1558 static int collision_cachedtrace_lastused;
1559 static int collision_cachedtrace_max;
1560 static int collision_cachedtrace_sequence;
1561 static int collision_cachedtrace_hashsize;
1562 static int *collision_cachedtrace_hash;
1563 static unsigned int *collision_cachedtrace_arrayfullhashindex;
1564 static unsigned int *collision_cachedtrace_arrayhashindex;
1565 static unsigned int *collision_cachedtrace_arraynext;
1566 static unsigned char *collision_cachedtrace_arrayused;
1567 static qboolean collision_cachedtrace_rebuildhash;
1569 void Collision_Cache_Reset(qboolean resetlimits)
1571 if (collision_cachedtrace_hash)
1572 Mem_Free(collision_cachedtrace_hash);
1573 if (collision_cachedtrace_array)
1574 Mem_Free(collision_cachedtrace_array);
1575 if (collision_cachedtrace_arrayfullhashindex)
1576 Mem_Free(collision_cachedtrace_arrayfullhashindex);
1577 if (collision_cachedtrace_arrayhashindex)
1578 Mem_Free(collision_cachedtrace_arrayhashindex);
1579 if (collision_cachedtrace_arraynext)
1580 Mem_Free(collision_cachedtrace_arraynext);
1581 if (collision_cachedtrace_arrayused)
1582 Mem_Free(collision_cachedtrace_arrayused);
1583 if (resetlimits || !collision_cachedtrace_max)
1584 collision_cachedtrace_max = collision_cache.integer ? 128 : 1;
1585 collision_cachedtrace_firstfree = 1;
1586 collision_cachedtrace_lastused = 0;
1587 collision_cachedtrace_hashsize = collision_cachedtrace_max;
1588 collision_cachedtrace_array = (collision_cachedtrace_t *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(collision_cachedtrace_t));
1589 collision_cachedtrace_hash = (int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_hashsize * sizeof(int));
1590 collision_cachedtrace_arrayfullhashindex = (unsigned int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned int));
1591 collision_cachedtrace_arrayhashindex = (unsigned int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned int));
1592 collision_cachedtrace_arraynext = (unsigned int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned int));
1593 collision_cachedtrace_arrayused = (unsigned char *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned char));
1594 collision_cachedtrace_sequence = 1;
1595 collision_cachedtrace_rebuildhash = false;
1598 void Collision_Cache_Init(mempool_t *mempool)
1600 collision_cachedtrace_mempool = mempool;
1601 Collision_Cache_Reset(true);
1604 static void Collision_Cache_RebuildHash(void)
1607 int range = collision_cachedtrace_lastused + 1;
1608 int sequence = collision_cachedtrace_sequence;
1609 int firstfree = collision_cachedtrace_max;
1611 int *hash = collision_cachedtrace_hash;
1612 unsigned int hashindex;
1613 unsigned int *arrayhashindex = collision_cachedtrace_arrayhashindex;
1614 unsigned int *arraynext = collision_cachedtrace_arraynext;
1615 collision_cachedtrace_rebuildhash = false;
1616 memset(collision_cachedtrace_hash, 0, collision_cachedtrace_hashsize * sizeof(int));
1617 for (index = 1;index < range;index++)
1619 if (collision_cachedtrace_arrayused[index] == sequence)
1621 hashindex = arrayhashindex[index];
1622 arraynext[index] = hash[hashindex];
1623 hash[hashindex] = index;
1628 if (firstfree > index)
1630 collision_cachedtrace_arrayused[index] = 0;
1633 collision_cachedtrace_firstfree = firstfree;
1634 collision_cachedtrace_lastused = lastused;
1637 void Collision_Cache_NewFrame(void)
1639 if (collision_cache.integer)
1641 if (collision_cachedtrace_max < 128)
1642 Collision_Cache_Reset(true);
1646 if (collision_cachedtrace_max > 1)
1647 Collision_Cache_Reset(true);
1649 // rebuild hash if sequence would overflow byte, otherwise increment
1650 if (collision_cachedtrace_sequence == 255)
1652 Collision_Cache_RebuildHash();
1653 collision_cachedtrace_sequence = 1;
1657 collision_cachedtrace_rebuildhash = true;
1658 collision_cachedtrace_sequence++;
1662 static unsigned int Collision_Cache_HashIndexForArray(unsigned int *array, unsigned int size)
1665 unsigned int hashindex = 0;
1666 // this is a super-cheesy checksum, designed only for speed
1667 for (i = 0;i < size;i++)
1668 hashindex += array[i] * (1 + i);
1672 static collision_cachedtrace_t *Collision_Cache_Lookup(dp_model_t *model, const matrix4x4_t *matrix, const matrix4x4_t *inversematrix, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
1675 unsigned int fullhashindex;
1678 int sequence = collision_cachedtrace_sequence;
1679 int *hash = collision_cachedtrace_hash;
1680 unsigned int *arrayfullhashindex = collision_cachedtrace_arrayfullhashindex;
1681 unsigned int *arraynext = collision_cachedtrace_arraynext;
1682 collision_cachedtrace_t *cached = collision_cachedtrace_array + index;
1683 collision_cachedtrace_parameters_t params;
1684 // all non-cached traces use the same index
1685 if (!collision_cache.integer)
1686 r_refdef.stats.collisioncache_traced++;
1689 // cached trace lookup
1690 memset(¶ms, 0, sizeof(params));
1691 params.model = model;
1692 VectorCopy(start, params.start);
1693 VectorCopy(end, params.end);
1694 params.hitsupercontentsmask = hitsupercontentsmask;
1695 params.matrix = *matrix;
1696 fullhashindex = Collision_Cache_HashIndexForArray((unsigned int *)¶ms, sizeof(params) / sizeof(unsigned int));
1697 hashindex = (int)(fullhashindex % (unsigned int)collision_cachedtrace_hashsize);
1698 for (index = hash[hashindex];index;index = arraynext[index])
1700 if (arrayfullhashindex[index] != fullhashindex)
1702 cached = collision_cachedtrace_array + index;
1703 //if (memcmp(&cached->p, ¶ms, sizeof(params)))
1704 if (cached->p.model != params.model
1705 || cached->p.end[0] != params.end[0]
1706 || cached->p.end[1] != params.end[1]
1707 || cached->p.end[2] != params.end[2]
1708 || cached->p.start[0] != params.start[0]
1709 || cached->p.start[1] != params.start[1]
1710 || cached->p.start[2] != params.start[2]
1711 || cached->p.hitsupercontentsmask != params.hitsupercontentsmask
1712 || cached->p.matrix.m[0][0] != params.matrix.m[0][0]
1713 || cached->p.matrix.m[0][1] != params.matrix.m[0][1]
1714 || cached->p.matrix.m[0][2] != params.matrix.m[0][2]
1715 || cached->p.matrix.m[0][3] != params.matrix.m[0][3]
1716 || cached->p.matrix.m[1][0] != params.matrix.m[1][0]
1717 || cached->p.matrix.m[1][1] != params.matrix.m[1][1]
1718 || cached->p.matrix.m[1][2] != params.matrix.m[1][2]
1719 || cached->p.matrix.m[1][3] != params.matrix.m[1][3]
1720 || cached->p.matrix.m[2][0] != params.matrix.m[2][0]
1721 || cached->p.matrix.m[2][1] != params.matrix.m[2][1]
1722 || cached->p.matrix.m[2][2] != params.matrix.m[2][2]
1723 || cached->p.matrix.m[2][3] != params.matrix.m[2][3]
1724 || cached->p.matrix.m[3][0] != params.matrix.m[3][0]
1725 || cached->p.matrix.m[3][1] != params.matrix.m[3][1]
1726 || cached->p.matrix.m[3][2] != params.matrix.m[3][2]
1727 || cached->p.matrix.m[3][3] != params.matrix.m[3][3]
1730 // found a matching trace in the cache
1731 r_refdef.stats.collisioncache_cached++;
1732 cached->valid = true;
1733 collision_cachedtrace_arrayused[index] = collision_cachedtrace_sequence;
1736 r_refdef.stats.collisioncache_traced++;
1737 // find an unused cache entry
1738 for (index = collision_cachedtrace_firstfree, range = collision_cachedtrace_max;index < range;index++)
1739 if (collision_cachedtrace_arrayused[index] == 0)
1743 // all claimed, but probably some are stale...
1744 for (index = 1, range = collision_cachedtrace_max;index < range;index++)
1745 if (collision_cachedtrace_arrayused[index] != sequence)
1749 // found a stale one, rebuild the hash
1750 Collision_Cache_RebuildHash();
1754 // we need to grow the cache
1755 collision_cachedtrace_max *= 2;
1756 Collision_Cache_Reset(false);
1760 // link the new cache entry into the hash bucket
1761 collision_cachedtrace_firstfree = index + 1;
1762 if (collision_cachedtrace_lastused < index)
1763 collision_cachedtrace_lastused = index;
1764 cached = collision_cachedtrace_array + index;
1765 collision_cachedtrace_arraynext[index] = collision_cachedtrace_hash[hashindex];
1766 collision_cachedtrace_hash[hashindex] = index;
1767 collision_cachedtrace_arrayhashindex[index] = hashindex;
1768 cached->valid = false;
1770 collision_cachedtrace_arrayfullhashindex[index] = fullhashindex;
1771 collision_cachedtrace_arrayused[index] = collision_cachedtrace_sequence;
1776 void Collision_Cache_ClipLineToGenericEntitySurfaces(trace_t *trace, dp_model_t *model, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
1778 collision_cachedtrace_t *cached = Collision_Cache_Lookup(model, matrix, inversematrix, start, end, hitsupercontentsmask);
1781 *trace = cached->result;
1785 Collision_ClipLineToGenericEntity(trace, model, NULL, NULL, vec3_origin, vec3_origin, 0, matrix, inversematrix, start, end, hitsupercontentsmask, true);
1787 cached->result = *trace;
1790 void Collision_Cache_ClipLineToWorldSurfaces(trace_t *trace, dp_model_t *model, const vec3_t start, const vec3_t end, int hitsupercontents)
1792 collision_cachedtrace_t *cached = Collision_Cache_Lookup(model, &identitymatrix, &identitymatrix, start, end, hitsupercontents);
1795 *trace = cached->result;
1799 Collision_ClipLineToWorld(trace, model, start, end, hitsupercontents, true);
1801 cached->result = *trace;
1804 void Collision_ClipToGenericEntity(trace_t *trace, dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, const vec3_t bodymins, const vec3_t bodymaxs, int bodysupercontents, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontentsmask)
1806 float starttransformed[3], endtransformed[3];
1808 memset(trace, 0, sizeof(*trace));
1809 trace->fraction = trace->realfraction = 1;
1811 Matrix4x4_Transform(inversematrix, start, starttransformed);
1812 Matrix4x4_Transform(inversematrix, end, endtransformed);
1813 #if COLLISIONPARANOID >= 3
1814 Con_Printf("trans(%f %f %f -> %f %f %f, %f %f %f -> %f %f %f)", start[0], start[1], start[2], starttransformed[0], starttransformed[1], starttransformed[2], end[0], end[1], end[2], endtransformed[0], endtransformed[1], endtransformed[2]);
1817 if (model && model->TraceBox)
1819 if(model->TraceBrush && (inversematrix->m[0][1] || inversematrix->m[0][2] || inversematrix->m[1][0] || inversematrix->m[1][2] || inversematrix->m[2][0] || inversematrix->m[2][1]))
1821 // we get here if TraceBrush exists, AND we have a rotation component (SOLID_BSP case)
1822 // using starttransformed, endtransformed is WRONG in this case!
1823 // should rather build a brush and trace using it
1824 colboxbrushf_t thisbrush_start, thisbrush_end;
1825 Collision_BrushForBox(&thisbrush_start, mins, maxs, 0, 0, NULL);
1826 Collision_BrushForBox(&thisbrush_end, mins, maxs, 0, 0, NULL);
1827 Collision_TranslateBrush(start, &thisbrush_start.brush);
1828 Collision_TranslateBrush(end, &thisbrush_end.brush);
1829 Collision_TransformBrush(inversematrix, &thisbrush_start.brush);
1830 Collision_TransformBrush(inversematrix, &thisbrush_end.brush);
1831 //Collision_TranslateBrush(starttransformed, &thisbrush_start.brush);
1832 //Collision_TranslateBrush(endtransformed, &thisbrush_end.brush);
1833 model->TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
1835 else // this is only approximate if rotated, quite useless
1836 model->TraceBox(model, frameblend, skeleton, trace, starttransformed, mins, maxs, endtransformed, hitsupercontentsmask);
1838 else // and this requires that the transformation matrix doesn't have angles components, like SV_TraceBox ensures; FIXME may get called if a model is SOLID_BSP but has no TraceBox function
1839 Collision_ClipTrace_Box(trace, bodymins, bodymaxs, starttransformed, mins, maxs, endtransformed, hitsupercontentsmask, bodysupercontents, 0, NULL);
1840 trace->fraction = bound(0, trace->fraction, 1);
1841 trace->realfraction = bound(0, trace->realfraction, 1);
1843 VectorLerp(start, trace->fraction, end, trace->endpos);
1845 // NOTE: this relies on plane.dist being directly after plane.normal
1846 Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal);
1849 void Collision_ClipToWorld(trace_t *trace, dp_model_t *model, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontents)
1851 memset(trace, 0, sizeof(*trace));
1852 trace->fraction = trace->realfraction = 1;
1853 // ->TraceBox: TraceBrush not needed here, as worldmodel is never rotated
1854 if (model && model->TraceBox)
1855 model->TraceBox(model, NULL, NULL, trace, start, mins, maxs, end, hitsupercontents);
1856 trace->fraction = bound(0, trace->fraction, 1);
1857 trace->realfraction = bound(0, trace->realfraction, 1);
1858 VectorLerp(start, trace->fraction, end, trace->endpos);
1861 void Collision_ClipLineToGenericEntity(trace_t *trace, dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, const vec3_t bodymins, const vec3_t bodymaxs, int bodysupercontents, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t start, const vec3_t end, int hitsupercontentsmask, qboolean hitsurfaces)
1863 float starttransformed[3], endtransformed[3];
1864 memset(trace, 0, sizeof(*trace));
1865 trace->fraction = trace->realfraction = 1;
1867 Matrix4x4_Transform(inversematrix, start, starttransformed);
1868 Matrix4x4_Transform(inversematrix, end, endtransformed);
1869 #if COLLISIONPARANOID >= 3
1870 Con_Printf("trans(%f %f %f -> %f %f %f, %f %f %f -> %f %f %f)", start[0], start[1], start[2], starttransformed[0], starttransformed[1], starttransformed[2], end[0], end[1], end[2], endtransformed[0], endtransformed[1], endtransformed[2]);
1873 if (model && model->TraceLineAgainstSurfaces && hitsurfaces)
1874 model->TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, starttransformed, endtransformed, hitsupercontentsmask);
1875 else if (model && model->TraceLine)
1876 model->TraceLine(model, frameblend, skeleton, trace, starttransformed, endtransformed, hitsupercontentsmask);
1878 Collision_ClipTrace_Box(trace, bodymins, bodymaxs, starttransformed, vec3_origin, vec3_origin, endtransformed, hitsupercontentsmask, bodysupercontents, 0, NULL);
1879 trace->fraction = bound(0, trace->fraction, 1);
1880 trace->realfraction = bound(0, trace->realfraction, 1);
1882 VectorLerp(start, trace->fraction, end, trace->endpos);
1884 // NOTE: this relies on plane.dist being directly after plane.normal
1885 Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal);
1888 void Collision_ClipLineToWorld(trace_t *trace, dp_model_t *model, const vec3_t start, const vec3_t end, int hitsupercontents, qboolean hitsurfaces)
1890 memset(trace, 0, sizeof(*trace));
1891 trace->fraction = trace->realfraction = 1;
1892 if (model && model->TraceLineAgainstSurfaces && hitsurfaces)
1893 model->TraceLineAgainstSurfaces(model, NULL, NULL, trace, start, end, hitsupercontents);
1894 else if (model && model->TraceLine)
1895 model->TraceLine(model, NULL, NULL, trace, start, end, hitsupercontents);
1896 trace->fraction = bound(0, trace->fraction, 1);
1897 trace->realfraction = bound(0, trace->realfraction, 1);
1898 VectorLerp(start, trace->fraction, end, trace->endpos);
1901 void Collision_ClipPointToGenericEntity(trace_t *trace, dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, const vec3_t bodymins, const vec3_t bodymaxs, int bodysupercontents, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t start, int hitsupercontentsmask)
1903 float starttransformed[3];
1904 memset(trace, 0, sizeof(*trace));
1905 trace->fraction = trace->realfraction = 1;
1907 Matrix4x4_Transform(inversematrix, start, starttransformed);
1908 #if COLLISIONPARANOID >= 3
1909 Con_Printf("trans(%f %f %f -> %f %f %f)", start[0], start[1], start[2], starttransformed[0], starttransformed[1], starttransformed[2]);
1912 if (model && model->TracePoint)
1913 model->TracePoint(model, NULL, NULL, trace, starttransformed, hitsupercontentsmask);
1915 Collision_ClipTrace_Point(trace, bodymins, bodymaxs, starttransformed, hitsupercontentsmask, bodysupercontents, 0, NULL);
1917 VectorCopy(start, trace->endpos);
1919 // NOTE: this relies on plane.dist being directly after plane.normal
1920 Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal);
1923 void Collision_ClipPointToWorld(trace_t *trace, dp_model_t *model, const vec3_t start, int hitsupercontents)
1925 memset(trace, 0, sizeof(*trace));
1926 trace->fraction = trace->realfraction = 1;
1927 if (model && model->TracePoint)
1928 model->TracePoint(model, NULL, NULL, trace, start, hitsupercontents);
1929 VectorCopy(start, trace->endpos);
1932 void Collision_CombineTraces(trace_t *cliptrace, const trace_t *trace, void *touch, qboolean isbmodel)
1934 // take the 'best' answers from the new trace and combine with existing data
1935 if (trace->allsolid)
1936 cliptrace->allsolid = true;
1937 if (trace->startsolid)
1940 cliptrace->bmodelstartsolid = true;
1941 cliptrace->startsolid = true;
1942 if (cliptrace->realfraction == 1)
1943 cliptrace->ent = touch;
1944 if (cliptrace->startdepth > trace->startdepth)
1946 cliptrace->startdepth = trace->startdepth;
1947 VectorCopy(trace->startdepthnormal, cliptrace->startdepthnormal);
1950 // don't set this except on the world, because it can easily confuse
1951 // monsters underwater if there's a bmodel involved in the trace
1952 // (inopen && inwater is how they check water visibility)
1953 //if (trace->inopen)
1954 // cliptrace->inopen = true;
1956 cliptrace->inwater = true;
1957 if ((trace->realfraction < cliptrace->realfraction) && (VectorLength2(trace->plane.normal) > 0))
1959 cliptrace->fraction = trace->fraction;
1960 cliptrace->realfraction = trace->realfraction;
1961 VectorCopy(trace->endpos, cliptrace->endpos);
1962 cliptrace->plane = trace->plane;
1963 cliptrace->ent = touch;
1964 cliptrace->hitsupercontents = trace->hitsupercontents;
1965 cliptrace->hitq3surfaceflags = trace->hitq3surfaceflags;
1966 cliptrace->hittexture = trace->hittexture;
1968 cliptrace->startsupercontents |= trace->startsupercontents;
1971 void Collision_ShortenTrace(trace_t *trace, float shorten_factor, const vec3_t end)
1973 // now undo our moving end 1 qu farther...
1974 trace->fraction = bound(trace->fraction, trace->fraction / shorten_factor - 1e-6, 1); // we subtract 1e-6 to guard for roundoff errors
1975 trace->realfraction = bound(trace->realfraction, trace->realfraction / shorten_factor - 1e-6, 1); // we subtract 1e-6 to guard for roundoff errors
1976 if(trace->fraction >= 1) // trace would NOT hit if not expanded!
1978 trace->fraction = 1;
1979 trace->realfraction = 1;
1980 VectorCopy(end, trace->endpos);
1981 memset(&trace->plane, 0, sizeof(trace->plane));
1983 trace->hitsupercontentsmask = 0;
1984 trace->hitsupercontents = 0;
1985 trace->hitq3surfaceflags = 0;
1986 trace->hittexture = NULL;