summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorsmatz <smatz@openttd.org>2009-06-23 23:31:43 +0000
committersmatz <smatz@openttd.org>2009-06-23 23:31:43 +0000
commit986cc75a126f55c76d546a263ca55153178643eb (patch)
tree5227789355c0b6dedb43f080803b0a90fc2eceaf
parent0045096403ed050cf972aef6d146535bbb88f713 (diff)
downloadopenttd-986cc75a126f55c76d546a263ca55153178643eb.tar.xz
(svn r16641) -Codechange: reduce number of multiplications done in FindTrainCollideEnum() to minimum
-rw-r--r--src/train_cmd.cpp8
1 files changed, 6 insertions, 2 deletions
diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp
index 7462e91ef..6942fb9d0 100644
--- a/src/train_cmd.cpp
+++ b/src/train_cmd.cpp
@@ -3561,8 +3561,12 @@ static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
int x_diff = v->x_pos - tcc->v->x_pos;
int y_diff = v->y_pos - tcc->v->y_pos;
- /* needed to disable possible crash of competitor train in station by building diagonal track at its end */
- if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
+ /* Needed to disable possible crash of competitor train in station by building diagonal track at its end.
+ * The second check is false when (abs(first), abs(second)) is: a) 5, 0 b) 4, <=3 c) 3, <=4, d) 2-, <=5
+ * Sum of these two is at most 2 + 5 == 4 + 3 == 7. So we can just test if sum of abs() is > 7 to prevent
+ * multiplying. Simply, when sum of abs() is >= 8, the sum of squares can't be <= 25.
+ * Even gcc3.4 seems to do abs() branchless (using arithmetics or conditional moves). */
+ if (abs(x_diff) + abs(y_diff) > 7 || x_diff * x_diff + y_diff * y_diff > 25) return NULL;
/* crash both trains */
tcc->num += TrainCrashed(Train::From(tcc->v));