a089f33774d3bb66037b940c454c11ca06527666
[oweals/minetest.git] / src / collision.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "collision.h"
21 #include <cmath>
22 #include "mapblock.h"
23 #include "map.h"
24 #include "nodedef.h"
25 #include "gamedef.h"
26 #ifndef SERVER
27 #include "client/clientenvironment.h"
28 #include "client/localplayer.h"
29 #endif
30 #include "serverenvironment.h"
31 #include "server/serveractiveobject.h"
32 #include "util/timetaker.h"
33 #include "profiler.h"
34
35 #ifdef __FAST_MATH__
36 #warning "-ffast-math is known to cause bugs in collision code, do not use!"
37 #endif
38
39 struct NearbyCollisionInfo {
40         NearbyCollisionInfo(bool is_ul, bool is_obj, int bouncy,
41                         const v3s16 &pos, const aabb3f &box) :
42                 is_unloaded(is_ul),
43                 is_object(is_obj),
44                 bouncy(bouncy),
45                 position(pos),
46                 box(box)
47         {}
48
49         bool is_unloaded;
50         bool is_step_up = false;
51         bool is_object;
52         int bouncy;
53         v3s16 position;
54         aabb3f box;
55 };
56
57
58 // Helper function:
59 // Checks for collision of a moving aabbox with a static aabbox
60 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
61 // The time after which the collision occurs is stored in dtime.
62 CollisionAxis axisAlignedCollision(
63                 const aabb3f &staticbox, const aabb3f &movingbox,
64                 const v3f &speed, f32 *dtime)
65 {
66         //TimeTaker tt("axisAlignedCollision");
67
68         aabb3f relbox(
69                         movingbox.MaxEdge.X - movingbox.MinEdge.X + staticbox.MaxEdge.X - staticbox.MinEdge.X,                                          // sum of the widths
70                         movingbox.MaxEdge.Y - movingbox.MinEdge.Y + staticbox.MaxEdge.Y - staticbox.MinEdge.Y,
71                         movingbox.MaxEdge.Z - movingbox.MinEdge.Z + staticbox.MaxEdge.Z - staticbox.MinEdge.Z,
72                         std::max(movingbox.MaxEdge.X, staticbox.MaxEdge.X) - std::min(movingbox.MinEdge.X, staticbox.MinEdge.X),        //outer bounding 'box' dimensions
73                         std::max(movingbox.MaxEdge.Y, staticbox.MaxEdge.Y) - std::min(movingbox.MinEdge.Y, staticbox.MinEdge.Y),
74                         std::max(movingbox.MaxEdge.Z, staticbox.MaxEdge.Z) - std::min(movingbox.MinEdge.Z, staticbox.MinEdge.Z)
75         );
76
77         const f32 dtime_max = *dtime;
78         const f32 inner_margin = -1.5f;
79         f32 distance;
80         f32 time;
81
82         if (speed.X) {
83                 distance = relbox.MaxEdge.X - relbox.MinEdge.X;
84
85                 *dtime = distance >= 0 ? std::abs(distance / speed.X) : -std::abs(distance / speed.X);
86                 time = std::max(*dtime, 0.0f);
87
88                 if (distance > inner_margin) {
89                         if (*dtime <= dtime_max) {
90                                 if ((speed.X > 0 && staticbox.MaxEdge.X > movingbox.MaxEdge.X) ||
91                                                 (speed.X < 0 && staticbox.MinEdge.X < movingbox.MinEdge.X)) {
92                                         if (
93                                                 (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y)
94                                                         - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y)
95                                                         - relbox.MinEdge.Y < 0) &&
96                                                 (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z)
97                                                         - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z)
98                                                         - relbox.MinEdge.Z < 0)
99                                                 ) 
100                                                 return COLLISION_AXIS_X;
101                                 }
102                         } else {
103                                 return COLLISION_AXIS_NONE;
104                         }
105                 }
106         }
107
108         // NO else if here
109
110         if (speed.Y) {
111                 distance = relbox.MaxEdge.Y - relbox.MinEdge.Y;
112
113                 *dtime = distance >= 0 ? std::abs(distance / speed.Y) : -std::abs(distance / speed.Y);
114                 time = std::max(*dtime, 0.0f);
115
116                 if (distance > inner_margin) {
117                         if (*dtime <= dtime_max) {
118                                 if ((speed.Y > 0 && staticbox.MaxEdge.Y > movingbox.MaxEdge.Y) ||
119                                                 (speed.Y < 0 && staticbox.MinEdge.Y < movingbox.MinEdge.Y)) {
120                                         if (
121                                                 (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X)
122                                                         - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X)
123                                                         - relbox.MinEdge.X < 0) &&
124                                                 (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z)
125                                                         - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z)
126                                                         - relbox.MinEdge.Z < 0)
127                                                 ) 
128                                                 return COLLISION_AXIS_Y;
129                                 }
130                         } else {
131                                 return COLLISION_AXIS_NONE;
132                         }
133                 }
134         }
135
136         // NO else if here
137
138         if (speed.Z) {
139                 distance = relbox.MaxEdge.Z - relbox.MinEdge.Z;
140
141                 *dtime = distance >= 0 ? std::abs(distance / speed.Z) : -std::abs(distance / speed.Z);
142                 time = std::max(*dtime, 0.0f);
143
144                 if (distance > inner_margin) {
145                         if (*dtime <= dtime_max) {
146                                 if ((speed.Z > 0 && staticbox.MaxEdge.Z > movingbox.MaxEdge.Z) ||
147                                                 (speed.Z < 0 && staticbox.MinEdge.Z < movingbox.MinEdge.Z)) {
148                                         if (
149                                                 (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X)
150                                                         - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X)
151                                                         - relbox.MinEdge.X < 0) &&
152                                                 (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y)
153                                                         - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y)
154                                                         - relbox.MinEdge.Y < 0)
155                                                 ) 
156                                                 return COLLISION_AXIS_Z;
157                                 }
158                         }
159                 }
160         }
161
162         return COLLISION_AXIS_NONE;
163 }
164
165 // Helper function:
166 // Checks if moving the movingbox up by the given distance would hit a ceiling.
167 bool wouldCollideWithCeiling(
168                 const std::vector<NearbyCollisionInfo> &cinfo,
169                 const aabb3f &movingbox,
170                 f32 y_increase, f32 d)
171 {
172         //TimeTaker tt("wouldCollideWithCeiling");
173
174         assert(y_increase >= 0);        // pre-condition
175
176         for (const auto &it : cinfo) {
177                 const aabb3f &staticbox = it.box;
178                 if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
179                                 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
180                                 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
181                                 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
182                                 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
183                                 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
184                         return true;
185         }
186
187         return false;
188 }
189
190 static inline void getNeighborConnectingFace(const v3s16 &p,
191         const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors)
192 {
193         MapNode n2 = map->getNode(p);
194         if (nodedef->nodeboxConnects(n, n2, v))
195                 *neighbors |= v;
196 }
197
198 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
199                 f32 pos_max_d, const aabb3f &box_0,
200                 f32 stepheight, f32 dtime,
201                 v3f *pos_f, v3f *speed_f,
202                 v3f accel_f, ActiveObject *self,
203                 bool collideWithObjects)
204 {
205         static bool time_notification_done = false;
206         Map *map = &env->getMap();
207
208         ScopeProfiler sp(g_profiler, "collisionMoveSimple()", SPT_AVG);
209
210         collisionMoveResult result;
211
212         /*
213                 Calculate new velocity
214         */
215         if (dtime > 0.5f) {
216                 if (!time_notification_done) {
217                         time_notification_done = true;
218                         infostream << "collisionMoveSimple: maximum step interval exceeded,"
219                                         " lost movement details!"<<std::endl;
220                 }
221                 dtime = 0.5f;
222         } else {
223                 time_notification_done = false;
224         }
225         *speed_f += accel_f * dtime;
226
227         // If there is no speed, there are no collisions
228         if (speed_f->getLength() == 0)
229                 return result;
230
231         // Limit speed for avoiding hangs
232         speed_f->Y = rangelim(speed_f->Y, -5000, 5000);
233         speed_f->X = rangelim(speed_f->X, -5000, 5000);
234         speed_f->Z = rangelim(speed_f->Z, -5000, 5000);
235
236         /*
237                 Collect node boxes in movement range
238         */
239         std::vector<NearbyCollisionInfo> cinfo;
240         {
241         //TimeTaker tt2("collisionMoveSimple collect boxes");
242         ScopeProfiler sp2(g_profiler, "collisionMoveSimple(): collect boxes", SPT_AVG);
243
244         v3f newpos_f = *pos_f + *speed_f * dtime;
245         v3f minpos_f(
246                 MYMIN(pos_f->X, newpos_f.X),
247                 MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5
248                 MYMIN(pos_f->Z, newpos_f.Z)
249         );
250         v3f maxpos_f(
251                 MYMAX(pos_f->X, newpos_f.X),
252                 MYMAX(pos_f->Y, newpos_f.Y),
253                 MYMAX(pos_f->Z, newpos_f.Z)
254         );
255         v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1);
256         v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1);
257
258         bool any_position_valid = false;
259
260         v3s16 p;
261         for (p.X = min.X; p.X <= max.X; p.X++)
262         for (p.Y = min.Y; p.Y <= max.Y; p.Y++)
263         for (p.Z = min.Z; p.Z <= max.Z; p.Z++) {
264                 bool is_position_valid;
265                 MapNode n = map->getNode(p, &is_position_valid);
266
267                 if (is_position_valid && n.getContent() != CONTENT_IGNORE) {
268                         // Object collides into walkable nodes
269
270                         any_position_valid = true;
271                         const NodeDefManager *nodedef = gamedef->getNodeDefManager();
272                         const ContentFeatures &f = nodedef->get(n);
273
274                         if (!f.walkable)
275                                 continue;
276
277                         int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
278
279                         int neighbors = 0;
280                         if (f.drawtype == NDT_NODEBOX &&
281                                 f.node_box.type == NODEBOX_CONNECTED) {
282                                 v3s16 p2 = p;
283
284                                 p2.Y++;
285                                 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
286
287                                 p2 = p;
288                                 p2.Y--;
289                                 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
290
291                                 p2 = p;
292                                 p2.Z--;
293                                 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
294
295                                 p2 = p;
296                                 p2.X--;
297                                 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
298
299                                 p2 = p;
300                                 p2.Z++;
301                                 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
302
303                                 p2 = p;
304                                 p2.X++;
305                                 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
306                         }
307                         std::vector<aabb3f> nodeboxes;
308                         n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
309
310                         // Calculate float position only once
311                         v3f posf = intToFloat(p, BS);
312                         for (auto box : nodeboxes) {
313                                 box.MinEdge += posf;
314                                 box.MaxEdge += posf;
315                                 cinfo.emplace_back(false, false, n_bouncy_value, p, box);
316                         }
317                 } else {
318                         // Collide with unloaded nodes (position invalid) and loaded
319                         // CONTENT_IGNORE nodes (position valid)
320                         aabb3f box = getNodeBox(p, BS);
321                         cinfo.emplace_back(true, false, 0, p, box);
322                 }
323         }
324
325         // Do not move if world has not loaded yet, since custom node boxes
326         // are not available for collision detection.
327         // This also intentionally occurs in the case of the object being positioned
328         // solely on loaded CONTENT_IGNORE nodes, no matter where they come from.
329         if (!any_position_valid) {
330                 *speed_f = v3f(0, 0, 0);
331                 return result;
332         }
333
334         } // tt2
335
336         if(collideWithObjects)
337         {
338                 /* add object boxes to cinfo */
339
340                 std::vector<ActiveObject*> objects;
341 #ifndef SERVER
342                 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
343                 if (c_env != 0) {
344                         // Calculate distance by speed, add own extent and 1.5m of tolerance
345                         f32 distance = speed_f->getLength() * dtime +
346                                 box_0.getExtent().getLength() + 1.5f * BS;
347                         std::vector<DistanceSortedActiveObject> clientobjects;
348                         c_env->getActiveObjects(*pos_f, distance, clientobjects);
349
350                         for (auto &clientobject : clientobjects) {
351                                 // Do collide with everything but itself and the parent CAO
352                                 if (!self || (self != clientobject.obj &&
353                                                 self != clientobject.obj->getParent())) {
354                                         objects.push_back((ActiveObject*) clientobject.obj);
355                                 }
356                         }
357                 }
358                 else
359 #endif
360                 {
361                         ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
362                         if (s_env != NULL) {
363                                 // Calculate distance by speed, add own extent and 1.5m of tolerance
364                                 f32 distance = speed_f->getLength() * dtime +
365                                         box_0.getExtent().getLength() + 1.5f * BS;
366
367                                 // search for objects which are not us, or we are not its parent
368                                 // we directly use the callback to populate the result to prevent
369                                 // a useless result loop here
370                                 auto include_obj_cb = [self, &objects] (ServerActiveObject *obj) {
371                                         if (!self || (self != obj && self != obj->getParent())) {
372                                                 objects.push_back((ActiveObject *)obj);
373                                         }
374                                         return false;
375                                 };
376
377                                 std::vector<ServerActiveObject *> s_objects;
378                                 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance, include_obj_cb);
379                         }
380                 }
381
382                 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
383                                 iter != objects.end(); ++iter) {
384                         ActiveObject *object = *iter;
385
386                         if (object) {
387                                 aabb3f object_collisionbox;
388                                 if (object->getCollisionBox(&object_collisionbox) &&
389                                                 object->collideWithObjects()) {
390                                         cinfo.emplace_back(false, true, 0, v3s16(), object_collisionbox);
391                                 }
392                         }
393                 }
394 #ifndef SERVER
395                 if (self && c_env) {
396                         LocalPlayer *lplayer = c_env->getLocalPlayer();
397                         if (lplayer->getParent() == nullptr) {
398                                 aabb3f lplayer_collisionbox = lplayer->getCollisionbox();
399                                 v3f lplayer_pos = lplayer->getPosition();
400                                 lplayer_collisionbox.MinEdge += lplayer_pos;
401                                 lplayer_collisionbox.MaxEdge += lplayer_pos;
402                                 cinfo.emplace_back(false, true, 0, v3s16(), lplayer_collisionbox);
403                         }
404                 }
405 #endif
406         } //tt3
407
408         /*
409                 Collision detection
410         */
411
412         f32 d = 0.0f;
413
414         int loopcount = 0;
415
416         while(dtime > BS * 1e-10f) {
417                 // Avoid infinite loop
418                 loopcount++;
419                 if (loopcount >= 100) {
420                         warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
421                         break;
422                 }
423
424                 aabb3f movingbox = box_0;
425                 movingbox.MinEdge += *pos_f;
426                 movingbox.MaxEdge += *pos_f;
427
428                 CollisionAxis nearest_collided = COLLISION_AXIS_NONE;
429                 f32 nearest_dtime = dtime;
430                 int nearest_boxindex = -1;
431
432                 /*
433                         Go through every nodebox, find nearest collision
434                 */
435                 for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
436                         const NearbyCollisionInfo &box_info = cinfo[boxindex];
437                         // Ignore if already stepped up this nodebox.
438                         if (box_info.is_step_up)
439                                 continue;
440
441                         // Find nearest collision of the two boxes (raytracing-like)
442                         f32 dtime_tmp = nearest_dtime;
443                         CollisionAxis collided = axisAlignedCollision(box_info.box,
444                                         movingbox, *speed_f, &dtime_tmp);
445
446                         if (collided == -1 || dtime_tmp >= nearest_dtime)
447                                 continue;
448
449                         nearest_dtime = dtime_tmp;
450                         nearest_collided = collided;
451                         nearest_boxindex = boxindex;
452                 }
453
454                 if (nearest_collided == COLLISION_AXIS_NONE) {
455                         // No collision with any collision box.
456                         *pos_f += *speed_f * dtime;
457                         dtime = 0;  // Set to 0 to avoid "infinite" loop due to small FP numbers
458                 } else {
459                         // Otherwise, a collision occurred.
460                         NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
461                         const aabb3f& cbox = nearest_info.box;
462
463                         //movingbox except moved to the horizontal position it would be after step up
464                         aabb3f stepbox = movingbox;
465                         stepbox.MinEdge.X += speed_f->X * dtime;
466                         stepbox.MinEdge.Z += speed_f->Z * dtime;
467                         stepbox.MaxEdge.X += speed_f->X * dtime;
468                         stepbox.MaxEdge.Z += speed_f->Z * dtime;
469                         // Check for stairs.
470                         bool step_up = (nearest_collided != COLLISION_AXIS_Y) && // must not be Y direction
471                                         (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
472                                         (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
473                                         (!wouldCollideWithCeiling(cinfo, stepbox,
474                                                         cbox.MaxEdge.Y - movingbox.MinEdge.Y,
475                                                         d));
476
477                         // Get bounce multiplier
478                         float bounce = -(float)nearest_info.bouncy / 100.0f;
479
480                         // Move to the point of collision and reduce dtime by nearest_dtime
481                         if (nearest_dtime < 0) {
482                                 // Handle negative nearest_dtime
483                                 if (!step_up) {
484                                         if (nearest_collided == COLLISION_AXIS_X)
485                                                 pos_f->X += speed_f->X * nearest_dtime;
486                                         if (nearest_collided == COLLISION_AXIS_Y)
487                                                 pos_f->Y += speed_f->Y * nearest_dtime;
488                                         if (nearest_collided == COLLISION_AXIS_Z)
489                                                 pos_f->Z += speed_f->Z * nearest_dtime;
490                                 }
491                         } else {
492                                 *pos_f += *speed_f * nearest_dtime;
493                                 dtime -= nearest_dtime;
494                         }
495
496                         bool is_collision = true;
497                         if (nearest_info.is_unloaded)
498                                 is_collision = false;
499
500                         CollisionInfo info;
501                         if (nearest_info.is_object)
502                                 info.type = COLLISION_OBJECT;
503                         else
504                                 info.type = COLLISION_NODE;
505
506                         info.node_p = nearest_info.position;
507                         info.old_speed = *speed_f;
508                         info.plane = nearest_collided;
509
510                         // Set the speed component that caused the collision to zero
511                         if (step_up) {
512                                 // Special case: Handle stairs
513                                 nearest_info.is_step_up = true;
514                                 is_collision = false;
515                         } else if (nearest_collided == COLLISION_AXIS_X) {
516                                 if (fabs(speed_f->X) > BS * 3)
517                                         speed_f->X *= bounce;
518                                 else
519                                         speed_f->X = 0;
520                                 result.collides = true;
521                         } else if (nearest_collided == COLLISION_AXIS_Y) {
522                                 if(fabs(speed_f->Y) > BS * 3)
523                                         speed_f->Y *= bounce;
524                                 else
525                                         speed_f->Y = 0;
526                                 result.collides = true;
527                         } else if (nearest_collided == COLLISION_AXIS_Z) {
528                                 if (fabs(speed_f->Z) > BS * 3)
529                                         speed_f->Z *= bounce;
530                                 else
531                                         speed_f->Z = 0;
532                                 result.collides = true;
533                         }
534
535                         info.new_speed = *speed_f;
536                         if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1f * BS)
537                                 is_collision = false;
538
539                         if (is_collision) {
540                                 info.axis = nearest_collided;
541                                 result.collisions.push_back(info);
542                         }
543                 }
544         }
545
546         /*
547                 Final touches: Check if standing on ground, step up stairs.
548         */
549         aabb3f box = box_0;
550         box.MinEdge += *pos_f;
551         box.MaxEdge += *pos_f;
552         for (const auto &box_info : cinfo) {
553                 const aabb3f &cbox = box_info.box;
554
555                 /*
556                         See if the object is touching ground.
557
558                         Object touches ground if object's minimum Y is near node's
559                         maximum Y and object's X-Z-area overlaps with the node's
560                         X-Z-area.
561                 */
562
563                 if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
564                                 cbox.MaxEdge.Z - d > box.MinEdge.Z &&
565                                 cbox.MinEdge.Z + d < box.MaxEdge.Z) {
566                         if (box_info.is_step_up) {
567                                 pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y;
568                                 box = box_0;
569                                 box.MinEdge += *pos_f;
570                                 box.MaxEdge += *pos_f;
571                         }
572                         if (std::fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.05f) {
573                                 result.touching_ground = true;
574
575                                 if (box_info.is_object)
576                                         result.standing_on_object = true;
577                         }
578                 }
579         }
580
581         return result;
582 }