File: Geometry.cpp

package info (click to toggle)
0ad 0.27.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 173,296 kB
  • sloc: cpp: 194,003; javascript: 19,098; ansic: 15,066; python: 6,328; sh: 1,699; perl: 1,575; java: 533; xml: 482; php: 192; makefile: 99
file content (459 lines) | stat: -rw-r--r-- 16,440 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/* Copyright (C) 2020 Wildfire Games.
 * This file is part of 0 A.D.
 *
 * 0 A.D. is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * 0 A.D. is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "precompiled.h"

#include "Geometry.h"

namespace Geometry
{

// TODO: all of these things could be optimised quite easily

CFixedVector2D GetHalfBoundingBox(const CFixedVector2D& u, const CFixedVector2D& v, const CFixedVector2D& halfSize)
{
	return CFixedVector2D(
		u.X.Multiply(halfSize.X).Absolute() + v.X.Multiply(halfSize.Y).Absolute(),
		u.Y.Multiply(halfSize.X).Absolute() + v.Y.Multiply(halfSize.Y).Absolute()
	);
}

fixed DistanceToSquare(const CFixedVector2D& point, const CFixedVector2D& u, const CFixedVector2D& v, const CFixedVector2D& halfSize, bool countInsideAsZero)
{
	/*
	 * Relative to its own coordinate system, we have a square like:
	 *
	 *  A  :    B    :  C
	 *     :         :
	 * - - ########### - -
	 *     #         #
	 *     # I       #
	 *  D  #    0    #  E     v
	 *     #         #        ^
	 *     #         #        |
	 * - - ########### - -      -->u
	 *     :         :
	 *  F  :    G    :  H
	 *
	 * where 0 is the center, u and v are unit axes,
	 * and the square is hw*2 by hh*2 units in size.
	 *
	 * Points in the BIG regions should check distance to horizontal edges.
	 * Points in the DIE regions should check distance to vertical edges.
	 * Points in the ACFH regions should check distance to the corresponding corner.
	 *
	 * So we just need to check all of the regions to work out which calculations to apply.
	 *
	 */

	// By symmetry (taking absolute values), we work only in the 0-B-C-E quadrant
	// du, dv are the location of the point in the square's coordinate system
	fixed du = point.Dot(u).Absolute();
	fixed dv = point.Dot(v).Absolute();

	fixed hw = halfSize.X;
	fixed hh = halfSize.Y;

	if (du < hw) // regions B, I, G
	{
		if (dv < hh) // region I
			return countInsideAsZero ? fixed::Zero() : std::min(hw - du, hh - dv);
		else
			return dv - hh;
	}
	else if (dv < hh) // regions D, E
	{
		return du - hw; // vertical edges
	}
	else // regions A, C, F, H
	{
		CFixedVector2D distance(du - hw, dv - hh);
		return distance.Length();
	}
}

// Same as above except it does not use Length
// For explanations refer to DistanceToSquare
fixed DistanceToSquareSquared(const CFixedVector2D& point, const CFixedVector2D& u, const CFixedVector2D& v, const CFixedVector2D& halfSize, bool countInsideAsZero)
{
	fixed du = point.Dot(u).Absolute();
	fixed dv = point.Dot(v).Absolute();

	fixed hw = halfSize.X;
	fixed hh = halfSize.Y;

	if (du < hw) // regions B, I, G
	{
		if (dv < hh) // region I
			return countInsideAsZero ? fixed::Zero() : std::min((hw - du).Square(), (hh - dv).Square());
		else
			return (dv - hh).Square(); // horizontal edges
	}
	else if (dv < hh) // regions D, E
	{
		return (du - hw).Square(); // vertical edges
	}
	else // regions A, C, F, H
	{
		return (du - hw).Square() + (dv - hh).Square();
	}
}

