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