]> 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         /*
217                 Collect node boxes in movement range
218         */
219         std::vector<aabb3f> cboxes;
220         std::vector<bool> is_unloaded;
221         std::vector<bool> is_step_up;
222         std::vector<bool> is_object;
223         std::vector<int> bouncy_values;
224         std::vector<v3s16> node_positions;
225         {
226         //TimeTaker tt2("collisionMoveSimple collect boxes");
227     ScopeProfiler sp(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG);
228
229         v3s16 oldpos_i = floatToInt(pos_f, BS);
230         v3s16 newpos_i = floatToInt(pos_f + speed_f * dtime, BS);
231         s16 min_x = MYMIN(oldpos_i.X, newpos_i.X) + (box_0.MinEdge.X / BS) - 1;
232         s16 min_y = MYMIN(oldpos_i.Y, newpos_i.Y) + (box_0.MinEdge.Y / BS) - 1;
233         s16 min_z = MYMIN(oldpos_i.Z, newpos_i.Z) + (box_0.MinEdge.Z / BS) - 1;
234         s16 max_x = MYMAX(oldpos_i.X, newpos_i.X) + (box_0.MaxEdge.X / BS) + 1;
235         s16 max_y = MYMAX(oldpos_i.Y, newpos_i.Y) + (box_0.MaxEdge.Y / BS) + 1;
236         s16 max_z = MYMAX(oldpos_i.Z, newpos_i.Z) + (box_0.MaxEdge.Z / BS) + 1;
237
238         for(s16 x = min_x; x <= max_x; x++)
239         for(s16 y = min_y; y <= max_y; y++)
240         for(s16 z = min_z; z <= max_z; z++)
241         {
242                 v3s16 p(x,y,z);
243                 try{
244                         // Object collides into walkable nodes
245                         MapNode n = map->getNode(p);
246                         const ContentFeatures &f = gamedef->getNodeDefManager()->get(n);
247                         if(f.walkable == false)
248                                 continue;
249                         int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
250
251                         std::vector<aabb3f> nodeboxes = n.getNodeBoxes(gamedef->ndef());
252                         for(std::vector<aabb3f>::iterator
253                                         i = nodeboxes.begin();
254                                         i != nodeboxes.end(); i++)
255                         {
256                                 aabb3f box = *i;
257                                 box.MinEdge += v3f(x, y, z)*BS;
258                                 box.MaxEdge += v3f(x, y, z)*BS;
259                                 cboxes.push_back(box);
260                                 is_unloaded.push_back(false);
261                                 is_step_up.push_back(false);
262                                 bouncy_values.push_back(n_bouncy_value);
263                                 node_positions.push_back(p);
264                                 is_object.push_back(false);
265                         }
266                 }
267                 catch(InvalidPositionException &e)
268                 {
269                         // Collide with unloaded nodes
270                         aabb3f box = getNodeBox(p, BS);
271                         cboxes.push_back(box);
272                         is_unloaded.push_back(true);
273                         is_step_up.push_back(false);
274                         bouncy_values.push_back(0);
275                         node_positions.push_back(p);
276                         is_object.push_back(false);
277                 }
278         }
279         } // tt2
280
281         {
282                 ScopeProfiler sp(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
283                 //TimeTaker tt3("collisionMoveSimple collect object boxes");
284
285                 /* add object boxes to cboxes */
286
287
288                 std::list<ActiveObject*> objects;
289 #ifndef SERVER
290                 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
291                 if (c_env != 0)
292                 {
293                         f32 distance = speed_f.getLength();
294                         std::vector<DistanceSortedActiveObject> clientobjects;
295                         c_env->getActiveObjects(pos_f,distance * 1.5,clientobjects);
296                         for (int i=0; i < clientobjects.size(); i++)
297                         {
298                                 objects.push_back((ActiveObject*)clientobjects[i].obj);
299                         }
300                 }
301                 else
302 #endif
303                 {
304                         ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
305                         if (s_env != 0)
306                         {
307                                 f32 distance = speed_f.getLength();
308                                 std::set<u16> s_objects = s_env->getObjectsInsideRadius(pos_f,distance * 1.5);
309                                 for (std::set<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); iter++)
310                                 {
311                                         ServerActiveObject *current = s_env->getActiveObject(*iter);
312                                         objects.push_back((ActiveObject*)current);
313                                 }
314                         }
315                 }
316
317                 for (std::list<ActiveObject*>::const_iterator iter = objects.begin();iter != objects.end(); ++iter)
318                 {
319                         ActiveObject *object = *iter;
320
321                         if (object != NULL)
322                         {
323                                 aabb3f object_collisionbox;
324                                 if (object->getCollisionBox(&object_collisionbox))
325                                 {
326                                         cboxes.push_back(object_collisionbox);
327                                         is_unloaded.push_back(false);
328                                         is_step_up.push_back(false);
329                                         bouncy_values.push_back(0);
330                                         node_positions.push_back(v3s16(0,0,0));
331                                         is_object.push_back(true);
332                                 }
333                         }
334                 }
335         } //tt3
336
337         assert(cboxes.size() == is_unloaded.size());
338         assert(cboxes.size() == is_step_up.size());
339         assert(cboxes.size() == bouncy_values.size());
340         assert(cboxes.size() == node_positions.size());
341         assert(cboxes.size() == is_object.size());
342
343         /*
344                 Collision detection
345         */
346
347         /*
348                 Collision uncertainty radius
349                 Make it a bit larger than the maximum distance of movement
350         */
351         f32 d = pos_max_d * 1.1;
352         // A fairly large value in here makes moving smoother
353         //f32 d = 0.15*BS;
354
355         // This should always apply, otherwise there are glitches
356         assert(d > pos_max_d);
357
358         int loopcount = 0;
359
360         while(dtime > BS*1e-10)
361         {
362                 //TimeTaker tt3("collisionMoveSimple dtime loop");
363         ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
364
365                 // Avoid infinite loop
366                 loopcount++;
367                 if(loopcount >= 100)
368                 {
369                         infostream<<"collisionMoveSimple: WARNING: Loop count exceeded, aborting to avoid infiniite loop"<<std::endl;
370                         dtime = 0;
371                         break;
372                 }
373
374                 aabb3f movingbox = box_0;
375                 movingbox.MinEdge += pos_f;
376                 movingbox.MaxEdge += pos_f;
377
378                 int nearest_collided = -1;
379                 f32 nearest_dtime = dtime;
380                 u32 nearest_boxindex = -1;
381
382                 /*
383                         Go through every nodebox, find nearest collision
384                 */
385                 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
386                 {
387                         // Ignore if already stepped up this nodebox.
388                         if(is_step_up[boxindex])
389                                 continue;
390
391                         // Find nearest collision of the two boxes (raytracing-like)
392                         f32 dtime_tmp;
393                         int collided = axisAlignedCollision(
394                                         cboxes[boxindex], movingbox, speed_f, d, dtime_tmp);
395
396                         if(collided == -1 || dtime_tmp >= nearest_dtime)
397                                 continue;
398
399                         nearest_dtime = dtime_tmp;
400                         nearest_collided = collided;
401                         nearest_boxindex = boxindex;
402                 }
403
404                 if(nearest_collided == -1)
405                 {
406                         // No collision with any collision box.
407                         pos_f += speed_f * dtime;
408                         dtime = 0;  // Set to 0 to avoid "infinite" loop due to small FP numbers
409                 }
410                 else
411                 {
412                         // Otherwise, a collision occurred.
413
414                         const aabb3f& cbox = cboxes[nearest_boxindex];
415
416                         // Check for stairs.
417                         bool step_up = (nearest_collided != 1) && // must not be Y direction
418                                         (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
419                                         (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
420                                         (!wouldCollideWithCeiling(cboxes, movingbox,
421                                                         cbox.MaxEdge.Y - movingbox.MinEdge.Y,
422                                                         d));
423
424                         // Get bounce multiplier
425                         bool bouncy = (bouncy_values[nearest_boxindex] >= 1);
426                         float bounce = -(float)bouncy_values[nearest_boxindex] / 100.0;
427
428                         // Move to the point of collision and reduce dtime by nearest_dtime
429                         if(nearest_dtime < 0)
430                         {
431                                 // Handle negative nearest_dtime (can be caused by the d allowance)
432                                 if(!step_up)
433                                 {
434                                         if(nearest_collided == 0)
435                                                 pos_f.X += speed_f.X * nearest_dtime;
436                                         if(nearest_collided == 1)
437                                                 pos_f.Y += speed_f.Y * nearest_dtime;
438                                         if(nearest_collided == 2)
439                                                 pos_f.Z += speed_f.Z * nearest_dtime;
440                                 }
441                         }
442                         else
443                         {
444                                 pos_f += speed_f * nearest_dtime;
445                                 dtime -= nearest_dtime;
446                         }
447                         
448                         bool is_collision = true;
449                         if(is_unloaded[nearest_boxindex])
450                                 is_collision = false;
451
452                         CollisionInfo info;
453                         if (is_object[nearest_boxindex]) {
454                                 info.type = COLLISION_OBJECT;
455                         }
456                         else
457                                 info.type = COLLISION_NODE;
458                         info.node_p = node_positions[nearest_boxindex];
459                         info.bouncy = bouncy;
460                         info.old_speed = speed_f;
461
462                         // Set the speed component that caused the collision to zero
463                         if(step_up)
464                         {
465                                 // Special case: Handle stairs
466                                 is_step_up[nearest_boxindex] = true;
467                                 is_collision = false;
468                         }
469                         else if(nearest_collided == 0) // X
470                         {
471                                 if(fabs(speed_f.X) > BS*3)
472                                         speed_f.X *= bounce;
473                                 else
474                                         speed_f.X = 0;
475                                 result.collides = true;
476                                 result.collides_xz = true;
477                         }
478                         else if(nearest_collided == 1) // Y
479                         {
480                                 if(fabs(speed_f.Y) > BS*3)
481                                         speed_f.Y *= bounce;
482                                 else
483                                         speed_f.Y = 0;
484                                 result.collides = true;
485                         }
486                         else if(nearest_collided == 2) // Z
487                         {
488                                 if(fabs(speed_f.Z) > BS*3)
489                                         speed_f.Z *= bounce;
490                                 else
491                                         speed_f.Z = 0;
492                                 result.collides = true;
493                                 result.collides_xz = true;
494                         }
495
496                         info.new_speed = speed_f;
497                         if(info.new_speed.getDistanceFrom(info.old_speed) < 0.1*BS)
498                                 is_collision = false;
499
500                         if(is_collision){
501                                 result.collisions.push_back(info);
502                         }
503                 }
504         }
505
506         /*
507                 Final touches: Check if standing on ground, step up stairs.
508         */
509         aabb3f box = box_0;
510         box.MinEdge += pos_f;
511         box.MaxEdge += pos_f;
512         for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
513         {
514                 const aabb3f& cbox = cboxes[boxindex];
515
516                 /*
517                         See if the object is touching ground.
518
519                         Object touches ground if object's minimum Y is near node's
520                         maximum Y and object's X-Z-area overlaps with the node's
521                         X-Z-area.
522
523                         Use 0.15*BS so that it is easier to get on a node.
524                 */
525                 if(
526                                 cbox.MaxEdge.X-d > box.MinEdge.X &&
527                                 cbox.MinEdge.X+d < box.MaxEdge.X &&
528                                 cbox.MaxEdge.Z-d > box.MinEdge.Z &&
529                                 cbox.MinEdge.Z+d < box.MaxEdge.Z
530                 ){
531                         if(is_step_up[boxindex])
532                         {
533                                 pos_f.Y += (cbox.MaxEdge.Y - box.MinEdge.Y);
534                                 box = box_0;
535                                 box.MinEdge += pos_f;
536                                 box.MaxEdge += pos_f;
537                         }
538                         if(fabs(cbox.MaxEdge.Y-box.MinEdge.Y) < 0.15*BS)
539                         {
540                                 result.touching_ground = true;
541                                 if(is_unloaded[boxindex])
542                                         result.standing_on_unloaded = true;
543                         }
544                 }
545         }
546
547         return result;
548 }
549
550 #if 0
551 // This doesn't seem to work and isn't used
552 collisionMoveResult collisionMovePrecise(Map *map, IGameDef *gamedef,
553                 f32 pos_max_d, const aabb3f &box_0,
554                 f32 stepheight, f32 dtime,
555                 v3f &pos_f, v3f &speed_f, v3f &accel_f)
556 {
557         //TimeTaker tt("collisionMovePrecise");
558     ScopeProfiler sp(g_profiler, "collisionMovePrecise avg", SPT_AVG);
559         
560         collisionMoveResult final_result;
561
562         // If there is no speed, there are no collisions
563         if(speed_f.getLength() == 0)
564                 return final_result;
565
566         // Don't allow overly huge dtime
567         if(dtime > 2.0)
568                 dtime = 2.0;
569
570         f32 dtime_downcount = dtime;
571
572         u32 loopcount = 0;
573         do
574         {
575                 loopcount++;
576
577                 // Maximum time increment (for collision detection etc)
578                 // time = distance / speed
579                 f32 dtime_max_increment = 1.0;
580                 if(speed_f.getLength() != 0)
581                         dtime_max_increment = pos_max_d / speed_f.getLength();
582
583                 // Maximum time increment is 10ms or lower
584                 if(dtime_max_increment > 0.01)
585                         dtime_max_increment = 0.01;
586
587                 f32 dtime_part;
588                 if(dtime_downcount > dtime_max_increment)
589                 {
590                         dtime_part = dtime_max_increment;
591                         dtime_downcount -= dtime_part;
592                 }
593                 else
594                 {
595                         dtime_part = dtime_downcount;
596                         /*
597                                 Setting this to 0 (no -=dtime_part) disables an infinite loop
598                                 when dtime_part is so small that dtime_downcount -= dtime_part
599                                 does nothing
600                         */
601                         dtime_downcount = 0;
602                 }
603
604                 collisionMoveResult result = collisionMoveSimple(map, gamedef,
605                                 pos_max_d, box_0, stepheight, dtime_part,
606                                 pos_f, speed_f, accel_f);
607
608                 if(result.touching_ground)
609                         final_result.touching_ground = true;
610                 if(result.collides)
611                         final_result.collides = true;
612                 if(result.collides_xz)
613                         final_result.collides_xz = true;
614                 if(result.standing_on_unloaded)
615                         final_result.standing_on_unloaded = true;
616         }
617         while(dtime_downcount > 0.001);
618
619         return final_result;
620 }
621 #endif