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