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