Optimize updateFastFaceRow processing by removing some TileSpec copy (#5678)
[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 "mapblock.h"
22 #include "map.h"
23 #include "nodedef.h"
24 #include "gamedef.h"
25 #ifndef SERVER
26 #include "clientenvironment.h"
27 #endif
28 #include "serverenvironment.h"
29 #include "serverobject.h"
30 #include "util/timetaker.h"
31 #include "profiler.h"
32
33 // float error is 10 - 9.96875 = 0.03125
34 //#define COLL_ZERO 0.032 // broken unit tests
35 #define COLL_ZERO 0
36
37
38 struct NearbyCollisionInfo {
39         NearbyCollisionInfo(bool is_ul, bool is_obj, int bouncy,
40                         const v3s16 &pos, const aabb3f &box) :
41                 is_unloaded(is_ul),
42                 is_step_up(false),
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;
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 int axisAlignedCollision(
63                 const aabb3f &staticbox, const aabb3f &movingbox,
64                 const v3f &speed, f32 d, f32 *dtime)
65 {
66         //TimeTaker tt("axisAlignedCollision");
67
68         f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X) - COLL_ZERO;     // reduce box size for solve collision stuck (flying sand)
69         f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later
70         f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z) - COLL_ZERO;
71
72         aabb3f relbox(
73                         movingbox.MinEdge.X - staticbox.MinEdge.X,
74                         movingbox.MinEdge.Y - staticbox.MinEdge.Y,
75                         movingbox.MinEdge.Z - staticbox.MinEdge.Z,
76                         movingbox.MaxEdge.X - staticbox.MinEdge.X,
77                         movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
78                         movingbox.MaxEdge.Z - staticbox.MinEdge.Z
79         );
80
81         if(speed.X > 0) // Check for collision with X- plane
82         {
83                 if (relbox.MaxEdge.X <= d) {
84                         *dtime = -relbox.MaxEdge.X / speed.X;
85                         if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
86                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
87                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
88                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
89                                 return 0;
90                 }
91                 else if(relbox.MinEdge.X > xsize)
92                 {
93                         return -1;
94                 }
95         }
96         else if(speed.X < 0) // Check for collision with X+ plane
97         {
98                 if (relbox.MinEdge.X >= xsize - d) {
99                         *dtime = (xsize - relbox.MinEdge.X) / speed.X;
100                         if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
101                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
102                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
103                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
104                                 return 0;
105                 }
106                 else if(relbox.MaxEdge.X < 0)
107                 {
108                         return -1;
109                 }
110         }
111
112         // NO else if here
113
114         if(speed.Y > 0) // Check for collision with Y- plane
115         {
116                 if (relbox.MaxEdge.Y <= d) {
117                         *dtime = -relbox.MaxEdge.Y / speed.Y;
118                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
119                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
120                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
121                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
122                                 return 1;
123                 }
124                 else if(relbox.MinEdge.Y > ysize)
125                 {
126                         return -1;
127                 }
128         }
129         else if(speed.Y < 0) // Check for collision with Y+ plane
130         {
131                 if (relbox.MinEdge.Y >= ysize - d) {
132                         *dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
133                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
134                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
135                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
136                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
137                                 return 1;
138                 }
139                 else if(relbox.MaxEdge.Y < 0)
140                 {
141                         return -1;
142                 }
143         }
144
145         // NO else if here
146
147         if(speed.Z > 0) // Check for collision with Z- plane
148         {
149                 if (relbox.MaxEdge.Z <= d) {
150                         *dtime = -relbox.MaxEdge.Z / speed.Z;
151                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
152                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
153                                         (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
154                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
155                                 return 2;
156                 }
157                 //else if(relbox.MinEdge.Z > zsize)
158                 //{
159                 //      return -1;
160                 //}
161         }
162         else if(speed.Z < 0) // Check for collision with Z+ plane
163         {
164                 if (relbox.MinEdge.Z >= zsize - d) {
165                         *dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
166                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
167                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
168                                         (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
169                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
170                                 return 2;
171                 }
172                 //else if(relbox.MaxEdge.Z < 0)
173                 //{
174                 //      return -1;
175                 //}
176         }
177
178         return -1;
179 }
180
181 // Helper function:
182 // Checks if moving the movingbox up by the given distance would hit a ceiling.
183 bool wouldCollideWithCeiling(
184                 const std::vector<NearbyCollisionInfo> &cinfo,
185                 const aabb3f &movingbox,
186                 f32 y_increase, f32 d)
187 {
188         //TimeTaker tt("wouldCollideWithCeiling");
189
190         assert(y_increase >= 0);        // pre-condition
191
192         for (std::vector<NearbyCollisionInfo>::const_iterator it = cinfo.begin();
193                         it != cinfo.end(); ++it) {
194                 const aabb3f &staticbox = it->box;
195                 if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
196                                 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
197                                 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
198                                 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
199                                 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
200                                 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
201                         return true;
202         }
203
204         return false;
205 }
206
207 static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef,
208                 Map *map, MapNode n, int v, int *neighbors)
209 {
210         MapNode n2 = map->getNodeNoEx(p);
211         if (nodedef->nodeboxConnects(n, n2, v))
212                 *neighbors |= v;
213 }
214
215 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
216                 f32 pos_max_d, const aabb3f &box_0,
217                 f32 stepheight, f32 dtime,
218                 v3f *pos_f, v3f *speed_f,
219                 v3f accel_f, ActiveObject *self,
220                 bool collideWithObjects)
221 {
222         static bool time_notification_done = false;
223         Map *map = &env->getMap();
224         //TimeTaker tt("collisionMoveSimple");
225         ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG);
226
227         collisionMoveResult result;
228
229         /*
230                 Calculate new velocity
231         */
232         if (dtime > 0.5) {
233                 if (!time_notification_done) {
234                         time_notification_done = true;
235                         infostream << "collisionMoveSimple: maximum step interval exceeded,"
236                                         " lost movement details!"<<std::endl;
237                 }
238                 dtime = 0.5;
239         } else {
240                 time_notification_done = false;
241         }
242         *speed_f += accel_f * dtime;
243
244         // If there is no speed, there are no collisions
245         if (speed_f->getLength() == 0)
246                 return result;
247
248         // Limit speed for avoiding hangs
249         speed_f->Y = rangelim(speed_f->Y, -5000, 5000);
250         speed_f->X = rangelim(speed_f->X, -5000, 5000);
251         speed_f->Z = rangelim(speed_f->Z, -5000, 5000);
252
253         /*
254                 Collect node boxes in movement range
255         */
256         std::vector<NearbyCollisionInfo> cinfo;
257         {
258         //TimeTaker tt2("collisionMoveSimple collect boxes");
259         ScopeProfiler sp(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG);
260
261         v3s16 oldpos_i = floatToInt(*pos_f, BS);
262         v3s16 newpos_i = floatToInt(*pos_f + *speed_f * dtime, BS);
263         s16 min_x = MYMIN(oldpos_i.X, newpos_i.X) + (box_0.MinEdge.X / BS) - 1;
264         s16 min_y = MYMIN(oldpos_i.Y, newpos_i.Y) + (box_0.MinEdge.Y / BS) - 1;
265         s16 min_z = MYMIN(oldpos_i.Z, newpos_i.Z) + (box_0.MinEdge.Z / BS) - 1;
266         s16 max_x = MYMAX(oldpos_i.X, newpos_i.X) + (box_0.MaxEdge.X / BS) + 1;
267         s16 max_y = MYMAX(oldpos_i.Y, newpos_i.Y) + (box_0.MaxEdge.Y / BS) + 1;
268         s16 max_z = MYMAX(oldpos_i.Z, newpos_i.Z) + (box_0.MaxEdge.Z / BS) + 1;
269
270         bool any_position_valid = false;
271
272         for(s16 x = min_x; x <= max_x; x++)
273         for(s16 y = min_y; y <= max_y; y++)
274         for(s16 z = min_z; z <= max_z; z++)
275         {
276                 v3s16 p(x,y,z);
277
278                 bool is_position_valid;
279                 MapNode n = map->getNodeNoEx(p, &is_position_valid);
280
281                 if (is_position_valid) {
282                         // Object collides into walkable nodes
283
284                         any_position_valid = true;
285                         INodeDefManager *nodedef = gamedef->getNodeDefManager();
286                         const ContentFeatures &f = nodedef->get(n);
287                         if(f.walkable == false)
288                                 continue;
289                         int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
290
291                         int neighbors = 0;
292                         if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) {
293                                 v3s16 p2 = p;
294
295                                 p2.Y++;
296                                 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
297
298                                 p2 = p;
299                                 p2.Y--;
300                                 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
301
302                                 p2 = p;
303                                 p2.Z--;
304                                 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
305
306                                 p2 = p;
307                                 p2.X--;
308                                 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
309
310                                 p2 = p;
311                                 p2.Z++;
312                                 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
313
314                                 p2 = p;
315                                 p2.X++;
316                                 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
317                         }
318                         std::vector<aabb3f> nodeboxes;
319                         n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
320                         for(std::vector<aabb3f>::iterator
321                                         i = nodeboxes.begin();
322                                         i != nodeboxes.end(); ++i)
323                         {
324                                 aabb3f box = *i;
325                                 box.MinEdge += v3f(x, y, z)*BS;
326                                 box.MaxEdge += v3f(x, y, z)*BS;
327                                 cinfo.push_back(NearbyCollisionInfo(false,
328                                         false, n_bouncy_value, p, box));
329                         }
330                 } else {
331                         // Collide with unloaded nodes
332                         aabb3f box = getNodeBox(p, BS);
333                         cinfo.push_back(NearbyCollisionInfo(true, false, 0, p, box));
334                 }
335         }
336
337         // Do not move if world has not loaded yet, since custom node boxes
338         // are not available for collision detection.
339         if (!any_position_valid) {
340                 *speed_f = v3f(0, 0, 0);
341                 return result;
342         }
343
344         } // tt2
345
346         if(collideWithObjects)
347         {
348                 ScopeProfiler sp(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
349                 //TimeTaker tt3("collisionMoveSimple collect object boxes");
350
351                 /* add object boxes to cinfo */
352
353                 std::vector<ActiveObject*> objects;
354 #ifndef SERVER
355                 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
356                 if (c_env != 0) {
357                         f32 distance = speed_f->getLength();
358                         std::vector<DistanceSortedActiveObject> clientobjects;
359                         c_env->getActiveObjects(*pos_f, distance * 1.5, clientobjects);
360                         for (size_t i=0; i < clientobjects.size(); i++) {
361                                 if ((self == 0) || (self != clientobjects[i].obj)) {
362                                         objects.push_back((ActiveObject*)clientobjects[i].obj);
363                                 }
364                         }
365                 }
366                 else
367 #endif
368                 {
369                         ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
370                         if (s_env != NULL) {
371                                 f32 distance = speed_f->getLength();
372                                 std::vector<u16> s_objects;
373                                 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance * 1.5);
374                                 for (std::vector<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); ++iter) {
375                                         ServerActiveObject *current = s_env->getActiveObject(*iter);
376                                         if ((self == 0) || (self != current)) {
377                                                 objects.push_back((ActiveObject*)current);
378                                         }
379                                 }
380                         }
381                 }
382
383                 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
384                                 iter != objects.end(); ++iter) {
385                         ActiveObject *object = *iter;
386
387                         if (object != NULL) {
388                                 aabb3f object_collisionbox;
389                                 if (object->getCollisionBox(&object_collisionbox) &&
390                                                 object->collideWithObjects()) {
391                                         cinfo.push_back(NearbyCollisionInfo(false, true, 0, v3s16(), object_collisionbox));
392                                 }
393                         }
394                 }
395         } //tt3
396
397         /*
398                 Collision detection
399         */
400
401         /*
402                 Collision uncertainty radius
403                 Make it a bit larger than the maximum distance of movement
404         */
405         f32 d = pos_max_d * 1.1;
406         // A fairly large value in here makes moving smoother
407         //f32 d = 0.15*BS;
408
409         // This should always apply, otherwise there are glitches
410         assert(d > pos_max_d);  // invariant
411
412         int loopcount = 0;
413
414         while(dtime > BS * 1e-10) {
415                 //TimeTaker tt3("collisionMoveSimple dtime loop");
416                 ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
417
418                 // Avoid infinite loop
419                 loopcount++;
420                 if (loopcount >= 100) {
421                         warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
422                         break;
423                 }
424
425                 aabb3f movingbox = box_0;
426                 movingbox.MinEdge += *pos_f;
427                 movingbox.MaxEdge += *pos_f;
428
429                 int nearest_collided = -1;
430                 f32 nearest_dtime = dtime;
431                 int nearest_boxindex = -1;
432
433                 /*
434                         Go through every nodebox, find nearest collision
435                 */
436                 for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
437                         NearbyCollisionInfo box_info = cinfo[boxindex];
438                         // Ignore if already stepped up this nodebox.
439                         if (box_info.is_step_up)
440                                 continue;
441
442                         // Find nearest collision of the two boxes (raytracing-like)
443                         f32 dtime_tmp;
444                         int collided = axisAlignedCollision(box_info.box,
445                                         movingbox, *speed_f, d, &dtime_tmp);
446
447                         if (collided == -1 || dtime_tmp >= nearest_dtime)
448                                 continue;
449
450                         nearest_dtime = dtime_tmp;
451                         nearest_collided = collided;
452                         nearest_boxindex = boxindex;
453                 }
454
455                 if (nearest_collided == -1) {
456                         // No collision with any collision box.
457                         *pos_f += *speed_f * dtime;
458                         dtime = 0;  // Set to 0 to avoid "infinite" loop due to small FP numbers
459                 } else {
460                         // Otherwise, a collision occurred.
461                         NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
462                         const aabb3f& cbox = nearest_info.box;
463                         // Check for stairs.
464                         bool step_up = (nearest_collided != 1) && // must not be Y direction
465                                         (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
466                                         (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
467                                         (!wouldCollideWithCeiling(cinfo, movingbox,
468                                                         cbox.MaxEdge.Y - movingbox.MinEdge.Y,
469                                                         d));
470
471                         // Get bounce multiplier
472                         bool bouncy = (nearest_info.bouncy >= 1);
473                         float bounce = -(float)nearest_info.bouncy / 100.0;
474
475                         // Move to the point of collision and reduce dtime by nearest_dtime
476                         if (nearest_dtime < 0) {
477                                 // Handle negative nearest_dtime (can be caused by the d allowance)
478                                 if (!step_up) {
479                                         if (nearest_collided == 0)
480                                                 pos_f->X += speed_f->X * nearest_dtime;
481                                         if (nearest_collided == 1)
482                                                 pos_f->Y += speed_f->Y * nearest_dtime;
483                                         if (nearest_collided == 2)
484                                                 pos_f->Z += speed_f->Z * nearest_dtime;
485                                 }
486                         } else {
487                                 *pos_f += *speed_f * nearest_dtime;
488                                 dtime -= nearest_dtime;
489                         }
490
491                         bool is_collision = true;
492                         if (nearest_info.is_unloaded)
493                                 is_collision = false;
494
495                         CollisionInfo info;
496                         if (nearest_info.is_object)
497                                 info.type = COLLISION_OBJECT;
498                         else
499                                 info.type = COLLISION_NODE;
500
501                         info.node_p = nearest_info.position;
502                         info.bouncy = bouncy;
503                         info.old_speed = *speed_f;
504
505                         // Set the speed component that caused the collision to zero
506                         if (step_up) {
507                                 // Special case: Handle stairs
508                                 nearest_info.is_step_up = true;
509                                 is_collision = false;
510                         } else if (nearest_collided == 0) { // X
511                                 if (fabs(speed_f->X) > BS * 3)
512                                         speed_f->X *= bounce;
513                                 else
514                                         speed_f->X = 0;
515                                 result.collides = true;
516                                 result.collides_xz = true;
517                         } else if (nearest_collided == 1) { // Y
518                                 if(fabs(speed_f->Y) > BS * 3)
519                                         speed_f->Y *= bounce;
520                                 else
521                                         speed_f->Y = 0;
522                                 result.collides = true;
523                         } else if (nearest_collided == 2) { // Z
524                                 if (fabs(speed_f->Z) > BS * 3)
525                                         speed_f->Z *= bounce;
526                                 else
527                                         speed_f->Z = 0;
528                                 result.collides = true;
529                                 result.collides_xz = true;
530                         }
531
532                         info.new_speed = *speed_f;
533                         if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1 * BS)
534                                 is_collision = false;
535
536                         if (is_collision) {
537                                 result.collisions.push_back(info);
538                         }
539                 }
540         }
541
542         /*
543                 Final touches: Check if standing on ground, step up stairs.
544         */
545         aabb3f box = box_0;
546         box.MinEdge += *pos_f;
547         box.MaxEdge += *pos_f;
548         for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
549                 NearbyCollisionInfo &box_info = cinfo[boxindex];
550                 const aabb3f &cbox = box_info.box;
551
552                 /*
553                         See if the object is touching ground.
554
555                         Object touches ground if object's minimum Y is near node's
556                         maximum Y and object's X-Z-area overlaps with the node's
557                         X-Z-area.
558
559                         Use 0.15*BS so that it is easier to get on a node.
560                 */
561                 if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
562                                 cbox.MaxEdge.Z - d > box.MinEdge.Z &&
563                                 cbox.MinEdge.Z + d < box.MaxEdge.Z) {
564                         if (box_info.is_step_up) {
565                                 pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y;
566                                 box = box_0;
567                                 box.MinEdge += *pos_f;
568                                 box.MaxEdge += *pos_f;
569                         }
570                         if (fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.15 * BS) {
571                                 result.touching_ground = true;
572
573                                 if (box_info.is_object)
574                                         result.standing_on_object = true;
575                                 if (box_info.is_unloaded)
576                                         result.standing_on_unloaded = true;
577                         }
578                 }
579         }
580
581         return result;
582 }