CFixedVector2D NearestPointOnSquare(const CFixedVector2D& point, const CFixedVector2D& u, const CFixedVector2D& v, const CFixedVector2D& halfSize)
{
	/*
	 * Relative to its own coordinate system, we have a square like:
	 *
	 *  A  :         :  C
	 *     :         :
	 * - - #### B #### - -
	 *     #\       /#
	 *     # \     / #
	 *     D  --0--  E        v
	 *     # /     \ #        ^
	 *     #/       \#        |
	 * - - #### G #### - -      -->u
	 *     :         :
	 *  F  :         :  H
	 *
	 * where 0 is the center, u and v are unit axes,
	 * and the square is hw*2 by hh*2 units in size.
	 *
	 * Points in the BDEG regions are nearest to the corresponding edge.
	 * Points in the ACFH regions are nearest to the corresponding corner.
	 *
	 * So we just need to check all of the regions to work out which calculations to apply.
	 *
	 */

	// du, dv are the location of the point in the square's coordinate system
	fixed du = point.Dot(u);
	fixed dv = point.Dot(v);

	fixed hw = halfSize.X;
	fixed hh = halfSize.Y;

	if (-hw < du && du < hw) // regions B, G; or regions D, E inside the square
	{
		if (-hh < dv && dv < hh && (du.Absolute() - hw).Absolute() < (dv.Absolute() - hh).Absolute()) // regions D, E
		{
			if (du >= fixed::Zero()) // E
				return u.Multiply(hw) + v.Multiply(dv);
			else // D
				return -u.Multiply(hw) + v.Multiply(dv);
		}
		else // B, G
		{
			if (dv >= fixed::Zero()) // B
				return v.Multiply(hh) + u.Multiply(du);
			else // G
				return -v.Multiply(hh) + u.Multiply(du);
		}
	}
	else if (-hh < dv && dv < hh) // regions D, E outside the square
	{
		if (du >= fixed::Zero()) // E
			return u.Multiply(hw) + v.Multiply(dv);
		else // D
			return -u.Multiply(hw) + v.Multiply(dv);
	}
	else // regions A, C, F, H
	{
		CFixedVector2D corner;
		if (du < fixed::Zero()) // A, F
			corner -= u.Multiply(hw);
		else // C, H
			corner += u.Multiply(hw);
		if (dv < fixed::Zero()) // F, H
			corner -= v.Multiply(hh);
		else // A, C
			corner += v.Multiply(hh);

		return corner;
	}
}

fixed DistanceSquareToSquare(const CFixedVector2D& relativePos, const CFixedVector2D& u1, const CFixedVector2D& v1, const CFixedVector2D& halfSize1, const CFixedVector2D& u2, const CFixedVector2D& v2, const CFixedVector2D& halfSize2)
{
	/*
	 * The shortest distance between two non colliding squares equals the distance between a corner
	 * and other square. Thus calculating all 8 those distances and taking the smallest.
	 * For colliding squares we simply return 0. When one of the points is inside the other square
	 * we depend on DistanceToSquare's countInsideAsZero. When no point is inside the other square,
	 * it is enough to check that two adjacent edges of one square does not collide with the other square.
	 */
	fixed hw1 = halfSize1.X;
	fixed hh1 = halfSize1.Y;
	fixed hw2 = halfSize2.X;
	fixed hh2 = halfSize2.Y;
	if (TestRaySquare(relativePos + u1.Multiply(hw1) + v1.Multiply(hh1), relativePos - u1.Multiply(hw1) + v1.Multiply(hh1), u2, v2, halfSize2) ||
	    TestRaySquare(relativePos + u1.Multiply(hw1) + v1.Multiply(hh1), relativePos + u1.Multiply(hw1) - v1.Multiply(hh1), u2, v2, halfSize2))
		return fixed::Zero();

	return std::min(std::min(std::min(
			DistanceToSquare(relativePos + u1.Multiply(hw1) + v1.Multiply(hh1), u2, v2, halfSize2, true),
			DistanceToSquare(relativePos + u1.Multiply(hw1) - v1.Multiply(hh1), u2, v2, halfSize2, true)),
		std::min(
			DistanceToSquare(relativePos - u1.Multiply(hw1) + v1.Multiply(hh1), u2, v2, halfSize2, true),
			DistanceToSquare(relativePos - u1.Multiply(hw1) - v1.Multiply(hh1), u2, v2, halfSize2, true))),
		std::min(std::min(
			DistanceToSquare(relativePos + u2.Multiply(hw2) + v2.Multiply(hh2), u1, v1, halfSize1, true),
			DistanceToSquare(relativePos + u2.Multiply(hw2) - v2.Multiply(hh2), u1, v1, halfSize1, true)),
		std::min(
			DistanceToSquare(relativePos - u2.Multiply(hw2) + v2.Multiply(hh2), u1, v1, halfSize1, true),
			DistanceToSquare(relativePos - u2.Multiply(hw2) - v2.Multiply(hh2), u1, v1, halfSize1, true))));
}

