3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "collision.h"
27 #include "client/clientenvironment.h"
28 #include "client/localplayer.h"
30 #include "serverenvironment.h"
31 #include "server/serveractiveobject.h"
32 #include "util/timetaker.h"
36 #warning "-ffast-math is known to cause bugs in collision code, do not use!"
39 struct NearbyCollisionInfo {
41 NearbyCollisionInfo(bool is_ul, int bouncy, const v3s16 &pos,
51 NearbyCollisionInfo(ActiveObject *obj, int bouncy,
59 inline bool isObject() const { return obj != nullptr; }
62 bool is_step_up = false;
70 // Truncate floating point numbers to specified number of decimal places
71 // in order to move all the floating point error to one side of the correct value
72 static inline f32 truncate(const f32 val, const f32 factor)
74 return truncf(val * factor) / factor;
77 static inline v3f truncate(const v3f& vec, const f32 factor)
80 truncate(vec.X, factor),
81 truncate(vec.Y, factor),
82 truncate(vec.Z, factor)
87 // Checks for collision of a moving aabbox with a static aabbox
88 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
89 // The time after which the collision occurs is stored in dtime.
90 CollisionAxis axisAlignedCollision(
91 const aabb3f &staticbox, const aabb3f &movingbox,
92 const v3f &speed, f32 *dtime)
94 //TimeTaker tt("axisAlignedCollision");
97 (movingbox.MaxEdge.X - movingbox.MinEdge.X) + (staticbox.MaxEdge.X - staticbox.MinEdge.X), // sum of the widths
98 (movingbox.MaxEdge.Y - movingbox.MinEdge.Y) + (staticbox.MaxEdge.Y - staticbox.MinEdge.Y),
99 (movingbox.MaxEdge.Z - movingbox.MinEdge.Z) + (staticbox.MaxEdge.Z - staticbox.MinEdge.Z),
100 std::max(movingbox.MaxEdge.X, staticbox.MaxEdge.X) - std::min(movingbox.MinEdge.X, staticbox.MinEdge.X), //outer bounding 'box' dimensions
101 std::max(movingbox.MaxEdge.Y, staticbox.MaxEdge.Y) - std::min(movingbox.MinEdge.Y, staticbox.MinEdge.Y),
102 std::max(movingbox.MaxEdge.Z, staticbox.MaxEdge.Z) - std::min(movingbox.MinEdge.Z, staticbox.MinEdge.Z)
105 const f32 dtime_max = *dtime;
106 f32 inner_margin; // the distance of clipping recovery
112 distance = relbox.MaxEdge.Y - relbox.MinEdge.Y;
113 *dtime = distance / std::abs(speed.Y);
114 time = std::max(*dtime, 0.0f);
116 if (*dtime <= dtime_max) {
117 inner_margin = std::max(-0.5f * (staticbox.MaxEdge.Y - staticbox.MinEdge.Y), -2.0f);
119 if ((speed.Y > 0 && staticbox.MinEdge.Y - movingbox.MaxEdge.Y > inner_margin) ||
120 (speed.Y < 0 && movingbox.MinEdge.Y - staticbox.MaxEdge.Y > inner_margin)) {
122 (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X)
123 - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X)
124 - relbox.MinEdge.X < 0) &&
125 (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z)
126 - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z)
127 - relbox.MinEdge.Z < 0)
129 return COLLISION_AXIS_Y;
133 return COLLISION_AXIS_NONE;
140 distance = relbox.MaxEdge.X - relbox.MinEdge.X;
141 *dtime = distance / std::abs(speed.X);
142 time = std::max(*dtime, 0.0f);
144 if (*dtime <= dtime_max) {
145 inner_margin = std::max(-0.5f * (staticbox.MaxEdge.X - staticbox.MinEdge.X), -2.0f);
147 if ((speed.X > 0 && staticbox.MinEdge.X - movingbox.MaxEdge.X > inner_margin) ||
148 (speed.X < 0 && movingbox.MinEdge.X - staticbox.MaxEdge.X > inner_margin)) {
150 (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y)
151 - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y)
152 - relbox.MinEdge.Y < 0) &&
153 (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z)
154 - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z)
155 - relbox.MinEdge.Z < 0)
157 return COLLISION_AXIS_X;
160 return COLLISION_AXIS_NONE;
167 distance = relbox.MaxEdge.Z - relbox.MinEdge.Z;
168 *dtime = distance / std::abs(speed.Z);
169 time = std::max(*dtime, 0.0f);
171 if (*dtime <= dtime_max) {
172 inner_margin = std::max(-0.5f * (staticbox.MaxEdge.Z - staticbox.MinEdge.Z), -2.0f);
174 if ((speed.Z > 0 && staticbox.MinEdge.Z - movingbox.MaxEdge.Z > inner_margin) ||
175 (speed.Z < 0 && movingbox.MinEdge.Z - staticbox.MaxEdge.Z > inner_margin)) {
177 (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X)
178 - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X)
179 - relbox.MinEdge.X < 0) &&
180 (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y)
181 - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y)
182 - relbox.MinEdge.Y < 0)
184 return COLLISION_AXIS_Z;
189 return COLLISION_AXIS_NONE;
193 // Checks if moving the movingbox up by the given distance would hit a ceiling.
194 bool wouldCollideWithCeiling(
195 const std::vector<NearbyCollisionInfo> &cinfo,
196 const aabb3f &movingbox,
197 f32 y_increase, f32 d)
199 //TimeTaker tt("wouldCollideWithCeiling");
201 assert(y_increase >= 0); // pre-condition
203 for (const auto &it : cinfo) {
204 const aabb3f &staticbox = it.box;
205 if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
206 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
207 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
208 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
209 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
210 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
217 static inline void getNeighborConnectingFace(const v3s16 &p,
218 const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors)
220 MapNode n2 = map->getNode(p);
221 if (nodedef->nodeboxConnects(n, n2, v))
225 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
226 f32 pos_max_d, const aabb3f &box_0,
227 f32 stepheight, f32 dtime,
228 v3f *pos_f, v3f *speed_f,
229 v3f accel_f, ActiveObject *self,
230 bool collideWithObjects)
232 static bool time_notification_done = false;
233 Map *map = &env->getMap();
235 ScopeProfiler sp(g_profiler, "collisionMoveSimple()", SPT_AVG);
237 collisionMoveResult result;
240 Calculate new velocity
243 if (!time_notification_done) {
244 time_notification_done = true;
245 infostream << "collisionMoveSimple: maximum step interval exceeded,"
246 " lost movement details!"<<std::endl;
250 time_notification_done = false;
253 v3f dpos_f = (*speed_f + accel_f * 0.5f * dtime) * dtime;
254 v3f newpos_f = *pos_f + dpos_f;
255 *speed_f += accel_f * dtime;
257 // If the object is static, there are no collisions
261 // Limit speed for avoiding hangs
262 speed_f->Y = rangelim(speed_f->Y, -5000, 5000);
263 speed_f->X = rangelim(speed_f->X, -5000, 5000);
264 speed_f->Z = rangelim(speed_f->Z, -5000, 5000);
266 *speed_f = truncate(*speed_f, 10000.0f);
269 Collect node boxes in movement range
271 std::vector<NearbyCollisionInfo> cinfo;
273 //TimeTaker tt2("collisionMoveSimple collect boxes");
274 ScopeProfiler sp2(g_profiler, "collisionMoveSimple(): collect boxes", SPT_AVG);
277 MYMIN(pos_f->X, newpos_f.X),
278 MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5
279 MYMIN(pos_f->Z, newpos_f.Z)
282 MYMAX(pos_f->X, newpos_f.X),
283 MYMAX(pos_f->Y, newpos_f.Y),
284 MYMAX(pos_f->Z, newpos_f.Z)
286 v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1);
287 v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1);
289 bool any_position_valid = false;
292 for (p.X = min.X; p.X <= max.X; p.X++)
293 for (p.Y = min.Y; p.Y <= max.Y; p.Y++)
294 for (p.Z = min.Z; p.Z <= max.Z; p.Z++) {
295 bool is_position_valid;
296 MapNode n = map->getNode(p, &is_position_valid);
298 if (is_position_valid && n.getContent() != CONTENT_IGNORE) {
299 // Object collides into walkable nodes
301 any_position_valid = true;
302 const NodeDefManager *nodedef = gamedef->getNodeDefManager();
303 const ContentFeatures &f = nodedef->get(n);
308 // Negative bouncy may have a meaning, but we need +value here.
309 int n_bouncy_value = abs(itemgroup_get(f.groups, "bouncy"));
312 if (f.drawtype == NDT_NODEBOX &&
313 f.node_box.type == NODEBOX_CONNECTED) {
317 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
321 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
325 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
329 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
333 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
337 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
339 std::vector<aabb3f> nodeboxes;
340 n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
342 // Calculate float position only once
343 v3f posf = intToFloat(p, BS);
344 for (auto box : nodeboxes) {
347 cinfo.emplace_back(false, n_bouncy_value, p, box);
350 // Collide with unloaded nodes (position invalid) and loaded
351 // CONTENT_IGNORE nodes (position valid)
352 aabb3f box = getNodeBox(p, BS);
353 cinfo.emplace_back(true, 0, p, box);
357 // Do not move if world has not loaded yet, since custom node boxes
358 // are not available for collision detection.
359 // This also intentionally occurs in the case of the object being positioned
360 // solely on loaded CONTENT_IGNORE nodes, no matter where they come from.
361 if (!any_position_valid) {
362 *speed_f = v3f(0, 0, 0);
368 if(collideWithObjects)
370 /* add object boxes to cinfo */
372 std::vector<ActiveObject*> objects;
374 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
376 // Calculate distance by speed, add own extent and 1.5m of tolerance
377 f32 distance = speed_f->getLength() * dtime +
378 box_0.getExtent().getLength() + 1.5f * BS;
379 std::vector<DistanceSortedActiveObject> clientobjects;
380 c_env->getActiveObjects(*pos_f, distance, clientobjects);
382 for (auto &clientobject : clientobjects) {
383 // Do collide with everything but itself and the parent CAO
384 if (!self || (self != clientobject.obj &&
385 self != clientobject.obj->getParent())) {
386 objects.push_back((ActiveObject*) clientobject.obj);
393 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
395 // Calculate distance by speed, add own extent and 1.5m of tolerance
396 f32 distance = speed_f->getLength() * dtime +
397 box_0.getExtent().getLength() + 1.5f * BS;
399 // search for objects which are not us, or we are not its parent
400 // we directly use the callback to populate the result to prevent
401 // a useless result loop here
402 auto include_obj_cb = [self, &objects] (ServerActiveObject *obj) {
403 if (!obj->isGone() &&
404 (!self || (self != obj && self != obj->getParent()))) {
405 objects.push_back((ActiveObject *)obj);
410 std::vector<ServerActiveObject *> s_objects;
411 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance, include_obj_cb);
415 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
416 iter != objects.end(); ++iter) {
417 ActiveObject *object = *iter;
419 if (object && object->collideWithObjects()) {
420 aabb3f object_collisionbox;
421 if (object->getCollisionBox(&object_collisionbox))
422 cinfo.emplace_back(object, 0, object_collisionbox);
427 LocalPlayer *lplayer = c_env->getLocalPlayer();
428 if (lplayer->getParent() == nullptr) {
429 aabb3f lplayer_collisionbox = lplayer->getCollisionbox();
430 v3f lplayer_pos = lplayer->getPosition();
431 lplayer_collisionbox.MinEdge += lplayer_pos;
432 lplayer_collisionbox.MaxEdge += lplayer_pos;
433 ActiveObject *obj = (ActiveObject*) lplayer->getCAO();
434 cinfo.emplace_back(obj, 0, lplayer_collisionbox);
448 while(dtime > BS * 1e-10f) {
449 // Avoid infinite loop
451 if (loopcount >= 100) {
452 warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
456 aabb3f movingbox = box_0;
457 movingbox.MinEdge += *pos_f;
458 movingbox.MaxEdge += *pos_f;
460 CollisionAxis nearest_collided = COLLISION_AXIS_NONE;
461 f32 nearest_dtime = dtime;
462 int nearest_boxindex = -1;
465 Go through every nodebox, find nearest collision
467 for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
468 const NearbyCollisionInfo &box_info = cinfo[boxindex];
469 // Ignore if already stepped up this nodebox.
470 if (box_info.is_step_up)
473 // Find nearest collision of the two boxes (raytracing-like)
474 f32 dtime_tmp = nearest_dtime;
475 CollisionAxis collided = axisAlignedCollision(box_info.box,
476 movingbox, *speed_f, &dtime_tmp);
478 if (collided == -1 || dtime_tmp >= nearest_dtime)
481 nearest_dtime = dtime_tmp;
482 nearest_collided = collided;
483 nearest_boxindex = boxindex;
486 if (nearest_collided == COLLISION_AXIS_NONE) {
487 // No collision with any collision box.
488 *pos_f += truncate(*speed_f * dtime, 100.0f);
489 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
491 // Otherwise, a collision occurred.
492 NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
493 const aabb3f& cbox = nearest_info.box;
495 //movingbox except moved to the horizontal position it would be after step up
496 aabb3f stepbox = movingbox;
497 stepbox.MinEdge.X += speed_f->X * dtime;
498 stepbox.MinEdge.Z += speed_f->Z * dtime;
499 stepbox.MaxEdge.X += speed_f->X * dtime;
500 stepbox.MaxEdge.Z += speed_f->Z * dtime;
502 bool step_up = (nearest_collided != COLLISION_AXIS_Y) && // must not be Y direction
503 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
504 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
505 (!wouldCollideWithCeiling(cinfo, stepbox,
506 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
509 // Get bounce multiplier
510 float bounce = -(float)nearest_info.bouncy / 100.0f;
512 // Move to the point of collision and reduce dtime by nearest_dtime
513 if (nearest_dtime < 0) {
514 // Handle negative nearest_dtime
516 if (nearest_collided == COLLISION_AXIS_X)
517 pos_f->X += speed_f->X * nearest_dtime;
518 if (nearest_collided == COLLISION_AXIS_Y)
519 pos_f->Y += speed_f->Y * nearest_dtime;
520 if (nearest_collided == COLLISION_AXIS_Z)
521 pos_f->Z += speed_f->Z * nearest_dtime;
524 *pos_f += truncate(*speed_f * nearest_dtime, 100.0f);
525 dtime -= nearest_dtime;
528 bool is_collision = true;
529 if (nearest_info.is_unloaded)
530 is_collision = false;
533 if (nearest_info.isObject())
534 info.type = COLLISION_OBJECT;
536 info.type = COLLISION_NODE;
538 info.node_p = nearest_info.position;
539 info.object = nearest_info.obj;
540 info.old_speed = *speed_f;
541 info.plane = nearest_collided;
543 // Set the speed component that caused the collision to zero
545 // Special case: Handle stairs
546 nearest_info.is_step_up = true;
547 is_collision = false;
548 } else if (nearest_collided == COLLISION_AXIS_X) {
549 if (fabs(speed_f->X) > BS * 3)
550 speed_f->X *= bounce;
553 result.collides = true;
554 } else if (nearest_collided == COLLISION_AXIS_Y) {
555 if(fabs(speed_f->Y) > BS * 3)
556 speed_f->Y *= bounce;
559 result.collides = true;
560 } else if (nearest_collided == COLLISION_AXIS_Z) {
561 if (fabs(speed_f->Z) > BS * 3)
562 speed_f->Z *= bounce;
565 result.collides = true;
568 info.new_speed = *speed_f;
569 if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1f * BS)
570 is_collision = false;
573 info.axis = nearest_collided;
574 result.collisions.push_back(info);
580 Final touches: Check if standing on ground, step up stairs.
583 box.MinEdge += *pos_f;
584 box.MaxEdge += *pos_f;
585 for (const auto &box_info : cinfo) {
586 const aabb3f &cbox = box_info.box;
589 See if the object is touching ground.
591 Object touches ground if object's minimum Y is near node's
592 maximum Y and object's X-Z-area overlaps with the node's
596 if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
597 cbox.MaxEdge.Z - d > box.MinEdge.Z &&
598 cbox.MinEdge.Z + d < box.MaxEdge.Z) {
599 if (box_info.is_step_up) {
600 pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y;
602 box.MinEdge += *pos_f;
603 box.MaxEdge += *pos_f;
605 if (std::fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.05f) {
606 result.touching_ground = true;
608 if (box_info.isObject())
609 result.standing_on_object = true;