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