fixed MaxDistanceToSquare(const CFixedVector2D& point, const CFixedVector2D& u, const CFixedVector2D& v, const CFixedVector2D& halfSize, bool countInsideAsZero)
{
	fixed hw = halfSize.X;
	fixed hh = halfSize.Y;

	if (point.Dot(u).Absolute() < hw && point.Dot(v).Absolute() < hh && countInsideAsZero)
		return fixed::Zero();

	/*
	 * The maximum distance from a point to an edge of a square equals the greatest distance
	 * from the point to the a corner. Thus calculating all and taking the greatest.
	 */
	return std::max(std::max(
			(point + u.Multiply(hw) + v.Multiply(hh)).Length(),
			(point + u.Multiply(hw) - v.Multiply(hh)).Length()),
		std::max(
			(point - u.Multiply(hw) + v.Multiply(hh)).Length(),
			(point - u.Multiply(hw) - v.Multiply(hh)).Length()));
}

fixed MaxDistanceSquareToSquare(const CFixedVector2D& relativePos, const CFixedVector2D& u1, const CFixedVector2D& v1, const CFixedVector2D& halfSize1, const CFixedVector2D& u2, const CFixedVector2D& v2, const CFixedVector2D& halfSize2)
{
	/*
	 * The maximum distance from an edge of a square to the edge of another square
	 * equals the greatest distance from the any of the 16 corner corner distances.
	*/
	fixed hw1 = halfSize1.X;
	fixed hh1 = halfSize1.Y;

	return std::max(std::max(
			MaxDistanceToSquare(relativePos + u1.Multiply(hw1) + v1.Multiply(hh1), u2, v2, halfSize2, true),
			MaxDistanceToSquare(relativePos + u1.Multiply(hw1) - v1.Multiply(hh1), u2, v2, halfSize2, true)),
		std::max(MaxDistanceToSquare(relativePos - u1.Multiply(hw1) + v1.Multiply(hh1), u2, v2, halfSize2, true),
			MaxDistanceToSquare(relativePos - u1.Multiply(hw1) - v1.Multiply(hh1), u2, v2, halfSize2, true)));
}

