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;
71 // Checks for collision of a moving aabbox with a static aabbox
72 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
73 // The time after which the collision occurs is stored in dtime.
74 CollisionAxis axisAlignedCollision(
75 const aabb3f &staticbox, const aabb3f &movingbox,
76 const v3f &speed, f32 *dtime)
78 //TimeTaker tt("axisAlignedCollision");
81 movingbox.MaxEdge.X - movingbox.MinEdge.X + staticbox.MaxEdge.X - staticbox.MinEdge.X, // sum of the widths
82 movingbox.MaxEdge.Y - movingbox.MinEdge.Y + staticbox.MaxEdge.Y - staticbox.MinEdge.Y,
83 movingbox.MaxEdge.Z - movingbox.MinEdge.Z + staticbox.MaxEdge.Z - staticbox.MinEdge.Z,
84 std::max(movingbox.MaxEdge.X, staticbox.MaxEdge.X) - std::min(movingbox.MinEdge.X, staticbox.MinEdge.X), //outer bounding 'box' dimensions
85 std::max(movingbox.MaxEdge.Y, staticbox.MaxEdge.Y) - std::min(movingbox.MinEdge.Y, staticbox.MinEdge.Y),
86 std::max(movingbox.MaxEdge.Z, staticbox.MaxEdge.Z) - std::min(movingbox.MinEdge.Z, staticbox.MinEdge.Z)
89 const f32 dtime_max = *dtime;
90 const f32 inner_margin = -1.5f;
95 distance = relbox.MaxEdge.X - relbox.MinEdge.X;
97 *dtime = distance >= 0 ? std::abs(distance / speed.X) : -std::abs(distance / speed.X);
98 time = std::max(*dtime, 0.0f);
100 if (distance > inner_margin) {
101 if (*dtime <= dtime_max) {
102 if ((speed.X > 0 && staticbox.MaxEdge.X > movingbox.MaxEdge.X) ||
103 (speed.X < 0 && staticbox.MinEdge.X < movingbox.MinEdge.X)) {
105 (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y)
106 - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y)
107 - relbox.MinEdge.Y < 0) &&
108 (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z)
109 - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z)
110 - relbox.MinEdge.Z < 0)
112 return COLLISION_AXIS_X;
115 return COLLISION_AXIS_NONE;
123 distance = relbox.MaxEdge.Y - relbox.MinEdge.Y;
125 *dtime = distance >= 0 ? std::abs(distance / speed.Y) : -std::abs(distance / speed.Y);
126 time = std::max(*dtime, 0.0f);
128 if (distance > inner_margin) {
129 if (*dtime <= dtime_max) {
130 if ((speed.Y > 0 && staticbox.MaxEdge.Y > movingbox.MaxEdge.Y) ||
131 (speed.Y < 0 && staticbox.MinEdge.Y < movingbox.MinEdge.Y)) {
133 (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X)
134 - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X)
135 - relbox.MinEdge.X < 0) &&
136 (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z)
137 - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z)
138 - relbox.MinEdge.Z < 0)
140 return COLLISION_AXIS_Y;
143 return COLLISION_AXIS_NONE;
151 distance = relbox.MaxEdge.Z - relbox.MinEdge.Z;
153 *dtime = distance >= 0 ? std::abs(distance / speed.Z) : -std::abs(distance / speed.Z);
154 time = std::max(*dtime, 0.0f);
156 if (distance > inner_margin) {
157 if (*dtime <= dtime_max) {
158 if ((speed.Z > 0 && staticbox.MaxEdge.Z > movingbox.MaxEdge.Z) ||
159 (speed.Z < 0 && staticbox.MinEdge.Z < movingbox.MinEdge.Z)) {
161 (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X)
162 - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X)
163 - relbox.MinEdge.X < 0) &&
164 (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y)
165 - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y)
166 - relbox.MinEdge.Y < 0)
168 return COLLISION_AXIS_Z;
174 return COLLISION_AXIS_NONE;
178 // Checks if moving the movingbox up by the given distance would hit a ceiling.
179 bool wouldCollideWithCeiling(
180 const std::vector<NearbyCollisionInfo> &cinfo,
181 const aabb3f &movingbox,
182 f32 y_increase, f32 d)
184 //TimeTaker tt("wouldCollideWithCeiling");
186 assert(y_increase >= 0); // pre-condition
188 for (const auto &it : cinfo) {
189 const aabb3f &staticbox = it.box;
190 if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
191 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
192 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
193 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
194 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
195 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
202 static inline void getNeighborConnectingFace(const v3s16 &p,
203 const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors)
205 MapNode n2 = map->getNode(p);
206 if (nodedef->nodeboxConnects(n, n2, v))
210 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
211 f32 pos_max_d, const aabb3f &box_0,
212 f32 stepheight, f32 dtime,
213 v3f *pos_f, v3f *speed_f,
214 v3f accel_f, ActiveObject *self,
215 bool collideWithObjects)
217 static bool time_notification_done = false;
218 Map *map = &env->getMap();
220 ScopeProfiler sp(g_profiler, "collisionMoveSimple()", SPT_AVG);
222 collisionMoveResult result;
225 Calculate new velocity
228 if (!time_notification_done) {
229 time_notification_done = true;
230 infostream << "collisionMoveSimple: maximum step interval exceeded,"
231 " lost movement details!"<<std::endl;
235 time_notification_done = false;
237 *speed_f += accel_f * dtime;
239 // If there is no speed, there are no collisions
240 if (speed_f->getLength() == 0)
243 // Limit speed for avoiding hangs
244 speed_f->Y = rangelim(speed_f->Y, -5000, 5000);
245 speed_f->X = rangelim(speed_f->X, -5000, 5000);
246 speed_f->Z = rangelim(speed_f->Z, -5000, 5000);
249 Collect node boxes in movement range
251 std::vector<NearbyCollisionInfo> cinfo;
253 //TimeTaker tt2("collisionMoveSimple collect boxes");
254 ScopeProfiler sp2(g_profiler, "collisionMoveSimple(): collect boxes", SPT_AVG);
256 v3f newpos_f = *pos_f + *speed_f * dtime;
258 MYMIN(pos_f->X, newpos_f.X),
259 MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5
260 MYMIN(pos_f->Z, newpos_f.Z)
263 MYMAX(pos_f->X, newpos_f.X),
264 MYMAX(pos_f->Y, newpos_f.Y),
265 MYMAX(pos_f->Z, newpos_f.Z)
267 v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1);
268 v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1);
270 bool any_position_valid = false;
273 for (p.X = min.X; p.X <= max.X; p.X++)
274 for (p.Y = min.Y; p.Y <= max.Y; p.Y++)
275 for (p.Z = min.Z; p.Z <= max.Z; p.Z++) {
276 bool is_position_valid;
277 MapNode n = map->getNode(p, &is_position_valid);
279 if (is_position_valid && n.getContent() != CONTENT_IGNORE) {
280 // Object collides into walkable nodes
282 any_position_valid = true;
283 const NodeDefManager *nodedef = gamedef->getNodeDefManager();
284 const ContentFeatures &f = nodedef->get(n);
289 int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
292 if (f.drawtype == NDT_NODEBOX &&
293 f.node_box.type == NODEBOX_CONNECTED) {
297 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
301 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
305 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
309 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
313 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
317 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
319 std::vector<aabb3f> nodeboxes;
320 n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
322 // Calculate float position only once
323 v3f posf = intToFloat(p, BS);
324 for (auto box : nodeboxes) {
327 cinfo.emplace_back(false, n_bouncy_value, p, box);
330 // Collide with unloaded nodes (position invalid) and loaded
331 // CONTENT_IGNORE nodes (position valid)
332 aabb3f box = getNodeBox(p, BS);
333 cinfo.emplace_back(true, 0, p, box);
337 // Do not move if world has not loaded yet, since custom node boxes
338 // are not available for collision detection.
339 // This also intentionally occurs in the case of the object being positioned
340 // solely on loaded CONTENT_IGNORE nodes, no matter where they come from.
341 if (!any_position_valid) {
342 *speed_f = v3f(0, 0, 0);
348 if(collideWithObjects)
350 /* add object boxes to cinfo */
352 std::vector<ActiveObject*> objects;
354 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
356 // Calculate distance by speed, add own extent and 1.5m of tolerance
357 f32 distance = speed_f->getLength() * dtime +
358 box_0.getExtent().getLength() + 1.5f * BS;
359 std::vector<DistanceSortedActiveObject> clientobjects;
360 c_env->getActiveObjects(*pos_f, distance, clientobjects);
362 for (auto &clientobject : clientobjects) {
363 // Do collide with everything but itself and the parent CAO
364 if (!self || (self != clientobject.obj &&
365 self != clientobject.obj->getParent())) {
366 objects.push_back((ActiveObject*) clientobject.obj);
373 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
375 // Calculate distance by speed, add own extent and 1.5m of tolerance
376 f32 distance = speed_f->getLength() * dtime +
377 box_0.getExtent().getLength() + 1.5f * BS;
379 // search for objects which are not us, or we are not its parent
380 // we directly use the callback to populate the result to prevent
381 // a useless result loop here
382 auto include_obj_cb = [self, &objects] (ServerActiveObject *obj) {
383 if (!self || (self != obj && self != obj->getParent())) {
384 objects.push_back((ActiveObject *)obj);
389 std::vector<ServerActiveObject *> s_objects;
390 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance, include_obj_cb);
394 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
395 iter != objects.end(); ++iter) {
396 ActiveObject *object = *iter;
398 if (object && object->collideWithObjects()) {
399 aabb3f object_collisionbox;
400 if (object->getCollisionBox(&object_collisionbox))
401 cinfo.emplace_back(object, 0, object_collisionbox);
406 LocalPlayer *lplayer = c_env->getLocalPlayer();
407 if (lplayer->getParent() == nullptr) {
408 aabb3f lplayer_collisionbox = lplayer->getCollisionbox();
409 v3f lplayer_pos = lplayer->getPosition();
410 lplayer_collisionbox.MinEdge += lplayer_pos;
411 lplayer_collisionbox.MaxEdge += lplayer_pos;
412 ActiveObject *obj = (ActiveObject*) lplayer->getCAO();
413 cinfo.emplace_back(obj, 0, lplayer_collisionbox);
427 while(dtime > BS * 1e-10f) {
428 // Avoid infinite loop
430 if (loopcount >= 100) {
431 warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
435 aabb3f movingbox = box_0;
436 movingbox.MinEdge += *pos_f;
437 movingbox.MaxEdge += *pos_f;
439 CollisionAxis nearest_collided = COLLISION_AXIS_NONE;
440 f32 nearest_dtime = dtime;
441 int nearest_boxindex = -1;
444 Go through every nodebox, find nearest collision
446 for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
447 const NearbyCollisionInfo &box_info = cinfo[boxindex];
448 // Ignore if already stepped up this nodebox.
449 if (box_info.is_step_up)
452 // Find nearest collision of the two boxes (raytracing-like)
453 f32 dtime_tmp = nearest_dtime;
454 CollisionAxis collided = axisAlignedCollision(box_info.box,
455 movingbox, *speed_f, &dtime_tmp);
457 if (collided == -1 || dtime_tmp >= nearest_dtime)
460 nearest_dtime = dtime_tmp;
461 nearest_collided = collided;
462 nearest_boxindex = boxindex;
465 if (nearest_collided == COLLISION_AXIS_NONE) {
466 // No collision with any collision box.
467 *pos_f += *speed_f * dtime;
468 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
470 // Otherwise, a collision occurred.
471 NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
472 const aabb3f& cbox = nearest_info.box;
474 //movingbox except moved to the horizontal position it would be after step up
475 aabb3f stepbox = movingbox;
476 stepbox.MinEdge.X += speed_f->X * dtime;
477 stepbox.MinEdge.Z += speed_f->Z * dtime;
478 stepbox.MaxEdge.X += speed_f->X * dtime;
479 stepbox.MaxEdge.Z += speed_f->Z * dtime;
481 bool step_up = (nearest_collided != COLLISION_AXIS_Y) && // must not be Y direction
482 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
483 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
484 (!wouldCollideWithCeiling(cinfo, stepbox,
485 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
488 // Get bounce multiplier
489 float bounce = -(float)nearest_info.bouncy / 100.0f;
491 // Move to the point of collision and reduce dtime by nearest_dtime
492 if (nearest_dtime < 0) {
493 // Handle negative nearest_dtime
495 if (nearest_collided == COLLISION_AXIS_X)
496 pos_f->X += speed_f->X * nearest_dtime;
497 if (nearest_collided == COLLISION_AXIS_Y)
498 pos_f->Y += speed_f->Y * nearest_dtime;
499 if (nearest_collided == COLLISION_AXIS_Z)
500 pos_f->Z += speed_f->Z * nearest_dtime;
503 *pos_f += *speed_f * nearest_dtime;
504 dtime -= nearest_dtime;
507 bool is_collision = true;
508 if (nearest_info.is_unloaded)
509 is_collision = false;
512 if (nearest_info.isObject())
513 info.type = COLLISION_OBJECT;
515 info.type = COLLISION_NODE;
517 info.node_p = nearest_info.position;
518 info.object = nearest_info.obj;
519 info.old_speed = *speed_f;
520 info.plane = nearest_collided;
522 // Set the speed component that caused the collision to zero
524 // Special case: Handle stairs
525 nearest_info.is_step_up = true;
526 is_collision = false;
527 } else if (nearest_collided == COLLISION_AXIS_X) {
528 if (fabs(speed_f->X) > BS * 3)
529 speed_f->X *= bounce;
532 result.collides = true;
533 } else if (nearest_collided == COLLISION_AXIS_Y) {
534 if(fabs(speed_f->Y) > BS * 3)
535 speed_f->Y *= bounce;
538 result.collides = true;
539 } else if (nearest_collided == COLLISION_AXIS_Z) {
540 if (fabs(speed_f->Z) > BS * 3)
541 speed_f->Z *= bounce;
544 result.collides = true;
547 info.new_speed = *speed_f;
548 if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1f * BS)
549 is_collision = false;
552 info.axis = nearest_collided;
553 result.collisions.push_back(info);
559 Final touches: Check if standing on ground, step up stairs.
562 box.MinEdge += *pos_f;
563 box.MaxEdge += *pos_f;
564 for (const auto &box_info : cinfo) {
565 const aabb3f &cbox = box_info.box;
568 See if the object is touching ground.
570 Object touches ground if object's minimum Y is near node's
571 maximum Y and object's X-Z-area overlaps with the node's
575 if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
576 cbox.MaxEdge.Z - d > box.MinEdge.Z &&
577 cbox.MinEdge.Z + d < box.MaxEdge.Z) {
578 if (box_info.is_step_up) {
579 pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y;
581 box.MinEdge += *pos_f;
582 box.MaxEdge += *pos_f;
584 if (std::fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.05f) {
585 result.touching_ground = true;
587 if (box_info.isObject())
588 result.standing_on_object = true;