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