bool TestRaySquare(const CFixedVector2D& a, const CFixedVector2D& b, const CFixedVector2D& u, const CFixedVector2D& v, const CFixedVector2D& halfSize)
{
	/*
	 * We only consider collisions to be when the ray goes from outside to inside the shape (and possibly out again).
	 * Various cases to consider:
	 *   'a' inside, 'b' inside -> no collision
	 *   'a' inside, 'b' outside -> no collision
	 *   'a' outside, 'b' inside -> collision
	 *   'a' outside, 'b' outside -> depends; use separating axis theorem:
	 *     if the ray's bounding box is outside the square -> no collision
	 *     if the whole square is on the same side of the ray -> no collision
	 *     otherwise -> collision
	 * (Points on the edge are considered 'inside'.)
	 */

	fixed hw = halfSize.X;
	fixed hh = halfSize.Y;

	fixed au = a.Dot(u);
	fixed av = a.Dot(v);

	if (-hw <= au && au <= hw && -hh <= av && av <= hh)
		return false; // a is inside

	fixed bu = b.Dot(u);
	fixed bv = b.Dot(v);

	if (-hw <= bu && bu <= hw && -hh <= bv && bv <= hh) // TODO: isn't this subsumed by the next checks?
		return true; // a is outside, b is inside

	if ((au < -hw && bu < -hw) || (au > hw && bu > hw) || (av < -hh && bv < -hh) || (av > hh && bv > hh))
		return false; // ab is entirely above/below/side the square

	CFixedVector2D abp = (b - a).Perpendicular();
	fixed s0 = abp.Dot((u.Multiply(hw) + v.Multiply(hh)) - a);
	fixed s1 = abp.Dot((u.Multiply(hw) - v.Multiply(hh)) - a);
	fixed s2 = abp.Dot((-u.Multiply(hw) - v.Multiply(hh)) - a);
	fixed s3 = abp.Dot((-u.Multiply(hw) + v.Multiply(hh)) - a);
	if (s0.IsZero() || s1.IsZero() || s2.IsZero() || s3.IsZero())
		return true; // ray intersects the corner

	bool sign = (s0 < fixed::Zero());
	if ((s1 < fixed::Zero()) != sign || (s2 < fixed::Zero()) != sign || (s3 < fixed::Zero()) != sign)
		return true; // ray cuts through the square

	return false;
}

// Exactly like TestRaySquare with u=(1,0), v=(0,1)
bool TestRayAASquare(const CFixedVector2D& a, const CFixedVector2D& b, const CFixedVector2D& halfSize)
{
	fixed hw = halfSize.X;
	fixed hh = halfSize.Y;

	if (-hw <= a.X && a.X <= hw && -hh <= a.Y && a.Y <= hh)
		return false; // a is inside

	if (-hw <= b.X && b.X <= hw && -hh <= b.Y && b.Y <= hh) // TODO: isn't this subsumed by the next checks?
		return true; // a is outside, b is inside

	if ((a.X < -hw && b.X < -hw) || (a.X > hw && b.X > hw) || (a.Y < -hh && b.Y < -hh) || (a.Y > hh && b.Y > hh))
		return false; // ab is entirely above/below/side the square

	CFixedVector2D abp = (b - a).Perpendicular();
	fixed s0 = abp.Dot(CFixedVector2D(hw, hh) - a);
	fixed s1 = abp.Dot(CFixedVector2D(hw, -hh) - a);
	fixed s2 = abp.Dot(CFixedVector2D(-hw, -hh) - a);
	fixed s3 = abp.Dot(CFixedVector2D(-hw, hh) - a);
	if (s0.IsZero() || s1.IsZero() || s2.IsZero() || s3.IsZero())
		return true; // ray intersects the corner

	bool sign = (s0 < fixed::Zero());
	if ((s1 < fixed::Zero()) != sign || (s2 < fixed::Zero()) != sign || (s3 < fixed::Zero()) != sign)
		return true; // ray cuts through the square

	return false;
}

/**
 * Separating axis test; returns true if the square defined by u/v/halfSize at the origin
 * is not entirely on the clockwise side of a line in direction 'axis' passing through 'a'
 */
static bool SquareSAT(const CFixedVector2D& a, const CFixedVector2D& axis, const CFixedVector2D& u, const CFixedVector2D& v, const CFixedVector2D& halfSize)
{
	fixed hw = halfSize.X;
	fixed hh = halfSize.Y;

	CFixedVector2D p = axis.Perpendicular();
	if (p.RelativeOrientation(u.Multiply(hw) + v.Multiply(hh) - a) <= 0)
		return true;
	if (p.RelativeOrientation(u.Multiply(hw) - v.Multiply(hh) - a) <= 0)
		return true;
	if (p.RelativeOrientation(-u.Multiply(hw) - v.Multiply(hh) - a) <= 0)
		return true;
	if (p.RelativeOrientation(-u.Multiply(hw) + v.Multiply(hh) - a) <= 0)
		return true;

	return false;
}

