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