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