bool TestSquareSquare(
		const CFixedVector2D& c0, const CFixedVector2D& u0, const CFixedVector2D& v0, const CFixedVector2D& halfSize0,
		const CFixedVector2D& c1, const CFixedVector2D& u1, const CFixedVector2D& v1, const CFixedVector2D& halfSize1)
{
	// TODO: need to test this carefully

	CFixedVector2D corner0a = c0 + u0.Multiply(halfSize0.X) + v0.Multiply(halfSize0.Y);
	CFixedVector2D corner0b = c0 - u0.Multiply(halfSize0.X) - v0.Multiply(halfSize0.Y);
	CFixedVector2D corner1a = c1 + u1.Multiply(halfSize1.X) + v1.Multiply(halfSize1.Y);
	CFixedVector2D corner1b = c1 - u1.Multiply(halfSize1.X) - v1.Multiply(halfSize1.Y);

	// Do a SAT test for each square vs each edge of the other square
	if (!SquareSAT(corner0a - c1, -u0, u1, v1, halfSize1))
		return false;
	if (!SquareSAT(corner0a - c1, v0, u1, v1, halfSize1))
		return false;
	if (!SquareSAT(corner0b - c1, u0, u1, v1, halfSize1))
		return false;
	if (!SquareSAT(corner0b - c1, -v0, u1, v1, halfSize1))
		return false;
	if (!SquareSAT(corner1a - c0, -u1, u0, v0, halfSize0))
		return false;
	if (!SquareSAT(corner1a - c0, v1, u0, v0, halfSize0))
		return false;
	if (!SquareSAT(corner1b - c0, u1, u0, v0, halfSize0))
		return false;
	if (!SquareSAT(corner1b - c0, -v1, u0, v0, halfSize0))
		return false;

	return true;
}

int GetPerimeterDistance(int x_max, int y_max, int x, int y)
{
	if (x_max <= 0 || y_max <= 0)
		return 0;

	int quarter = x_max + y_max;
	if (x == x_max && y >= 0)
		return y;
	if (y == y_max)
		return quarter - x;
	if (x == -x_max)
		return 2 * quarter - y;
	if (y == -y_max)
		return 3 * quarter + x;
	if (x == x_max)
		return 4 * quarter + y;
	return 0;
}

std::pair<int, int> GetPerimeterCoordinates(int x_max, int y_max, int k)
{
	if (x_max <= 0 || y_max <= 0)
		return std::pair<int, int>(0, 0);

	int quarter = x_max + y_max;
	k %= 4 * quarter;
	if (k < 0)
		k += 4 * quarter;

	if (k < y_max)
		return std::pair<int, int>(x_max, k);
	if (k < quarter + x_max)
		return std::pair<int, int>(quarter - k, y_max);
	if (k < 2 * quarter + y_max)
		return std::pair<int, int>(-x_max, 2 * quarter - k);
	if (k < 3 * quarter + x_max)
		return std::pair<int, int>(k - 3 * quarter, -y_max);
	return std::pair<int, int>(x_max, k - 4 * quarter);
}

fixed DistanceToSegment(
	const CFixedVector2D& point, const CFixedVector2D& a, const CFixedVector2D& b)
{
	// First we need to figure out from which part of the segment we should
	// calculate distance.
	// We split 2D space in three spaces:
	//               |                                |
	//             1 |                2               | 3
	//               A--------------------------------B
	// Here we need  | Between A and B we need to     | Here we need
	// distance to A | calculate distance to the line | distance to B
	//
	const CFixedVector2D dir = b - a;
	// We project the point, point A, and point B upon the direction of the
	// segment to figure out in which space the point is.
	const fixed pointDot = dir.Dot(point);
	const fixed aDot = dir.Dot(a);
	// The point is lying in space #1.
	if (pointDot <= aDot)
		return (point - a).Length();
	const fixed bDot = dir.Dot(b);
	// The point is lying in space #3.
	if (pointDot >= bDot)
		return (point - b).Length();
	// The point is lying in space #2.
	CFixedVector2D normal = dir.Perpendicular();
	normal.Normalize();
	return (normal.Dot(a) - normal.Dot(point)).Absolute();
}

} // namespace Geometry