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