]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - collision.c
Add skipmaterialflagsmask feature to TraceLine and friends - this allows more sensibl...
[xonotic/darkplaces.git] / collision.c
1
2 #include "quakedef.h"
3 #include "polygon.h"
4 #include "collision.h"
5
6 #define COLLISION_EDGEDIR_DOT_EPSILON (0.999f)
7 #define COLLISION_EDGECROSS_MINLENGTH2 (1.0f / 4194304.0f)
8 #define COLLISION_SNAPSCALE (32.0f)
9 #define COLLISION_SNAP (1.0f / COLLISION_SNAPSCALE)
10 #define COLLISION_SNAP2 (2.0f / COLLISION_SNAPSCALE)
11 #define COLLISION_PLANE_DIST_EPSILON (2.0f / COLLISION_SNAPSCALE)
12
13 cvar_t collision_impactnudge = {0, "collision_impactnudge", "0.03125", "how much to back off from the impact"};
14 cvar_t collision_extendmovelength = {0, "collision_extendmovelength", "16", "internal bias on trace length to ensure detection of collisions within the collision_impactnudge distance so that short moves do not degrade across frames (this does not alter the final trace length)"};
15 cvar_t collision_extendtraceboxlength = {0, "collision_extendtraceboxlength", "1", "internal bias for tracebox() qc builtin to account for collision_impactnudge (this does not alter the final trace length)"};
16 cvar_t collision_extendtracelinelength = {0, "collision_extendtracelinelength", "1", "internal bias for traceline() qc builtin to account for collision_impactnudge (this does not alter the final trace length)"};
17 cvar_t collision_debug_tracelineasbox = {0, "collision_debug_tracelineasbox", "0", "workaround for any bugs in Collision_TraceLineBrushFloat by using Collision_TraceBrushBrushFloat"};
18 cvar_t collision_cache = {0, "collision_cache", "1", "store results of collision traces for next frame to reuse if possible (optimization)"};
19 //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)"};
20 cvar_t collision_triangle_bevelsides = {0, "collision_triangle_bevelsides", "0", "generate sloped edge planes on triangles - if 0, see axialedgeplanes"};
21 cvar_t collision_triangle_axialsides = {0, "collision_triangle_axialsides", "1", "generate axially-aligned edge planes on triangles - otherwise use perpendicular edge planes"};
22 cvar_t collision_bih_fullrecursion = { 0, "collision_bih_fullrecursion", "0", "debugging option to disable the bih recursion optimizations by iterating the entire tree" };
23
24 mempool_t *collision_mempool;
25
26 void Collision_Init (void)
27 {
28         Cvar_RegisterVariable(&collision_impactnudge);
29         Cvar_RegisterVariable(&collision_extendmovelength);
30         Cvar_RegisterVariable(&collision_extendtracelinelength);
31         Cvar_RegisterVariable(&collision_extendtraceboxlength);
32         Cvar_RegisterVariable(&collision_debug_tracelineasbox);
33         Cvar_RegisterVariable(&collision_cache);
34 //      Cvar_RegisterVariable(&collision_triangle_neighborsides);
35         Cvar_RegisterVariable(&collision_triangle_bevelsides);
36         Cvar_RegisterVariable(&collision_triangle_axialsides);
37         Cvar_RegisterVariable(&collision_bih_fullrecursion);
38         collision_mempool = Mem_AllocPool("collision cache", 0, NULL);
39         Collision_Cache_Init(collision_mempool);
40 }
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 static void Collision_PrintBrushAsQHull(colbrushf_t *brush, const char *name)
56 {
57         int i;
58         Con_Printf("3 %s\n%i\n", name, brush->numpoints);
59         for (i = 0;i < brush->numpoints;i++)
60                 Con_Printf("%f %f %f\n", brush->points[i].v[0], brush->points[i].v[1], brush->points[i].v[2]);
61         // FIXME: optimize!
62         Con_Printf("4\n%i\n", brush->numplanes);
63         for (i = 0;i < brush->numplanes;i++)
64                 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);
65 }
66
67 static void Collision_ValidateBrush(colbrushf_t *brush)
68 {
69         int j, k, pointsoffplanes, pointonplanes, pointswithinsufficientplanes, printbrush;
70         float d;
71         printbrush = false;
72         if (!brush->numpoints)
73         {
74                 Con_Print("Collision_ValidateBrush: brush with no points!\n");
75                 printbrush = true;
76         }
77 #if 0
78         // it's ok for a brush to have one point and no planes...
79         if (brush->numplanes == 0 && brush->numpoints != 1)
80         {
81                 Con_Print("Collision_ValidateBrush: brush with no planes and more than one point!\n");
82                 printbrush = true;
83         }
84 #endif
85         if (brush->numplanes)
86         {
87                 pointsoffplanes = 0;
88                 pointswithinsufficientplanes = 0;
89                 for (k = 0;k < brush->numplanes;k++)
90                         if (DotProduct(brush->planes[k].normal, brush->planes[k].normal) < 0.0001f)
91                                 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);
92                 for (j = 0;j < brush->numpoints;j++)
93                 {
94                         pointonplanes = 0;
95                         for (k = 0;k < brush->numplanes;k++)
96                         {
97                                 d = DotProduct(brush->points[j].v, brush->planes[k].normal) - brush->planes[k].dist;
98                                 if (d > COLLISION_PLANE_DIST_EPSILON)
99                                 {
100                                         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);
101                                         printbrush = true;
102                                 }
103                                 if (fabs(d) > COLLISION_PLANE_DIST_EPSILON)
104                                         pointsoffplanes++;
105                                 else
106                                         pointonplanes++;
107                         }
108                         if (pointonplanes < 3)
109                                 pointswithinsufficientplanes++;
110                 }
111                 if (pointswithinsufficientplanes)
112                 {
113                         Con_Print("Collision_ValidateBrush: some points have insufficient planes, every point must be on at least 3 planes to form a corner.\n");
114                         printbrush = true;
115                 }
116                 if (pointsoffplanes == 0) // all points are on all planes
117                 {
118                         Con_Print("Collision_ValidateBrush: all points lie on all planes (degenerate, no brush volume!)\n");
119                         printbrush = true;
120                 }
121         }
122         if (printbrush)
123                 Collision_PrintBrushAsQHull(brush, "unnamed");
124 }
125
126 static float nearestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
127 {
128         float dist, bestdist;
129         if (!numpoints)
130                 return 0;
131         bestdist = DotProduct(points->v, normal);
132         points++;
133         while(--numpoints)
134         {
135                 dist = DotProduct(points->v, normal);
136                 bestdist = min(bestdist, dist);
137                 points++;
138         }
139         return bestdist;
140 }
141
142 static float furthestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
143 {
144         float dist, bestdist;
145         if (!numpoints)
146                 return 0;
147         bestdist = DotProduct(points->v, normal);
148         points++;
149         while(--numpoints)
150         {
151                 dist = DotProduct(points->v, normal);
152                 bestdist = max(bestdist, dist);
153                 points++;
154         }
155         return bestdist;
156 }
157
158 static void Collision_CalcEdgeDirsForPolygonBrushFloat(colbrushf_t *brush)
159 {
160         int i, j;
161         for (i = 0, j = brush->numpoints - 1;i < brush->numpoints;j = i, i++)
162                 VectorSubtract(brush->points[i].v, brush->points[j].v, brush->edgedirs[j].v);
163 }
164
165 colbrushf_t *Collision_NewBrushFromPlanes(mempool_t *mempool, int numoriginalplanes, const colplanef_t *originalplanes, int supercontents, int q3surfaceflags, const texture_t *texture, int hasaabbplanes)
166 {
167         // TODO: planesbuf could be replaced by a remapping table
168         int j, k, w, xyzflags;
169         int numpointsbuf = 0, maxpointsbuf = 256, numedgedirsbuf = 0, maxedgedirsbuf = 256, numplanesbuf = 0, maxplanesbuf = 256, numelementsbuf = 0, maxelementsbuf = 256;
170         int isaabb = true;
171         double maxdist;
172         colbrushf_t *brush;
173         colpointf_t pointsbuf[256];
174         colpointf_t edgedirsbuf[256];
175         colplanef_t planesbuf[256];
176         int elementsbuf[1024];
177         int polypointbuf[256];
178         int pmaxpoints = 64;
179         int pnumpoints;
180         double p[2][3*64];
181 #if 0
182         // enable these if debugging to avoid seeing garbage in unused data-
183         memset(pointsbuf, 0, sizeof(pointsbuf));
184         memset(edgedirsbuf, 0, sizeof(edgedirsbuf));
185         memset(planesbuf, 0, sizeof(planesbuf));
186         memset(elementsbuf, 0, sizeof(elementsbuf));
187         memset(polypointbuf, 0, sizeof(polypointbuf));
188         memset(p, 0, sizeof(p));
189 #endif
190
191         // check if there are too many planes and skip the brush
192         if (numoriginalplanes >= maxplanesbuf)
193         {
194                 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many planes for buffer\n");
195                 return NULL;
196         }
197
198         // figure out how large a bounding box we need to properly compute this brush
199         maxdist = 0;
200         for (j = 0;j < numoriginalplanes;j++)
201                 maxdist = max(maxdist, fabs(originalplanes[j].dist));
202         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
203         maxdist = floor(maxdist * (4.0 / 1024.0) + 2) * 1024.0;
204         // construct a collision brush (points, planes, and renderable mesh) from
205         // a set of planes, this also optimizes out any unnecessary planes (ones
206         // whose polygon is clipped away by the other planes)
207         for (j = 0;j < numoriginalplanes;j++)
208         {
209                 int n;
210                 // add the new plane
211                 VectorCopy(originalplanes[j].normal, planesbuf[numplanesbuf].normal);
212                 planesbuf[numplanesbuf].dist = originalplanes[j].dist;
213                 planesbuf[numplanesbuf].q3surfaceflags = originalplanes[j].q3surfaceflags;
214                 planesbuf[numplanesbuf].texture = originalplanes[j].texture;
215                 numplanesbuf++;
216
217                 // create a large polygon from the plane
218                 w = 0;
219                 PolygonD_QuadForPlane(p[w], originalplanes[j].normal[0], originalplanes[j].normal[1], originalplanes[j].normal[2], originalplanes[j].dist, maxdist);
220                 pnumpoints = 4;
221                 // clip it by all other planes
222                 for (k = 0;k < numoriginalplanes && pnumpoints >= 3 && pnumpoints <= pmaxpoints;k++)
223                 {
224                         // skip the plane this polygon
225                         // (nothing happens if it is processed, this is just an optimization)
226                         if (k != j)
227                         {
228                                 // we want to keep the inside of the brush plane so we flip
229                                 // the cutting plane
230                                 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);
231                                 w = !w;
232                         }
233                 }
234
235                 // if nothing is left, skip it
236                 if (pnumpoints < 3)
237                 {
238                         //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);
239                         continue;
240                 }
241
242                 for (k = 0;k < pnumpoints;k++)
243                 {
244                         int l, m;
245                         m = 0;
246                         for (l = 0;l < numoriginalplanes;l++)
247                                 if (fabs(DotProduct(&p[w][k*3], originalplanes[l].normal) - originalplanes[l].dist) < COLLISION_PLANE_DIST_EPSILON)
248                                         m++;
249                         if (m < 3)
250                                 break;
251                 }
252                 if (k < pnumpoints)
253                 {
254                         Con_DPrintf("Collision_NewBrushFromPlanes: warning: polygon point does not lie on at least 3 planes\n");
255                         //return NULL;
256                 }
257
258                 // check if there are too many polygon vertices for buffer
259                 if (pnumpoints > pmaxpoints)
260                 {
261                         Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
262                         return NULL;
263                 }
264
265                 // check if there are too many triangle elements for buffer
266                 if (numelementsbuf + (pnumpoints - 2) * 3 > maxelementsbuf)
267                 {
268                         Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many triangle elements for buffer\n");
269                         return NULL;
270                 }
271
272                 // add the unique points for this polygon
273                 for (k = 0;k < pnumpoints;k++)
274                 {
275                         int m;
276                         float v[3];
277                         // downgrade to float precision before comparing
278                         VectorCopy(&p[w][k*3], v);
279
280                         // check if there is already a matching point (no duplicates)
281                         for (m = 0;m < numpointsbuf;m++)
282                                 if (VectorDistance2(v, pointsbuf[m].v) < COLLISION_SNAP2)
283                                         break;
284
285                         // if there is no match, add a new one
286                         if (m == numpointsbuf)
287                         {
288                                 // check if there are too many and skip the brush
289                                 if (numpointsbuf >= maxpointsbuf)
290                                 {
291                                         Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
292                                         return NULL;
293                                 }
294                                 // add the new one
295                                 VectorCopy(&p[w][k*3], pointsbuf[numpointsbuf].v);
296                                 numpointsbuf++;
297                         }
298
299                         // store the index into a buffer
300                         polypointbuf[k] = m;
301                 }
302
303                 // add the triangles for the polygon
304                 // (this particular code makes a triangle fan)
305                 for (k = 0;k < pnumpoints - 2;k++)
306                 {
307                         elementsbuf[numelementsbuf++] = polypointbuf[0];
308                         elementsbuf[numelementsbuf++] = polypointbuf[k + 1];
309                         elementsbuf[numelementsbuf++] = polypointbuf[k + 2];
310                 }
311
312                 // add the unique edgedirs for this polygon
313                 for (k = 0, n = pnumpoints-1;k < pnumpoints;n = k, k++)
314                 {
315                         int m;
316                         float dir[3];
317                         // downgrade to float precision before comparing
318                         VectorSubtract(&p[w][k*3], &p[w][n*3], dir);
319                         VectorNormalize(dir);
320
321                         // check if there is already a matching edgedir (no duplicates)
322                         for (m = 0;m < numedgedirsbuf;m++)
323                                 if (DotProduct(dir, edgedirsbuf[m].v) >= COLLISION_EDGEDIR_DOT_EPSILON)
324                                         break;
325                         // skip this if there is
326                         if (m < numedgedirsbuf)
327                                 continue;
328
329                         // try again with negated edgedir
330                         VectorNegate(dir, dir);
331                         // check if there is already a matching edgedir (no duplicates)
332                         for (m = 0;m < numedgedirsbuf;m++)
333                                 if (DotProduct(dir, edgedirsbuf[m].v) >= COLLISION_EDGEDIR_DOT_EPSILON)
334                                         break;
335                         // if there is no match, add a new one
336                         if (m == numedgedirsbuf)
337                         {
338                                 // check if there are too many and skip the brush
339                                 if (numedgedirsbuf >= maxedgedirsbuf)
340                                 {
341                                         Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many edgedirs for buffer\n");
342                                         return NULL;
343                                 }
344                                 // add the new one
345                                 VectorCopy(dir, edgedirsbuf[numedgedirsbuf].v);
346                                 numedgedirsbuf++;
347                         }
348                 }
349
350                 // if any normal is not purely axial, it's not an axis-aligned box
351                 if (isaabb && (originalplanes[j].normal[0] == 0) + (originalplanes[j].normal[1] == 0) + (originalplanes[j].normal[2] == 0) < 2)
352                         isaabb = false;
353         }
354
355         // if nothing is left, there's nothing to allocate
356         if (numplanesbuf < 4)
357         {
358                 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);
359                 return NULL;
360         }
361
362         // if no triangles or points could be constructed, then this routine failed but the brush is not discarded
363         if (numelementsbuf < 12 || numpointsbuf < 4)
364                 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);
365
366         // validate plane distances
367         for (j = 0;j < numplanesbuf;j++)
368         {
369                 float d = furthestplanedist_float(planesbuf[j].normal, pointsbuf, numpointsbuf);
370                 if (fabs(planesbuf[j].dist - d) > COLLISION_PLANE_DIST_EPSILON)
371                         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);
372         }
373
374         // allocate the brush and copy to it
375         brush = (colbrushf_t *)Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colpointf_t) * numpointsbuf + sizeof(colpointf_t) * numedgedirsbuf + sizeof(colplanef_t) * numplanesbuf + sizeof(int) * numelementsbuf);
376         brush->isaabb = isaabb;
377         brush->hasaabbplanes = hasaabbplanes;
378         brush->supercontents = supercontents;
379         brush->numplanes = numplanesbuf;
380         brush->numedgedirs = numedgedirsbuf;
381         brush->numpoints = numpointsbuf;
382         brush->numtriangles = numelementsbuf / 3;
383         brush->planes = (colplanef_t *)(brush + 1);
384         brush->points = (colpointf_t *)(brush->planes + brush->numplanes);
385         brush->edgedirs = (colpointf_t *)(brush->points + brush->numpoints);
386         brush->elements = (int *)(brush->points + brush->numpoints);
387         brush->q3surfaceflags = q3surfaceflags;
388         brush->texture = texture;
389         for (j = 0;j < brush->numpoints;j++)
390         {
391                 brush->points[j].v[0] = pointsbuf[j].v[0];
392                 brush->points[j].v[1] = pointsbuf[j].v[1];
393                 brush->points[j].v[2] = pointsbuf[j].v[2];
394         }
395         for (j = 0;j < brush->numedgedirs;j++)
396         {
397                 brush->edgedirs[j].v[0] = edgedirsbuf[j].v[0];
398                 brush->edgedirs[j].v[1] = edgedirsbuf[j].v[1];
399                 brush->edgedirs[j].v[2] = edgedirsbuf[j].v[2];
400         }
401         for (j = 0;j < brush->numplanes;j++)
402         {
403                 brush->planes[j].normal[0] = planesbuf[j].normal[0];
404                 brush->planes[j].normal[1] = planesbuf[j].normal[1];
405                 brush->planes[j].normal[2] = planesbuf[j].normal[2];
406                 brush->planes[j].dist = planesbuf[j].dist;
407                 brush->planes[j].q3surfaceflags = planesbuf[j].q3surfaceflags;
408                 brush->planes[j].texture = planesbuf[j].texture;
409         }
410         for (j = 0;j < brush->numtriangles * 3;j++)
411                 brush->elements[j] = elementsbuf[j];
412
413         xyzflags = 0;
414         VectorClear(brush->mins);
415         VectorClear(brush->maxs);
416         for (j = 0;j < min(6, numoriginalplanes);j++)
417         {
418                      if (originalplanes[j].normal[0] ==  1) {xyzflags |=  1;brush->maxs[0] =  originalplanes[j].dist;}
419                 else if (originalplanes[j].normal[0] == -1) {xyzflags |=  2;brush->mins[0] = -originalplanes[j].dist;}
420                 else if (originalplanes[j].normal[1] ==  1) {xyzflags |=  4;brush->maxs[1] =  originalplanes[j].dist;}
421                 else if (originalplanes[j].normal[1] == -1) {xyzflags |=  8;brush->mins[1] = -originalplanes[j].dist;}
422                 else if (originalplanes[j].normal[2] ==  1) {xyzflags |= 16;brush->maxs[2] =  originalplanes[j].dist;}
423                 else if (originalplanes[j].normal[2] == -1) {xyzflags |= 32;brush->mins[2] = -originalplanes[j].dist;}
424         }
425         // if not all xyzflags were set, then this is not a brush from q3map/q3map2, and needs reconstruction of the bounding box
426         // (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)
427         if (xyzflags != 63)
428         {
429                 VectorCopy(brush->points[0].v, brush->mins);
430                 VectorCopy(brush->points[0].v, brush->maxs);
431                 for (j = 1;j < brush->numpoints;j++)
432                 {
433                         brush->mins[0] = min(brush->mins[0], brush->points[j].v[0]);
434                         brush->mins[1] = min(brush->mins[1], brush->points[j].v[1]);
435                         brush->mins[2] = min(brush->mins[2], brush->points[j].v[2]);
436                         brush->maxs[0] = max(brush->maxs[0], brush->points[j].v[0]);
437                         brush->maxs[1] = max(brush->maxs[1], brush->points[j].v[1]);
438                         brush->maxs[2] = max(brush->maxs[2], brush->points[j].v[2]);
439                 }
440         }
441         brush->mins[0] -= 1;
442         brush->mins[1] -= 1;
443         brush->mins[2] -= 1;
444         brush->maxs[0] += 1;
445         brush->maxs[1] += 1;
446         brush->maxs[2] += 1;
447         Collision_ValidateBrush(brush);
448         return brush;
449 }
450
451
452
453 void Collision_CalcPlanesForTriangleBrushFloat(colbrushf_t *brush)
454 {
455         float edge0[3], edge1[3], edge2[3];
456         colpointf_t *p;
457
458         TriangleNormal(brush->points[0].v, brush->points[1].v, brush->points[2].v, brush->planes[0].normal);
459         if (DotProduct(brush->planes[0].normal, brush->planes[0].normal) < 0.0001f)
460         {
461                 // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
462                 // note that some of these exist in q3bsp bspline patches
463                 brush->numplanes = 0;
464                 return;
465         }
466
467         // there are 5 planes (front, back, sides) and 3 edges
468         brush->numplanes = 5;
469         brush->numedgedirs = 3;
470         VectorNormalize(brush->planes[0].normal);
471         brush->planes[0].dist = DotProduct(brush->points->v, brush->planes[0].normal);
472         VectorNegate(brush->planes[0].normal, brush->planes[1].normal);
473         brush->planes[1].dist = -brush->planes[0].dist;
474         // edge directions are easy to calculate
475         VectorSubtract(brush->points[2].v, brush->points[0].v, edge0);
476         VectorSubtract(brush->points[0].v, brush->points[1].v, edge1);
477         VectorSubtract(brush->points[1].v, brush->points[2].v, edge2);
478         VectorCopy(edge0, brush->edgedirs[0].v);
479         VectorCopy(edge1, brush->edgedirs[1].v);
480         VectorCopy(edge2, brush->edgedirs[2].v);
481         // now select an algorithm to generate the side planes
482         if (collision_triangle_bevelsides.integer)
483         {
484                 // 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
485                 CrossProduct(edge0, brush->planes->normal, brush->planes[2].normal);
486                 CrossProduct(edge1, brush->planes->normal, brush->planes[3].normal);
487                 CrossProduct(edge2, brush->planes->normal, brush->planes[4].normal);
488                 VectorNormalize(brush->planes[2].normal);
489                 VectorNormalize(brush->planes[3].normal);
490                 VectorNormalize(brush->planes[4].normal);
491                 VectorAdd(brush->planes[2].normal, brush->planes[0].normal, brush->planes[2].normal);
492                 VectorAdd(brush->planes[3].normal, brush->planes[0].normal, brush->planes[3].normal);
493                 VectorAdd(brush->planes[4].normal, brush->planes[0].normal, brush->planes[4].normal);
494                 VectorNormalize(brush->planes[2].normal);
495                 VectorNormalize(brush->planes[3].normal);
496                 VectorNormalize(brush->planes[4].normal);
497         }
498         else if (collision_triangle_axialsides.integer)
499         {
500                 float projectionnormal[3], projectionedge0[3], projectionedge1[3], projectionedge2[3];
501                 int i, best;
502                 float dist, bestdist;
503                 bestdist = fabs(brush->planes[0].normal[0]);
504                 best = 0;
505                 for (i = 1;i < 3;i++)
506                 {
507                         dist = fabs(brush->planes[0].normal[i]);
508                         if (bestdist < dist)
509                         {
510                                 bestdist = dist;
511                                 best = i;
512                         }
513                 }
514                 VectorClear(projectionnormal);
515                 if (brush->planes[0].normal[best] < 0)
516                         projectionnormal[best] = -1;
517                 else
518                         projectionnormal[best] = 1;
519                 VectorCopy(edge0, projectionedge0);
520                 VectorCopy(edge1, projectionedge1);
521                 VectorCopy(edge2, projectionedge2);
522                 projectionedge0[best] = 0;
523                 projectionedge1[best] = 0;
524                 projectionedge2[best] = 0;
525                 CrossProduct(projectionedge0, projectionnormal, brush->planes[2].normal);
526                 CrossProduct(projectionedge1, projectionnormal, brush->planes[3].normal);
527                 CrossProduct(projectionedge2, projectionnormal, brush->planes[4].normal);
528                 VectorNormalize(brush->planes[2].normal);
529                 VectorNormalize(brush->planes[3].normal);
530                 VectorNormalize(brush->planes[4].normal);
531         }
532         else
533         {
534                 CrossProduct(edge0, brush->planes->normal, brush->planes[2].normal);
535                 CrossProduct(edge1, brush->planes->normal, brush->planes[3].normal);
536                 CrossProduct(edge2, brush->planes->normal, brush->planes[4].normal);
537                 VectorNormalize(brush->planes[2].normal);
538                 VectorNormalize(brush->planes[3].normal);
539                 VectorNormalize(brush->planes[4].normal);
540         }
541         brush->planes[2].dist = DotProduct(brush->points[2].v, brush->planes[2].normal);
542         brush->planes[3].dist = DotProduct(brush->points[0].v, brush->planes[3].normal);
543         brush->planes[4].dist = DotProduct(brush->points[1].v, brush->planes[4].normal);
544
545         if (developer_extra.integer)
546         {
547                 int i;
548                 // validity check - will be disabled later
549                 Collision_ValidateBrush(brush);
550                 for (i = 0;i < brush->numplanes;i++)
551                 {
552                         int j;
553                         for (j = 0, p = brush->points;j < brush->numpoints;j++, p++)
554                                 if (DotProduct(p->v, brush->planes[i].normal) > brush->planes[i].dist + COLLISION_PLANE_DIST_EPSILON)
555                                         Con_DPrintf("Error in brush plane generation, plane %i\n", i);
556                 }
557         }
558 }
559
560 // NOTE: start and end of each brush pair must have same numplanes/numpoints
561 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)
562 {
563         int nplane, nplane2, nedge1, nedge2, hitq3surfaceflags = 0;
564         int tracenumedgedirs = trace_start->numedgedirs;
565         //int othernumedgedirs = other_start->numedgedirs;
566         int tracenumpoints = trace_start->numpoints;
567         int othernumpoints = other_start->numpoints;
568         int numplanes1 = other_start->numplanes;
569         int numplanes2 = numplanes1 + trace_start->numplanes;
570         int numplanes3 = numplanes2 + trace_start->numedgedirs * other_start->numedgedirs * 2;
571         vec_t enterfrac = -1, leavefrac = 1, startdist, enddist, ie, f, imove, enterfrac2 = -1;
572         vec4_t startplane;
573         vec4_t endplane;
574         vec4_t newimpactplane;
575         const texture_t *hittexture = NULL;
576         vec_t startdepth = 1;
577         vec3_t startdepthnormal;
578         const texture_t *starttexture = NULL;
579
580         VectorClear(startdepthnormal);
581         Vector4Clear(newimpactplane);
582
583         // fast case for AABB vs compiled brushes (which begin with AABB planes and also have precomputed bevels for AABB collisions)
584         if (trace_start->isaabb && other_start->hasaabbplanes)
585                 numplanes3 = numplanes2 = numplanes1;
586
587         // Separating Axis Theorem:
588         // if a supporting vector (plane normal) can be found that separates two
589         // objects, they are not colliding.
590         //
591         // Minkowski Sum:
592         // reduce the size of one object to a point while enlarging the other to
593         // represent the space that point can not occupy.
594         //
595         // try every plane we can construct between the two brushes and measure
596         // the distance between them.
597         for (nplane = 0;nplane < numplanes3;nplane++)
598         {
599                 if (nplane < numplanes1)
600                 {
601                         nplane2 = nplane;
602                         VectorCopy(other_start->planes[nplane2].normal, startplane);
603                         VectorCopy(other_end->planes[nplane2].normal, endplane);
604                 }
605                 else if (nplane < numplanes2)
606                 {
607                         nplane2 = nplane - numplanes1;
608                         VectorCopy(trace_start->planes[nplane2].normal, startplane);
609                         VectorCopy(trace_end->planes[nplane2].normal, endplane);
610                 }
611                 else
612                 {
613                         // pick an edgedir from each brush and cross them
614                         nplane2 = nplane - numplanes2;
615                         nedge1 = nplane2 >> 1;
616                         nedge2 = nedge1 / tracenumedgedirs;
617                         nedge1 -= nedge2 * tracenumedgedirs;
618                         if (nplane2 & 1)
619                         {
620                                 CrossProduct(trace_start->edgedirs[nedge1].v, other_start->edgedirs[nedge2].v, startplane);
621                                 CrossProduct(trace_end->edgedirs[nedge1].v, other_end->edgedirs[nedge2].v, endplane);
622                         }
623                         else
624                         {
625                                 CrossProduct(other_start->edgedirs[nedge2].v, trace_start->edgedirs[nedge1].v, startplane);
626                                 CrossProduct(other_end->edgedirs[nedge2].v, trace_end->edgedirs[nedge1].v, endplane);
627                         }
628                         if (VectorLength2(startplane) < COLLISION_EDGECROSS_MINLENGTH2 || VectorLength2(endplane) < COLLISION_EDGECROSS_MINLENGTH2)
629                                 continue; // degenerate crossproducts
630                         VectorNormalize(startplane);
631                         VectorNormalize(endplane);
632                 }
633                 startplane[3] = furthestplanedist_float(startplane, other_start->points, othernumpoints);
634                 endplane[3] = furthestplanedist_float(endplane, other_end->points, othernumpoints);
635                 startdist = nearestplanedist_float(startplane, trace_start->points, tracenumpoints) - startplane[3];
636                 enddist = nearestplanedist_float(endplane, trace_end->points, tracenumpoints) - endplane[3];
637                 //Con_Printf("%c%i: startdist = %f, enddist = %f, startdist / (startdist - enddist) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, startdist, enddist, startdist / (startdist - enddist));
638
639                 // aside from collisions, this is also used for error correction
640                 if (startdist <= 0.0f && nplane < numplanes1 && (startdepth < startdist || startdepth == 1))
641                 {
642                         startdepth = startdist;
643                         VectorCopy(startplane, startdepthnormal);
644                         starttexture = other_start->planes[nplane2].texture;
645                 }
646
647                 if (startdist > enddist)
648                 {
649                         // moving into brush
650                         if (enddist > 0.0f)
651                                 return;
652                         if (startdist >= 0)
653                         {
654                                 // enter
655                                 imove = 1 / (startdist - enddist);
656                                 f = startdist * imove;
657                                 // check if this will reduce the collision time range
658                                 if (enterfrac < f)
659                                 {
660                                         // reduced collision time range
661                                         enterfrac = f;
662                                         // if the collision time range is now empty, no collision
663                                         if (enterfrac > leavefrac)
664                                                 return;
665                                         // calculate the nudged fraction and impact normal we'll
666                                         // need if we accept this collision later
667                                         enterfrac2 = (startdist - collision_impactnudge.value) * imove;
668                                         // if the collision would be further away than the trace's
669                                         // existing collision data, we don't care about this
670                                         // collision
671                                         if (enterfrac2 >= trace->fraction)
672                                                 return;
673                                         ie = 1.0f - enterfrac;
674                                         newimpactplane[0] = startplane[0] * ie + endplane[0] * enterfrac;
675                                         newimpactplane[1] = startplane[1] * ie + endplane[1] * enterfrac;
676                                         newimpactplane[2] = startplane[2] * ie + endplane[2] * enterfrac;
677                                         newimpactplane[3] = startplane[3] * ie + endplane[3] * enterfrac;
678                                         if (nplane < numplanes1)
679                                         {
680                                                 // use the plane from other
681                                                 nplane2 = nplane;
682                                                 hitq3surfaceflags = other_start->planes[nplane2].q3surfaceflags;
683                                                 hittexture = other_start->planes[nplane2].texture;
684                                         }
685                                         else if (nplane < numplanes2)
686                                         {
687                                                 // use the plane from trace
688                                                 nplane2 = nplane - numplanes1;
689                                                 hitq3surfaceflags = trace_start->planes[nplane2].q3surfaceflags;
690                                                 hittexture = trace_start->planes[nplane2].texture;
691                                         }
692                                         else
693                                         {
694                                                 hitq3surfaceflags = other_start->q3surfaceflags;
695                                                 hittexture = other_start->texture;
696                                         }
697                                 }
698                         }
699                 }
700                 else
701                 {
702                         // moving out of brush
703                         if (startdist >= 0)
704                                 return;
705                         if (enddist > 0)
706                         {
707                                 // leave
708                                 f = startdist / (startdist - enddist);
709                                 // check if this will reduce the collision time range
710                                 if (leavefrac > f)
711                                 {
712                                         // reduced collision time range
713                                         leavefrac = f;
714                                         // if the collision time range is now empty, no collision
715                                         if (enterfrac > leavefrac)
716                                                 return;
717                                 }
718                         }
719                 }
720         }
721
722         // at this point we know the trace overlaps the brush because it was not
723         // rejected at any point in the loop above
724
725         // see if the trace started outside the brush or not
726         if (enterfrac > -1)
727         {
728                 // started outside, and overlaps, therefore there is a collision here
729                 // store out the impact information
730                 if ((trace->hitsupercontentsmask & other_start->supercontents) && !(trace->skipsupercontentsmask & other_start->supercontents) && !(trace->skipmaterialflagsmask & (hittexture ? hittexture->currentmaterialflags : 0)))
731                 {
732                         trace->hitsupercontents = other_start->supercontents;
733                         trace->hitq3surfaceflags = hitq3surfaceflags;
734                         trace->hittexture = hittexture;
735                         trace->fraction = bound(0, enterfrac2, 1);
736                         VectorCopy(newimpactplane, trace->plane.normal);
737                         trace->plane.dist = newimpactplane[3];
738                 }
739         }
740         else
741         {
742                 // started inside, update startsolid and friends
743                 trace->startsupercontents |= other_start->supercontents;
744                 if ((trace->hitsupercontentsmask & other_start->supercontents) && !(trace->skipsupercontentsmask & other_start->supercontents) && !(trace->skipmaterialflagsmask & (starttexture ? starttexture->currentmaterialflags : 0)))
745                 {
746                         trace->startsolid = true;
747                         if (leavefrac < 1)
748                                 trace->allsolid = true;
749                         VectorCopy(newimpactplane, trace->plane.normal);
750                         trace->plane.dist = newimpactplane[3];
751                         if (trace->startdepth > startdepth)
752                         {
753                                 trace->startdepth = startdepth;
754                                 VectorCopy(startdepthnormal, trace->startdepthnormal);
755                                 trace->starttexture = starttexture;
756                         }
757                 }
758         }
759 }
760
761 // NOTE: start and end of each brush pair must have same numplanes/numpoints
762 void Collision_TraceLineBrushFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const colbrushf_t *other_start, const colbrushf_t *other_end)
763 {
764         int nplane, hitq3surfaceflags = 0;
765         int numplanes = other_start->numplanes;
766         vec_t enterfrac = -1, leavefrac = 1, startdist, enddist, ie, f, imove, enterfrac2 = -1;
767         vec4_t startplane;
768         vec4_t endplane;
769         vec4_t newimpactplane;
770         const texture_t *hittexture = NULL;
771         vec_t startdepth = 1;
772         vec3_t startdepthnormal;
773         const texture_t *starttexture = NULL;
774
775         if (collision_debug_tracelineasbox.integer)
776         {
777                 colboxbrushf_t thisbrush_start, thisbrush_end;
778                 Collision_BrushForBox(&thisbrush_start, linestart, linestart, 0, 0, NULL);
779                 Collision_BrushForBox(&thisbrush_end, lineend, lineend, 0, 0, NULL);
780                 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, other_start, other_end);
781                 return;
782         }
783
784         VectorClear(startdepthnormal);
785         Vector4Clear(newimpactplane);
786
787         // Separating Axis Theorem:
788         // if a supporting vector (plane normal) can be found that separates two
789         // objects, they are not colliding.
790         //
791         // Minkowski Sum:
792         // reduce the size of one object to a point while enlarging the other to
793         // represent the space that point can not occupy.
794         //
795         // try every plane we can construct between the two brushes and measure
796         // the distance between them.
797         for (nplane = 0;nplane < numplanes;nplane++)
798         {
799                 VectorCopy(other_start->planes[nplane].normal, startplane);
800                 startplane[3] = other_start->planes[nplane].dist;
801                 VectorCopy(other_end->planes[nplane].normal, endplane);
802                 endplane[3] = other_end->planes[nplane].dist;
803                 startdist = DotProduct(linestart, startplane) - startplane[3];
804                 enddist = DotProduct(lineend, endplane) - endplane[3];
805                 //Con_Printf("%c%i: startdist = %f, enddist = %f, startdist / (startdist - enddist) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, startdist, enddist, startdist / (startdist - enddist));
806
807                 // aside from collisions, this is also used for error correction
808                 if (startdist <= 0.0f && (startdepth < startdist || startdepth == 1))
809                 {
810                         startdepth = startdist;
811                         VectorCopy(startplane, startdepthnormal);
812                         starttexture = other_start->planes[nplane].texture;
813                 }
814
815                 if (startdist > enddist)
816                 {
817                         // moving into brush
818                         if (enddist > 0.0f)
819                                 return;
820                         if (startdist > 0)
821                         {
822                                 // enter
823                                 imove = 1 / (startdist - enddist);
824                                 f = startdist * imove;
825                                 // check if this will reduce the collision time range
826                                 if (enterfrac < f)
827                                 {
828                                         // reduced collision time range
829                                         enterfrac = f;
830                                         // if the collision time range is now empty, no collision
831                                         if (enterfrac > leavefrac)
832                                                 return;
833                                         // calculate the nudged fraction and impact normal we'll
834                                         // need if we accept this collision later
835                                         enterfrac2 = (startdist - collision_impactnudge.value) * imove;
836                                         // if the collision would be further away than the trace's
837                                         // existing collision data, we don't care about this
838                                         // collision
839                                         if (enterfrac2 >= trace->fraction)
840                                                 return;
841                                         ie = 1.0f - enterfrac;
842                                         newimpactplane[0] = startplane[0] * ie + endplane[0] * enterfrac;
843                                         newimpactplane[1] = startplane[1] * ie + endplane[1] * enterfrac;
844                                         newimpactplane[2] = startplane[2] * ie + endplane[2] * enterfrac;
845                                         newimpactplane[3] = startplane[3] * ie + endplane[3] * enterfrac;
846                                         hitq3surfaceflags = other_start->planes[nplane].q3surfaceflags;
847                                         hittexture = other_start->planes[nplane].texture;
848                                 }
849                         }
850                 }
851                 else
852                 {
853                         // moving out of brush
854                         if (startdist > 0)
855                                 return;
856                         if (enddist > 0)
857                         {
858                                 // leave
859                                 f = startdist / (startdist - enddist);
860                                 // check if this will reduce the collision time range
861                                 if (leavefrac > f)
862                                 {
863                                         // reduced collision time range
864                                         leavefrac = f;
865                                         // if the collision time range is now empty, no collision
866                                         if (enterfrac > leavefrac)
867                                                 return;
868                                 }
869                         }
870                 }
871         }
872
873         // at this point we know the trace overlaps the brush because it was not
874         // rejected at any point in the loop above
875
876         // see if the trace started outside the brush or not
877         if (enterfrac > -1)
878         {
879                 // started outside, and overlaps, therefore there is a collision here
880                 // store out the impact information
881                 if ((trace->hitsupercontentsmask & other_start->supercontents) && !(trace->skipsupercontentsmask & other_start->supercontents) && !(trace->skipmaterialflagsmask & (hittexture ? hittexture->currentmaterialflags : 0)))
882                 {
883                         trace->hitsupercontents = other_start->supercontents;
884                         trace->hitq3surfaceflags = hitq3surfaceflags;
885                         trace->hittexture = hittexture;
886                         trace->fraction = bound(0, enterfrac2, 1);
887                         VectorCopy(newimpactplane, trace->plane.normal);
888                         trace->plane.dist = newimpactplane[3];
889                 }
890         }
891         else
892         {
893                 // started inside, update startsolid and friends
894                 trace->startsupercontents |= other_start->supercontents;
895                 if ((trace->hitsupercontentsmask & other_start->supercontents) && !(trace->skipsupercontentsmask & other_start->supercontents) && !(trace->skipmaterialflagsmask & (starttexture ? starttexture->currentmaterialflags : 0)))
896                 {
897                         trace->startsolid = true;
898                         if (leavefrac < 1)
899                                 trace->allsolid = true;
900                         VectorCopy(newimpactplane, trace->plane.normal);
901                         trace->plane.dist = newimpactplane[3];
902                         if (trace->startdepth > startdepth)
903                         {
904                                 trace->startdepth = startdepth;
905                                 VectorCopy(startdepthnormal, trace->startdepthnormal);
906                                 trace->starttexture = starttexture;
907                         }
908                 }
909         }
910 }
911
912 qboolean Collision_PointInsideBrushFloat(const vec3_t point, const colbrushf_t *brush)
913 {
914         int nplane;
915         const colplanef_t *plane;
916
917         if (!BoxesOverlap(point, point, brush->mins, brush->maxs))
918                 return false;
919         for (nplane = 0, plane = brush->planes;nplane < brush->numplanes;nplane++, plane++)
920                 if (DotProduct(plane->normal, point) > plane->dist)
921                         return false;
922         return true;
923 }
924
925 void Collision_TracePointBrushFloat(trace_t *trace, const vec3_t linestart, const colbrushf_t *other_start)
926 {
927         int nplane;
928         int numplanes = other_start->numplanes;
929         vec_t startdist;
930         vec4_t startplane;
931         vec4_t newimpactplane;
932         vec_t startdepth = 1;
933         vec3_t startdepthnormal;
934         const texture_t *starttexture = NULL;
935
936         VectorClear(startdepthnormal);
937         Vector4Clear(newimpactplane);
938
939         // Separating Axis Theorem:
940         // if a supporting vector (plane normal) can be found that separates two
941         // objects, they are not colliding.
942         //
943         // Minkowski Sum:
944         // reduce the size of one object to a point while enlarging the other to
945         // represent the space that point can not occupy.
946         //
947         // try every plane we can construct between the two brushes and measure
948         // the distance between them.
949         for (nplane = 0; nplane < numplanes; nplane++)
950         {
951                 VectorCopy(other_start->planes[nplane].normal, startplane);
952                 startplane[3] = other_start->planes[nplane].dist;
953                 startdist = DotProduct(linestart, startplane) - startplane[3];
954
955                 if (startdist > 0)
956                         return;
957
958                 // aside from collisions, this is also used for error correction
959                 if (startdepth < startdist || startdepth == 1)
960                 {
961                         startdepth = startdist;
962                         VectorCopy(startplane, startdepthnormal);
963                         starttexture = other_start->planes[nplane].texture;
964                 }
965         }
966
967         // at this point we know the trace overlaps the brush because it was not
968         // rejected at any point in the loop above
969
970         // started inside, update startsolid and friends
971         trace->startsupercontents |= other_start->supercontents;
972         if ((trace->hitsupercontentsmask & other_start->supercontents) && !(trace->skipsupercontentsmask & other_start->supercontents) && !(trace->skipmaterialflagsmask & (starttexture ? starttexture->currentmaterialflags : 0)))
973         {
974                 trace->startsolid = true;
975                 trace->allsolid = true;
976                 VectorCopy(newimpactplane, trace->plane.normal);
977                 trace->plane.dist = newimpactplane[3];
978                 if (trace->startdepth > startdepth)
979                 {
980                         trace->startdepth = startdepth;
981                         VectorCopy(startdepthnormal, trace->startdepthnormal);
982                         trace->starttexture = starttexture;
983                 }
984         }
985 }
986
987 static void Collision_SnapCopyPoints(int numpoints, const colpointf_t *in, colpointf_t *out, float fractionprecision, float invfractionprecision)
988 {
989         int i;
990         for (i = 0;i < numpoints;i++)
991         {
992                 out[i].v[0] = floor(in[i].v[0] * fractionprecision + 0.5f) * invfractionprecision;
993                 out[i].v[1] = floor(in[i].v[1] * fractionprecision + 0.5f) * invfractionprecision;
994                 out[i].v[2] = floor(in[i].v[2] * fractionprecision + 0.5f) * invfractionprecision;
995         }
996 }
997
998 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)
999 {
1000         int i;
1001         colpointf_t points[3];
1002         colpointf_t edgedirs[3];
1003         colplanef_t planes[5];
1004         colbrushf_t brush;
1005         memset(&brush, 0, sizeof(brush));
1006         brush.isaabb = false;
1007         brush.hasaabbplanes = false;
1008         brush.numpoints = 3;
1009         brush.numedgedirs = 3;
1010         brush.numplanes = 5;
1011         brush.points = points;
1012         brush.edgedirs = edgedirs;
1013         brush.planes = planes;
1014         brush.supercontents = supercontents;
1015         brush.q3surfaceflags = q3surfaceflags;
1016         brush.texture = texture;
1017         for (i = 0;i < brush.numplanes;i++)
1018         {
1019                 brush.planes[i].q3surfaceflags = q3surfaceflags;
1020                 brush.planes[i].texture = texture;
1021         }
1022         if(stride > 0)
1023         {
1024                 int k, cnt, tri;
1025                 cnt = (numtriangles + stride - 1) / stride;
1026                 for(i = 0; i < cnt; ++i)
1027                 {
1028                         if(BoxesOverlap(bbox6f + i * 6, bbox6f + i * 6 + 3, segmentmins, segmentmaxs))
1029                         {
1030                                 for(k = 0; k < stride; ++k)
1031                                 {
1032                                         tri = i * stride + k;
1033                                         if(tri >= numtriangles)
1034                                                 break;
1035                                         VectorCopy(vertex3f + element3i[tri * 3 + 0] * 3, points[0].v);
1036                                         VectorCopy(vertex3f + element3i[tri * 3 + 1] * 3, points[1].v);
1037                                         VectorCopy(vertex3f + element3i[tri * 3 + 2] * 3, points[2].v);
1038                                         Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1039                                         Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1040                                         Collision_CalcPlanesForTriangleBrushFloat(&brush);
1041                                         //Collision_PrintBrushAsQHull(&brush, "brush");
1042                                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1043                                 }
1044                         }
1045                 }
1046         }
1047         else if(stride == 0)
1048         {
1049                 for (i = 0;i < numtriangles;i++, element3i += 3)
1050                 {
1051                         if (TriangleBBoxOverlapsBox(vertex3f + element3i[0]*3, vertex3f + element3i[1]*3, vertex3f + element3i[2]*3, segmentmins, segmentmaxs))
1052                         {
1053                                 VectorCopy(vertex3f + element3i[0] * 3, points[0].v);
1054                                 VectorCopy(vertex3f + element3i[1] * 3, points[1].v);
1055                                 VectorCopy(vertex3f + element3i[2] * 3, points[2].v);
1056                                 Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1057                                 Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1058                                 Collision_CalcPlanesForTriangleBrushFloat(&brush);
1059                                 //Collision_PrintBrushAsQHull(&brush, "brush");
1060                                 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1061                         }
1062                 }
1063         }
1064         else
1065         {
1066                 for (i = 0;i < numtriangles;i++, element3i += 3)
1067                 {
1068                         VectorCopy(vertex3f + element3i[0] * 3, points[0].v);
1069                         VectorCopy(vertex3f + element3i[1] * 3, points[1].v);
1070                         VectorCopy(vertex3f + element3i[2] * 3, points[2].v);
1071                         Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1072                         Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1073                         Collision_CalcPlanesForTriangleBrushFloat(&brush);
1074                         //Collision_PrintBrushAsQHull(&brush, "brush");
1075                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1076                 }
1077         }
1078 }
1079
1080 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)
1081 {
1082         int i;
1083         // FIXME: snap vertices?
1084         if(stride > 0)
1085         {
1086                 int k, cnt, tri;
1087                 cnt = (numtriangles + stride - 1) / stride;
1088                 for(i = 0; i < cnt; ++i)
1089                 {
1090                         if(BoxesOverlap(bbox6f + i * 6, bbox6f + i * 6 + 3, segmentmins, segmentmaxs))
1091                         {
1092                                 for(k = 0; k < stride; ++k)
1093                                 {
1094                                         tri = i * stride + k;
1095                                         if(tri >= numtriangles)
1096                                                 break;
1097                                         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);
1098                                 }
1099                         }
1100                 }
1101         }
1102         else
1103         {
1104                 for (i = 0;i < numtriangles;i++, element3i += 3)
1105                         Collision_TraceLineTriangleFloat(trace, linestart, lineend, vertex3f + element3i[0] * 3, vertex3f + element3i[1] * 3, vertex3f + element3i[2] * 3, supercontents, q3surfaceflags, texture);
1106         }
1107 }
1108
1109 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)
1110 {
1111         int i;
1112         colpointf_t points[3];
1113         colpointf_t edgedirs[3];
1114         colplanef_t planes[5];
1115         colbrushf_t brush;
1116         memset(&brush, 0, sizeof(brush));
1117         brush.isaabb = false;
1118         brush.hasaabbplanes = false;
1119         brush.numpoints = 3;
1120         brush.numedgedirs = 3;
1121         brush.numplanes = 5;
1122         brush.points = points;
1123         brush.edgedirs = edgedirs;
1124         brush.planes = planes;
1125         brush.supercontents = supercontents;
1126         brush.q3surfaceflags = q3surfaceflags;
1127         brush.texture = texture;
1128         for (i = 0;i < brush.numplanes;i++)
1129         {
1130                 brush.planes[i].q3surfaceflags = q3surfaceflags;
1131                 brush.planes[i].texture = texture;
1132         }
1133         VectorCopy(v0, points[0].v);
1134         VectorCopy(v1, points[1].v);
1135         VectorCopy(v2, points[2].v);
1136         Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1137         Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1138         Collision_CalcPlanesForTriangleBrushFloat(&brush);
1139         //Collision_PrintBrushAsQHull(&brush, "brush");
1140         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1141 }
1142
1143 void Collision_BrushForBox(colboxbrushf_t *boxbrush, const vec3_t mins, const vec3_t maxs, int supercontents, int q3surfaceflags, const texture_t *texture)
1144 {
1145         int i;
1146         memset(boxbrush, 0, sizeof(*boxbrush));
1147         boxbrush->brush.isaabb = true;
1148         boxbrush->brush.hasaabbplanes = true;
1149         boxbrush->brush.points = boxbrush->points;
1150         boxbrush->brush.edgedirs = boxbrush->edgedirs;
1151         boxbrush->brush.planes = boxbrush->planes;
1152         boxbrush->brush.supercontents = supercontents;
1153         boxbrush->brush.q3surfaceflags = q3surfaceflags;
1154         boxbrush->brush.texture = texture;
1155         if (VectorCompare(mins, maxs))
1156         {
1157                 // point brush
1158                 boxbrush->brush.numpoints = 1;
1159                 boxbrush->brush.numedgedirs = 0;
1160                 boxbrush->brush.numplanes = 0;
1161                 VectorCopy(mins, boxbrush->brush.points[0].v);
1162         }
1163         else
1164         {
1165                 boxbrush->brush.numpoints = 8;
1166                 boxbrush->brush.numedgedirs = 3;
1167                 boxbrush->brush.numplanes = 6;
1168                 // there are 8 points on a box
1169                 // there are 3 edgedirs on a box (both signs are tested in collision)
1170                 // there are 6 planes on a box
1171                 VectorSet(boxbrush->brush.points[0].v, mins[0], mins[1], mins[2]);
1172                 VectorSet(boxbrush->brush.points[1].v, maxs[0], mins[1], mins[2]);
1173                 VectorSet(boxbrush->brush.points[2].v, mins[0], maxs[1], mins[2]);
1174                 VectorSet(boxbrush->brush.points[3].v, maxs[0], maxs[1], mins[2]);
1175                 VectorSet(boxbrush->brush.points[4].v, mins[0], mins[1], maxs[2]);
1176                 VectorSet(boxbrush->brush.points[5].v, maxs[0], mins[1], maxs[2]);
1177                 VectorSet(boxbrush->brush.points[6].v, mins[0], maxs[1], maxs[2]);
1178                 VectorSet(boxbrush->brush.points[7].v, maxs[0], maxs[1], maxs[2]);
1179                 VectorSet(boxbrush->brush.edgedirs[0].v, 1, 0, 0);
1180                 VectorSet(boxbrush->brush.edgedirs[1].v, 0, 1, 0);
1181                 VectorSet(boxbrush->brush.edgedirs[2].v, 0, 0, 1);
1182                 VectorSet(boxbrush->brush.planes[0].normal, -1,  0,  0);boxbrush->brush.planes[0].dist = -mins[0];
1183                 VectorSet(boxbrush->brush.planes[1].normal,  1,  0,  0);boxbrush->brush.planes[1].dist =  maxs[0];
1184                 VectorSet(boxbrush->brush.planes[2].normal,  0, -1,  0);boxbrush->brush.planes[2].dist = -mins[1];
1185                 VectorSet(boxbrush->brush.planes[3].normal,  0,  1,  0);boxbrush->brush.planes[3].dist =  maxs[1];
1186                 VectorSet(boxbrush->brush.planes[4].normal,  0,  0, -1);boxbrush->brush.planes[4].dist = -mins[2];
1187                 VectorSet(boxbrush->brush.planes[5].normal,  0,  0,  1);boxbrush->brush.planes[5].dist =  maxs[2];
1188                 for (i = 0;i < 6;i++)
1189                 {
1190                         boxbrush->brush.planes[i].q3surfaceflags = q3surfaceflags;
1191                         boxbrush->brush.planes[i].texture = texture;
1192                 }
1193         }
1194         boxbrush->brush.supercontents = supercontents;
1195         boxbrush->brush.q3surfaceflags = q3surfaceflags;
1196         boxbrush->brush.texture = texture;
1197         VectorSet(boxbrush->brush.mins, mins[0] - 1, mins[1] - 1, mins[2] - 1);
1198         VectorSet(boxbrush->brush.maxs, maxs[0] + 1, maxs[1] + 1, maxs[2] + 1);
1199         //Collision_ValidateBrush(&boxbrush->brush);
1200 }
1201
1202 //pseudocode for detecting line/sphere overlap without calculating an impact point
1203 //linesphereorigin = sphereorigin - linestart;linediff = lineend - linestart;linespherefrac = DotProduct(linesphereorigin, linediff) / DotProduct(linediff, linediff);return VectorLength2(linesphereorigin - bound(0, linespherefrac, 1) * linediff) >= sphereradius*sphereradius;
1204
1205 // LordHavoc: currently unused, but tested
1206 // note: this can be used for tracing a moving sphere vs a stationary sphere,
1207 // by simply adding the moving sphere's radius to the sphereradius parameter,
1208 // all the results are correct (impactpoint, impactnormal, and fraction)
1209 float Collision_ClipTrace_Line_Sphere(double *linestart, double *lineend, double *sphereorigin, double sphereradius, double *impactpoint, double *impactnormal)
1210 {
1211         double dir[3], scale, v[3], deviationdist2, impactdist, linelength;
1212         // make sure the impactpoint and impactnormal are valid even if there is
1213         // no collision
1214         VectorCopy(lineend, impactpoint);
1215         VectorClear(impactnormal);
1216         // calculate line direction
1217         VectorSubtract(lineend, linestart, dir);
1218         // normalize direction
1219         linelength = VectorLength(dir);
1220         if (linelength)
1221         {
1222                 scale = 1.0 / linelength;
1223                 VectorScale(dir, scale, dir);
1224         }
1225         // this dotproduct calculates the distance along the line at which the
1226         // sphere origin is (nearest point to the sphere origin on the line)
1227         impactdist = DotProduct(sphereorigin, dir) - DotProduct(linestart, dir);
1228         // calculate point on line at that distance, and subtract the
1229         // sphereorigin from it, so we have a vector to measure for the distance
1230         // of the line from the sphereorigin (deviation, how off-center it is)
1231         VectorMA(linestart, impactdist, dir, v);
1232         VectorSubtract(v, sphereorigin, v);
1233         deviationdist2 = sphereradius * sphereradius - VectorLength2(v);
1234         // if squared offset length is outside the squared sphere radius, miss
1235         if (deviationdist2 < 0)
1236                 return 1; // miss (off to the side)
1237         // nudge back to find the correct impact distance
1238         impactdist -= sqrt(deviationdist2);
1239         if (impactdist >= linelength)
1240                 return 1; // miss (not close enough)
1241         if (impactdist < 0)
1242                 return 1; // miss (linestart is past or inside sphere)
1243         // calculate new impactpoint
1244         VectorMA(linestart, impactdist, dir, impactpoint);
1245         // calculate impactnormal (surface normal at point of impact)
1246         VectorSubtract(impactpoint, sphereorigin, impactnormal);
1247         // normalize impactnormal
1248         VectorNormalize(impactnormal);
1249         // return fraction of movement distance
1250         return impactdist / linelength;
1251 }
1252
1253 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)
1254 {
1255         float d1, d2, d, f, f2, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, faceplanenormallength2, edge01[3], edge21[3], edge02[3];
1256
1257         // this function executes:
1258         // 32 ops when line starts behind triangle
1259         // 38 ops when line ends infront of triangle
1260         // 43 ops when line fraction is already closer than this triangle
1261         // 72 ops when line is outside edge 01
1262         // 92 ops when line is outside edge 21
1263         // 115 ops when line is outside edge 02
1264         // 123 ops when line impacts triangle and updates trace results
1265
1266         // this code is designed for clockwise triangles, conversion to
1267         // counterclockwise would require swapping some things around...
1268         // it is easier to simply swap the point0 and point2 parameters to this
1269         // function when calling it than it is to rewire the internals.
1270
1271         // calculate the faceplanenormal of the triangle, this represents the front side
1272         // 15 ops
1273         VectorSubtract(point0, point1, edge01);
1274         VectorSubtract(point2, point1, edge21);
1275         CrossProduct(edge01, edge21, faceplanenormal);
1276         // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
1277         // 6 ops
1278         faceplanenormallength2 = DotProduct(faceplanenormal, faceplanenormal);
1279         if (faceplanenormallength2 < 0.0001f)
1280                 return;
1281         // calculate the distance
1282         // 5 ops
1283         faceplanedist = DotProduct(point0, faceplanenormal);
1284
1285         // if start point is on the back side there is no collision
1286         // (we don't care about traces going through the triangle the wrong way)
1287
1288         // calculate the start distance
1289         // 6 ops
1290         d1 = DotProduct(faceplanenormal, linestart);
1291         if (d1 <= faceplanedist)
1292                 return;
1293
1294         // calculate the end distance
1295         // 6 ops
1296         d2 = DotProduct(faceplanenormal, lineend);
1297         // if both are in front, there is no collision
1298         if (d2 >= faceplanedist)
1299                 return;
1300
1301         // from here on we know d1 is >= 0 and d2 is < 0
1302         // this means the line starts infront and ends behind, passing through it
1303
1304         // calculate the recipricol of the distance delta,
1305         // so we can use it multiple times cheaply (instead of division)
1306         // 2 ops
1307         d = 1.0f / (d1 - d2);
1308         // calculate the impact fraction by taking the start distance (> 0)
1309         // and subtracting the face plane distance (this is the distance of the
1310         // triangle along that same normal)
1311         // then multiply by the recipricol distance delta
1312         // 4 ops
1313         f = (d1 - faceplanedist) * d;
1314         f2  = f - collision_impactnudge.value * d;
1315         // skip out if this impact is further away than previous ones
1316         // 1 ops
1317         if (f2 >= trace->fraction)
1318                 return;
1319         // calculate the perfect impact point for classification of insidedness
1320         // 9 ops
1321         impact[0] = linestart[0] + f * (lineend[0] - linestart[0]);
1322         impact[1] = linestart[1] + f * (lineend[1] - linestart[1]);
1323         impact[2] = linestart[2] + f * (lineend[2] - linestart[2]);
1324
1325         // calculate the edge normal and reject if impact is outside triangle
1326         // (an edge normal faces away from the triangle, to get the desired normal
1327         //  a crossproduct with the faceplanenormal is used, and because of the way
1328         // the insidedness comparison is written it does not need to be normalized)
1329
1330         // first use the two edges from the triangle plane math
1331         // the other edge only gets calculated if the point survives that long
1332
1333         // 20 ops
1334         CrossProduct(edge01, faceplanenormal, edgenormal);
1335         if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1336                 return;
1337
1338         // 20 ops
1339         CrossProduct(faceplanenormal, edge21, edgenormal);
1340         if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1341                 return;
1342
1343         // 23 ops
1344         VectorSubtract(point0, point2, edge02);
1345         CrossProduct(faceplanenormal, edge02, edgenormal);
1346         if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1347                 return;
1348
1349         // 8 ops (rare)
1350
1351         // skip if this trace should not be blocked by these contents
1352         if (!(supercontents & trace->hitsupercontentsmask) || (supercontents & trace->skipsupercontentsmask) || (texture->currentmaterialflags & trace->skipmaterialflagsmask))
1353                 return;
1354
1355         // store the new trace fraction
1356         trace->fraction = f2;
1357
1358         // store the new trace plane (because collisions only happen from
1359         // the front this is always simply the triangle normal, never flipped)
1360         d = 1.0 / sqrt(faceplanenormallength2);
1361         VectorScale(faceplanenormal, d, trace->plane.normal);
1362         trace->plane.dist = faceplanedist * d;
1363
1364         trace->hitsupercontents = supercontents;
1365         trace->hitq3surfaceflags = q3surfaceflags;
1366         trace->hittexture = texture;
1367 }
1368
1369 void Collision_BoundingBoxOfBrushTraceSegment(const colbrushf_t *start, const colbrushf_t *end, vec3_t mins, vec3_t maxs, float startfrac, float endfrac)
1370 {
1371         int i;
1372         colpointf_t *ps, *pe;
1373         float tempstart[3], tempend[3];
1374         VectorLerp(start->points[0].v, startfrac, end->points[0].v, mins);
1375         VectorCopy(mins, maxs);
1376         for (i = 0, ps = start->points, pe = end->points;i < start->numpoints;i++, ps++, pe++)
1377         {
1378                 VectorLerp(ps->v, startfrac, pe->v, tempstart);
1379                 VectorLerp(ps->v, endfrac, pe->v, tempend);
1380                 mins[0] = min(mins[0], min(tempstart[0], tempend[0]));
1381                 mins[1] = min(mins[1], min(tempstart[1], tempend[1]));
1382                 mins[2] = min(mins[2], min(tempstart[2], tempend[2]));
1383                 maxs[0] = min(maxs[0], min(tempstart[0], tempend[0]));
1384                 maxs[1] = min(maxs[1], min(tempstart[1], tempend[1]));
1385                 maxs[2] = min(maxs[2], min(tempstart[2], tempend[2]));
1386         }
1387         mins[0] -= 1;
1388         mins[1] -= 1;
1389         mins[2] -= 1;
1390         maxs[0] += 1;
1391         maxs[1] += 1;
1392         maxs[2] += 1;
1393 }
1394
1395 //===========================================
1396
1397 static void Collision_TranslateBrush(const vec3_t shift, colbrushf_t *brush)
1398 {
1399         int i;
1400         // now we can transform the data
1401         for(i = 0; i < brush->numplanes; ++i)
1402         {
1403                 brush->planes[i].dist += DotProduct(shift, brush->planes[i].normal);
1404         }
1405         for(i = 0; i < brush->numpoints; ++i)
1406         {
1407                 VectorAdd(brush->points[i].v, shift, brush->points[i].v);
1408         }
1409         VectorAdd(brush->mins, shift, brush->mins);
1410         VectorAdd(brush->maxs, shift, brush->maxs);
1411 }
1412
1413 static void Collision_TransformBrush(const matrix4x4_t *matrix, colbrushf_t *brush)
1414 {
1415         int i;
1416         vec3_t v;
1417         // we're breaking any AABB properties here...
1418         brush->isaabb = false;
1419         brush->hasaabbplanes = false;
1420         // now we can transform the data
1421         for(i = 0; i < brush->numplanes; ++i)
1422         {
1423                 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_and_dist);
1424         }
1425         for(i = 0; i < brush->numedgedirs; ++i)
1426         {
1427                 Matrix4x4_Transform(matrix, brush->edgedirs[i].v, v);
1428                 VectorCopy(v, brush->edgedirs[i].v);
1429         }
1430         for(i = 0; i < brush->numpoints; ++i)
1431         {
1432                 Matrix4x4_Transform(matrix, brush->points[i].v, v);
1433                 VectorCopy(v, brush->points[i].v);
1434         }
1435         VectorCopy(brush->points[0].v, brush->mins);
1436         VectorCopy(brush->points[0].v, brush->maxs);
1437         for(i = 1; i < brush->numpoints; ++i)
1438         {
1439                 if(brush->points[i].v[0] < brush->mins[0]) brush->mins[0] = brush->points[i].v[0];
1440                 if(brush->points[i].v[1] < brush->mins[1]) brush->mins[1] = brush->points[i].v[1];
1441                 if(brush->points[i].v[2] < brush->mins[2]) brush->mins[2] = brush->points[i].v[2];
1442                 if(brush->points[i].v[0] > brush->maxs[0]) brush->maxs[0] = brush->points[i].v[0];
1443                 if(brush->points[i].v[1] > brush->maxs[1]) brush->maxs[1] = brush->points[i].v[1];
1444                 if(brush->points[i].v[2] > brush->maxs[2]) brush->maxs[2] = brush->points[i].v[2];
1445         }
1446 }
1447
1448 typedef struct collision_cachedtrace_parameters_s
1449 {
1450         dp_model_t *model;
1451         vec3_t end;
1452         vec3_t start;
1453         int hitsupercontentsmask;
1454         int skipsupercontentsmask;
1455         int skipmaterialflagsmask;
1456         matrix4x4_t matrix;
1457 }
1458 collision_cachedtrace_parameters_t;
1459
1460 typedef struct collision_cachedtrace_s
1461 {
1462         qboolean valid;
1463         collision_cachedtrace_parameters_t p;
1464         trace_t result;
1465 }
1466 collision_cachedtrace_t;
1467
1468 static mempool_t *collision_cachedtrace_mempool;
1469 static collision_cachedtrace_t *collision_cachedtrace_array;
1470 static int collision_cachedtrace_firstfree;
1471 static int collision_cachedtrace_lastused;
1472 static int collision_cachedtrace_max;
1473 static unsigned char collision_cachedtrace_sequence;
1474 static int collision_cachedtrace_hashsize;
1475 static int *collision_cachedtrace_hash;
1476 static unsigned int *collision_cachedtrace_arrayfullhashindex;
1477 static unsigned int *collision_cachedtrace_arrayhashindex;
1478 static unsigned int *collision_cachedtrace_arraynext;
1479 static unsigned char *collision_cachedtrace_arrayused;
1480 static qboolean collision_cachedtrace_rebuildhash;
1481
1482 void Collision_Cache_Reset(qboolean resetlimits)
1483 {
1484         if (collision_cachedtrace_hash)
1485                 Mem_Free(collision_cachedtrace_hash);
1486         if (collision_cachedtrace_array)
1487                 Mem_Free(collision_cachedtrace_array);
1488         if (collision_cachedtrace_arrayfullhashindex)
1489                 Mem_Free(collision_cachedtrace_arrayfullhashindex);
1490         if (collision_cachedtrace_arrayhashindex)
1491                 Mem_Free(collision_cachedtrace_arrayhashindex);
1492         if (collision_cachedtrace_arraynext)
1493                 Mem_Free(collision_cachedtrace_arraynext);
1494         if (collision_cachedtrace_arrayused)
1495                 Mem_Free(collision_cachedtrace_arrayused);
1496         if (resetlimits || !collision_cachedtrace_max)
1497                 collision_cachedtrace_max = collision_cache.integer ? 128 : 1;
1498         collision_cachedtrace_firstfree = 1;
1499         collision_cachedtrace_lastused = 0;
1500         collision_cachedtrace_hashsize = collision_cachedtrace_max;
1501         collision_cachedtrace_array = (collision_cachedtrace_t *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(collision_cachedtrace_t));
1502         collision_cachedtrace_hash = (int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_hashsize * sizeof(int));
1503         collision_cachedtrace_arrayfullhashindex = (unsigned int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned int));
1504         collision_cachedtrace_arrayhashindex = (unsigned int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned int));
1505         collision_cachedtrace_arraynext = (unsigned int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned int));
1506         collision_cachedtrace_arrayused = (unsigned char *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned char));
1507         collision_cachedtrace_sequence = 1;
1508         collision_cachedtrace_rebuildhash = false;
1509 }
1510
1511 void Collision_Cache_Init(mempool_t *mempool)
1512 {
1513         collision_cachedtrace_mempool = mempool;
1514         Collision_Cache_Reset(true);
1515 }
1516
1517 static void Collision_Cache_RebuildHash(void)
1518 {
1519         int index;
1520         int range = collision_cachedtrace_lastused + 1;
1521         unsigned char sequence = collision_cachedtrace_sequence;
1522         int firstfree = collision_cachedtrace_max;
1523         int lastused = 0;
1524         int *hash = collision_cachedtrace_hash;
1525         unsigned int hashindex;
1526         unsigned int *arrayhashindex = collision_cachedtrace_arrayhashindex;
1527         unsigned int *arraynext = collision_cachedtrace_arraynext;
1528         collision_cachedtrace_rebuildhash = false;
1529         memset(collision_cachedtrace_hash, 0, collision_cachedtrace_hashsize * sizeof(int));
1530         for (index = 1;index < range;index++)
1531         {
1532                 if (collision_cachedtrace_arrayused[index] == sequence)
1533                 {
1534                         hashindex = arrayhashindex[index];
1535                         arraynext[index] = hash[hashindex];
1536                         hash[hashindex] = index;
1537                         lastused = index;
1538                 }
1539                 else
1540                 {
1541                         if (firstfree > index)
1542                                 firstfree = index;
1543                         collision_cachedtrace_arrayused[index] = 0;
1544                 }
1545         }
1546         collision_cachedtrace_firstfree = firstfree;
1547         collision_cachedtrace_lastused = lastused;
1548 }
1549
1550 void Collision_Cache_NewFrame(void)
1551 {
1552         if (collision_cache.integer)
1553         {
1554                 if (collision_cachedtrace_max < 128)
1555                         Collision_Cache_Reset(true);
1556         }
1557         else
1558         {
1559                 if (collision_cachedtrace_max > 1)
1560                         Collision_Cache_Reset(true);
1561         }
1562         // rebuild hash if sequence would overflow byte, otherwise increment
1563         if (collision_cachedtrace_sequence == 255)
1564         {
1565                 Collision_Cache_RebuildHash();
1566                 collision_cachedtrace_sequence = 1;
1567         }
1568         else
1569         {
1570                 collision_cachedtrace_rebuildhash = true;
1571                 collision_cachedtrace_sequence++;
1572         }
1573 }
1574
1575 static unsigned int Collision_Cache_HashIndexForArray(unsigned int *array, unsigned int size)
1576 {
1577         unsigned int i;
1578         unsigned int hashindex = 0;
1579         // this is a super-cheesy checksum, designed only for speed
1580         for (i = 0;i < size;i++)
1581                 hashindex += array[i] * (1 + i);
1582         return hashindex;
1583 }
1584
1585 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, int skipsupercontentsmask, int skipmaterialflagsmask)
1586 {
1587         int hashindex = 0;
1588         unsigned int fullhashindex;
1589         int index = 0;
1590         int range;
1591         unsigned char sequence = collision_cachedtrace_sequence;
1592         int *hash = collision_cachedtrace_hash;
1593         unsigned int *arrayfullhashindex = collision_cachedtrace_arrayfullhashindex;
1594         unsigned int *arraynext = collision_cachedtrace_arraynext;
1595         collision_cachedtrace_t *cached = collision_cachedtrace_array + index;
1596         collision_cachedtrace_parameters_t params;
1597         // all non-cached traces use the same index
1598         if (!collision_cache.integer)
1599                 r_refdef.stats[r_stat_photoncache_traced]++;
1600         else
1601         {
1602                 // cached trace lookup
1603                 memset(&params, 0, sizeof(params));
1604                 params.model = model;
1605                 VectorCopy(start, params.start);
1606                 VectorCopy(end,   params.end);
1607                 params.hitsupercontentsmask = hitsupercontentsmask;
1608                 params.skipsupercontentsmask = skipsupercontentsmask;
1609                 params.skipmaterialflagsmask = skipmaterialflagsmask;
1610                 params.matrix = *matrix;
1611                 fullhashindex = Collision_Cache_HashIndexForArray((unsigned int *)&params, sizeof(params) / sizeof(unsigned int));
1612                 hashindex = (int)(fullhashindex % (unsigned int)collision_cachedtrace_hashsize);
1613                 for (index = hash[hashindex];index;index = arraynext[index])
1614                 {
1615                         if (arrayfullhashindex[index] != fullhashindex)
1616                                 continue;
1617                         cached = collision_cachedtrace_array + index;
1618                         //if (memcmp(&cached->p, &params, sizeof(params)))
1619                         if (cached->p.model != params.model
1620                          || cached->p.end[0] != params.end[0]
1621                          || cached->p.end[1] != params.end[1]
1622                          || cached->p.end[2] != params.end[2]
1623                          || cached->p.start[0] != params.start[0]
1624                          || cached->p.start[1] != params.start[1]
1625                          || cached->p.start[2] != params.start[2]
1626                          || cached->p.hitsupercontentsmask != params.hitsupercontentsmask
1627                          || cached->p.skipsupercontentsmask != params.skipsupercontentsmask
1628                          || cached->p.skipmaterialflagsmask != params.skipmaterialflagsmask
1629                          || cached->p.matrix.m[0][0] != params.matrix.m[0][0]
1630                          || cached->p.matrix.m[0][1] != params.matrix.m[0][1]
1631                          || cached->p.matrix.m[0][2] != params.matrix.m[0][2]
1632                          || cached->p.matrix.m[0][3] != params.matrix.m[0][3]
1633                          || cached->p.matrix.m[1][0] != params.matrix.m[1][0]
1634                          || cached->p.matrix.m[1][1] != params.matrix.m[1][1]
1635                          || cached->p.matrix.m[1][2] != params.matrix.m[1][2]
1636                          || cached->p.matrix.m[1][3] != params.matrix.m[1][3]
1637                          || cached->p.matrix.m[2][0] != params.matrix.m[2][0]
1638                          || cached->p.matrix.m[2][1] != params.matrix.m[2][1]
1639                          || cached->p.matrix.m[2][2] != params.matrix.m[2][2]
1640                          || cached->p.matrix.m[2][3] != params.matrix.m[2][3]
1641                          || cached->p.matrix.m[3][0] != params.matrix.m[3][0]
1642                          || cached->p.matrix.m[3][1] != params.matrix.m[3][1]
1643                          || cached->p.matrix.m[3][2] != params.matrix.m[3][2]
1644                          || cached->p.matrix.m[3][3] != params.matrix.m[3][3]
1645                         )
1646                                 continue;
1647                         // found a matching trace in the cache
1648                         r_refdef.stats[r_stat_photoncache_cached]++;
1649                         cached->valid = true;
1650                         collision_cachedtrace_arrayused[index] = collision_cachedtrace_sequence;
1651                         return cached;
1652                 }
1653                 r_refdef.stats[r_stat_photoncache_traced]++;
1654                 // find an unused cache entry
1655                 for (index = collision_cachedtrace_firstfree, range = collision_cachedtrace_max;index < range;index++)
1656                         if (collision_cachedtrace_arrayused[index] == 0)
1657                                 break;
1658                 if (index == range)
1659                 {
1660                         // all claimed, but probably some are stale...
1661                         for (index = 1, range = collision_cachedtrace_max;index < range;index++)
1662                                 if (collision_cachedtrace_arrayused[index] != sequence)
1663                                         break;
1664                         if (index < range)
1665                         {
1666                                 // found a stale one, rebuild the hash
1667                                 Collision_Cache_RebuildHash();
1668                         }
1669                         else
1670                         {
1671                                 // we need to grow the cache
1672                                 collision_cachedtrace_max *= 2;
1673                                 Collision_Cache_Reset(false);
1674                                 index = 1;
1675                         }
1676                 }
1677                 // link the new cache entry into the hash bucket
1678                 collision_cachedtrace_firstfree = index + 1;
1679                 if (collision_cachedtrace_lastused < index)
1680                         collision_cachedtrace_lastused = index;
1681                 cached = collision_cachedtrace_array + index;
1682                 collision_cachedtrace_arraynext[index] = collision_cachedtrace_hash[hashindex];
1683                 collision_cachedtrace_hash[hashindex] = index;
1684                 collision_cachedtrace_arrayhashindex[index] = hashindex;
1685                 cached->valid = false;
1686                 cached->p = params;
1687                 collision_cachedtrace_arrayfullhashindex[index] = fullhashindex;
1688                 collision_cachedtrace_arrayused[index] = collision_cachedtrace_sequence;
1689         }
1690         return cached;
1691 }
1692
1693 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, int skipsupercontentsmask, int skipmaterialflagsmask)
1694 {
1695         collision_cachedtrace_t *cached = Collision_Cache_Lookup(model, matrix, inversematrix, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1696         if (cached->valid)
1697         {
1698                 *trace = cached->result;
1699                 return;
1700         }
1701
1702         Collision_ClipLineToGenericEntity(trace, model, NULL, NULL, vec3_origin, vec3_origin, 0, matrix, inversematrix, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, collision_extendmovelength.value, true);
1703
1704         cached->result = *trace;
1705 }
1706
1707 void Collision_Cache_ClipLineToWorldSurfaces(trace_t *trace, dp_model_t *model, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
1708 {
1709         collision_cachedtrace_t *cached = Collision_Cache_Lookup(model, &identitymatrix, &identitymatrix, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1710         if (cached->valid)
1711         {
1712                 *trace = cached->result;
1713                 return;
1714         }
1715
1716         Collision_ClipLineToWorld(trace, model, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, collision_extendmovelength.value, true);
1717
1718         cached->result = *trace;
1719 }
1720
1721 typedef struct extendtraceinfo_s
1722 {
1723         trace_t *trace;
1724         float realstart[3];
1725         float realend[3];
1726         float realdelta[3];
1727         float extendstart[3];
1728         float extendend[3];
1729         float extenddelta[3];
1730         float reallength;
1731         float extendlength;
1732         float scaletoextend;
1733         float extend;
1734 }
1735 extendtraceinfo_t;
1736
1737 static void Collision_ClipExtendPrepare(extendtraceinfo_t *extendtraceinfo, trace_t *trace, const vec3_t tstart, const vec3_t tend, float textend)
1738 {
1739         memset(trace, 0, sizeof(*trace));
1740         trace->fraction = 1;
1741
1742         extendtraceinfo->trace = trace;
1743         VectorCopy(tstart, extendtraceinfo->realstart);
1744         VectorCopy(tend, extendtraceinfo->realend);
1745         VectorSubtract(extendtraceinfo->realend, extendtraceinfo->realstart, extendtraceinfo->realdelta);
1746         VectorCopy(extendtraceinfo->realstart, extendtraceinfo->extendstart);
1747         VectorCopy(extendtraceinfo->realend, extendtraceinfo->extendend);
1748         VectorCopy(extendtraceinfo->realdelta, extendtraceinfo->extenddelta);
1749         extendtraceinfo->reallength = VectorLength(extendtraceinfo->realdelta);
1750         extendtraceinfo->extendlength = extendtraceinfo->reallength;
1751         extendtraceinfo->scaletoextend = 1.0f;
1752         extendtraceinfo->extend = textend;
1753
1754         // make the trace longer according to the extend parameter
1755         if (extendtraceinfo->reallength && extendtraceinfo->extend)
1756         {
1757                 extendtraceinfo->extendlength = extendtraceinfo->reallength + extendtraceinfo->extend;
1758                 extendtraceinfo->scaletoextend = extendtraceinfo->extendlength / extendtraceinfo->reallength;
1759                 VectorMA(extendtraceinfo->realstart, extendtraceinfo->scaletoextend, extendtraceinfo->realdelta, extendtraceinfo->extendend);
1760                 VectorSubtract(extendtraceinfo->extendend, extendtraceinfo->extendstart, extendtraceinfo->extenddelta);
1761         }
1762 }
1763
1764 static void Collision_ClipExtendFinish(extendtraceinfo_t *extendtraceinfo)
1765 {
1766         trace_t *trace = extendtraceinfo->trace;
1767
1768         if (trace->fraction != 1.0f)
1769         {
1770                 // undo the extended trace length
1771                 trace->fraction *= extendtraceinfo->scaletoextend;
1772
1773                 // if the extended trace hit something that the unextended trace did not hit (even considering the collision_impactnudge), then we have to clear the hit information
1774                 if (trace->fraction > 1.0f)
1775                 {
1776                         // note that ent may refer to either startsolid or fraction<1, we can't restore the startsolid ent unfortunately
1777                         trace->ent = NULL;
1778                         trace->hitq3surfaceflags = 0;
1779                         trace->hitsupercontents = 0;
1780                         trace->hittexture = NULL;
1781                         VectorClear(trace->plane.normal);
1782                         trace->plane.dist = 0.0f;
1783                 }
1784         }
1785
1786         // clamp things
1787         trace->fraction = bound(0, trace->fraction, 1);
1788
1789         // calculate the end position
1790         VectorMA(extendtraceinfo->realstart, trace->fraction, extendtraceinfo->realdelta, trace->endpos);
1791 }
1792
1793 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 tstart, const vec3_t mins, const vec3_t maxs, const vec3_t tend, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, float extend)
1794 {
1795         vec3_t starttransformed, endtransformed;
1796         extendtraceinfo_t extendtraceinfo;
1797         Collision_ClipExtendPrepare(&extendtraceinfo, trace, tstart, tend, extend);
1798
1799         Matrix4x4_Transform(inversematrix, extendtraceinfo.extendstart, starttransformed);
1800         Matrix4x4_Transform(inversematrix, extendtraceinfo.extendend, endtransformed);
1801 #if COLLISIONPARANOID >= 3
1802         Con_Printf("trans(%f %f %f -> %f %f %f, %f %f %f -> %f %f %f)", extendtraceinfo.extendstart[0], extendtraceinfo.extendstart[1], extendtraceinfo.extendstart[2], starttransformed[0], starttransformed[1], starttransformed[2], extendtraceinfo.extendend[0], extendtraceinfo.extendend[1], extendtraceinfo.extendend[2], endtransformed[0], endtransformed[1], endtransformed[2]);
1803 #endif
1804
1805         if (model && model->TraceBox)
1806         {
1807                 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]))
1808                 {
1809                         // we get here if TraceBrush exists, AND we have a rotation component (SOLID_BSP case)
1810                         // using starttransformed, endtransformed is WRONG in this case!
1811                         // should rather build a brush and trace using it
1812                         colboxbrushf_t thisbrush_start, thisbrush_end;
1813                         Collision_BrushForBox(&thisbrush_start, mins, maxs, 0, 0, NULL);
1814                         Collision_BrushForBox(&thisbrush_end, mins, maxs, 0, 0, NULL);
1815                         Collision_TranslateBrush(extendtraceinfo.extendstart, &thisbrush_start.brush);
1816                         Collision_TranslateBrush(extendtraceinfo.extendend, &thisbrush_end.brush);
1817                         Collision_TransformBrush(inversematrix, &thisbrush_start.brush);
1818                         Collision_TransformBrush(inversematrix, &thisbrush_end.brush);
1819                         //Collision_TranslateBrush(starttransformed, &thisbrush_start.brush);
1820                         //Collision_TranslateBrush(endtransformed, &thisbrush_end.brush);
1821                         model->TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1822                 }
1823                 else // this is only approximate if rotated, quite useless
1824                         model->TraceBox(model, frameblend, skeleton, trace, starttransformed, mins, maxs, endtransformed, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1825         }
1826         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
1827                 Collision_ClipTrace_Box(trace, bodymins, bodymaxs, starttransformed, mins, maxs, endtransformed, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, bodysupercontents, 0, NULL);
1828
1829         Collision_ClipExtendFinish(&extendtraceinfo);
1830
1831         // transform plane
1832         // NOTE: this relies on plane.dist being directly after plane.normal
1833         Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal_and_dist);
1834 }
1835
1836 void Collision_ClipToWorld(trace_t *trace, dp_model_t *model, const vec3_t tstart, const vec3_t mins, const vec3_t maxs, const vec3_t tend, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, float extend)
1837 {
1838         extendtraceinfo_t extendtraceinfo;
1839         Collision_ClipExtendPrepare(&extendtraceinfo, trace, tstart, tend, extend);
1840         // ->TraceBox: TraceBrush not needed here, as worldmodel is never rotated
1841         if (model && model->TraceBox)
1842                 model->TraceBox(model, NULL, NULL, trace, extendtraceinfo.extendstart, mins, maxs, extendtraceinfo.extendend, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1843         Collision_ClipExtendFinish(&extendtraceinfo);
1844 }
1845
1846 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 tstart, const vec3_t tend, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, float extend, qboolean hitsurfaces)
1847 {
1848         vec3_t starttransformed, endtransformed;
1849         extendtraceinfo_t extendtraceinfo;
1850         Collision_ClipExtendPrepare(&extendtraceinfo, trace, tstart, tend, extend);
1851
1852         Matrix4x4_Transform(inversematrix, extendtraceinfo.extendstart, starttransformed);
1853         Matrix4x4_Transform(inversematrix, extendtraceinfo.extendend, endtransformed);
1854 #if COLLISIONPARANOID >= 3
1855         Con_Printf("trans(%f %f %f -> %f %f %f, %f %f %f -> %f %f %f)", extendtraceinfo.extendstart[0], extendtraceinfo.extendstart[1], extendtraceinfo.extendstart[2], starttransformed[0], starttransformed[1], starttransformed[2], extendtraceinfo.extendend[0], extendtraceinfo.extendend[1], extendtraceinfo.extendend[2], endtransformed[0], endtransformed[1], endtransformed[2]);
1856 #endif
1857
1858         if (model && model->TraceLineAgainstSurfaces && hitsurfaces)
1859                 model->TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, starttransformed, endtransformed, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1860         else if (model && model->TraceLine)
1861                 model->TraceLine(model, frameblend, skeleton, trace, starttransformed, endtransformed, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1862         else
1863                 Collision_ClipTrace_Box(trace, bodymins, bodymaxs, starttransformed, vec3_origin, vec3_origin, endtransformed, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, bodysupercontents, 0, NULL);
1864
1865         Collision_ClipExtendFinish(&extendtraceinfo);
1866
1867         // transform plane
1868         // NOTE: this relies on plane.dist being directly after plane.normal
1869         Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal_and_dist);
1870 }
1871
1872 void Collision_ClipLineToWorld(trace_t *trace, dp_model_t *model, const vec3_t tstart, const vec3_t tend, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, float extend, qboolean hitsurfaces)
1873 {
1874         extendtraceinfo_t extendtraceinfo;
1875         Collision_ClipExtendPrepare(&extendtraceinfo, trace, tstart, tend, extend);
1876
1877         if (model && model->TraceLineAgainstSurfaces && hitsurfaces)
1878                 model->TraceLineAgainstSurfaces(model, NULL, NULL, trace, extendtraceinfo.extendstart, extendtraceinfo.extendend, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1879         else if (model && model->TraceLine)
1880                 model->TraceLine(model, NULL, NULL, trace, extendtraceinfo.extendstart, extendtraceinfo.extendend, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1881
1882         Collision_ClipExtendFinish(&extendtraceinfo);
1883 }
1884
1885 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, int skipsupercontentsmask, int skipmaterialflagsmask)
1886 {
1887         float starttransformed[3];
1888         memset(trace, 0, sizeof(*trace));
1889         trace->fraction = 1;
1890
1891         Matrix4x4_Transform(inversematrix, start, starttransformed);
1892 #if COLLISIONPARANOID >= 3
1893         Con_Printf("trans(%f %f %f -> %f %f %f)", start[0], start[1], start[2], starttransformed[0], starttransformed[1], starttransformed[2]);
1894 #endif
1895
1896         if (model && model->TracePoint)
1897                 model->TracePoint(model, NULL, NULL, trace, starttransformed, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1898         else
1899                 Collision_ClipTrace_Point(trace, bodymins, bodymaxs, starttransformed, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, bodysupercontents, 0, NULL);
1900
1901         VectorCopy(start, trace->endpos);
1902         // transform plane
1903         // NOTE: this relies on plane.dist being directly after plane.normal
1904         Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal_and_dist);
1905 }
1906
1907 void Collision_ClipPointToWorld(trace_t *trace, dp_model_t *model, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
1908 {
1909         memset(trace, 0, sizeof(*trace));
1910         trace->fraction = 1;
1911         if (model && model->TracePoint)
1912                 model->TracePoint(model, NULL, NULL, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
1913         VectorCopy(start, trace->endpos);
1914 }
1915
1916 void Collision_CombineTraces(trace_t *cliptrace, const trace_t *trace, void *touch, qboolean isbmodel)
1917 {
1918         // take the 'best' answers from the new trace and combine with existing data
1919         if (trace->allsolid)
1920                 cliptrace->allsolid = true;
1921         if (trace->startsolid)
1922         {
1923                 if (isbmodel)
1924                         cliptrace->bmodelstartsolid = true;
1925                 cliptrace->startsolid = true;
1926                 if (cliptrace->fraction == 1)
1927                         cliptrace->ent = touch;
1928                 if (cliptrace->startdepth > trace->startdepth)
1929                 {
1930                         cliptrace->startdepth = trace->startdepth;
1931                         VectorCopy(trace->startdepthnormal, cliptrace->startdepthnormal);
1932                 }
1933         }
1934         // don't set this except on the world, because it can easily confuse
1935         // monsters underwater if there's a bmodel involved in the trace
1936         // (inopen && inwater is how they check water visibility)
1937         //if (trace->inopen)
1938         //      cliptrace->inopen = true;
1939         if (trace->inwater)
1940                 cliptrace->inwater = true;
1941         if ((trace->fraction < cliptrace->fraction) && (VectorLength2(trace->plane.normal) > 0))
1942         {
1943                 cliptrace->fraction = trace->fraction;
1944                 VectorCopy(trace->endpos, cliptrace->endpos);
1945                 cliptrace->plane = trace->plane;
1946                 cliptrace->ent = touch;
1947                 cliptrace->hitsupercontents = trace->hitsupercontents;
1948                 cliptrace->hitq3surfaceflags = trace->hitq3surfaceflags;
1949                 cliptrace->hittexture = trace->hittexture;
1950         }
1951         cliptrace->startsupercontents |= trace->startsupercontents;
1952 }