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