2D physics game performance problems (libgdx box2d in android) - java

I am making a 2D car game like earn to die 2. I ve almost completed it. Only problem is the physics engine performance. I am using box2d and there are 10 meters length edge shapes totally building a 100 km terrain. 1 car and usually 30-40 boxes. Number of active dynamic bodies is around 60-100, max 120. Game fluently working in desktop but in android fps drops below 30 when actives bodies are more than 60. There are collisions between car and boxes and boxes each other and both box and car to ground.
I am using libgdx framework 1.9.4 as version, java is 1.7, coding with eclipse neon, windows 7.
this is how I am counting active bodies in world
int num=0;
Array<Body> bodies=new Array<>();
world.getBodies(bodies);
for(Body b:bodies){
if(b.isActive())num++;
}
active dynamic bodies are usually around 100
it is not a drawing issue with all terrain and underground meshes and car and boxes cost 6-7 mili seconds I measured them when box2d debug rendered is off and world step method call costs about 30 mili seconds when there are about 30 boxes while the car is crushing into them
I don't load all game objects (boxes for now) I splitted entire map into chunks map size is 100 km and chunk size is 50 meters when the car is in the next 50 meters ( in the chunk range) I load the boxes from a ready pool ( box2d world representations of the those objects are also pooled and when the boxes are in pool I deactivate their box2d body with setActive(false) and back to true while the chunk is loading)
I applied this chunk system for terrain too. I load all the terrain when the game is loading then deactivate them by setting with this method setActive(false) and when the car goes on trough the map if the chunk range includes car's x axis coordinate I activate the next chunk which contains the terrain static bodies having around 20 fixtures with size of 10 meters, makes the chunk size 200 meters at total.
the green lines are active terrain shapes as you see left and right after a distance are deactivated till the end of the map this part is from around 60 km of the map in middle of 100 km terrain map.
when vehicle moved little more new boxes will load there ahead and old ones will be pooled if they are 20 meters back from the car.
My questions are
1) is this fps (20 fps) normal and expected?(android 7 this is phone specifications http://www.androidpolice.com/2016/02/23/the-general-mobile-gm-5-plus-is-the-most-powerful-android-one-device-yet/)
2) can the 100 km terrain be problem if so how should I manage it?
->I tried activating/deactivating terrain bodies when they out of the screen rectangle.
->I tried hundreds of fixtures on a single body or every terrain piece is as separated body but best performance with I splited 100 km terrain into 200 meters chunks and each chunk is a body and consist of about 20 fixtures.
3) simulating 100 dynamic bodies with huge edge shape terrain is tottaly impossible ? ( but in the earn to die they did it)
4) should I write my own simple physics for only this kind of game (a simple specific one) ?
5) should I use bullet physics instead of box2d for 2D purposes ? is it possible? and will I face with performance problems ?
if you need any code pls comment, I will add.
are there any really fast physics engines I couldn't find on the net if there are do you suggest to change box2D ?
good to note:
I am simulating box2d with constant time step I tried 1/60 1/45 1/30 and 8-3 , 6-
2 as iteration steps.
I use high damping values like .9 for both linear and angular for all bodies.
I also would like to split those boxes into pieces actually I am doing it but without splitting hem when car crushed I am experiencing this fps drop so I disabled it for now.
Only joints are wheel joints and used for wheel of car no more joints in anywhere in map.
Sizes are realistic those boxes are 1.2 meters high.
for boxes and cars polygon shapes used for terrain edge shapes used (chain shape)
velocity threshold is 1 as default in world settings.
if there are any notes I forgot pls comment and I will share.
thank you.

Disclaimer: I can't answer all of your question, and below are just a guess from me.
A few years ago, I developed a game prototype and game library with Java + box2d + plain Opengl (LWJGL).
I think you are facing some issues that occurred to me.
However, with my low experience, I could be wrong.
If experts (readers) think that there are any mistake in my post, please comment below, I will fix it.
My guess
Java is slow / not quite suitable for game.
Disclaimer: There is a lot of argument about this.
I am not an expert enough to put a solid statement here, but I see a lot of my game-prototype run 3x-10x faster in C++ than Java. (with not-so-different algorithm)
Memory fragmentation
As you may already know, even you use pool, it is still very poor compared to C++.
You pool the boxes, but you can't pool everything, e.g. game logic data-structure, vector2D, plain array (new[] often), some horror algorithm in some libraries that you use.
Deactivated bodies still cost memory (intensify memory fragmentation indirectly).
You have a lot of static bodies / high complexity of static body.
You didn't mention how many static body you have, and what are them.
Are you using a high-amount-of-vertices shape for the terrain?
Popular physic engines like Box2D and Bullet are cool at convex shape, and expert at primitive shape, but tend to work poorly with concave shape (e.g. your terrian)
Your shapes are continuously colliding each other.
For example, a stack of 100 boxes cost a lot more computation than 100 boxes scattering around the scene.
Too large world
As far as I know, box2d divide a scene (world) into a grid. If your world is very large, but a lot of body cluster into the same cell of the grid, Box2D will work relatively worse.
It is not limited to Box2D.
Bullet and Ogre3D - in certain configuration - also suffer from this issue.
Answer (guess again)
1) is this fps (20 fps) normal and expected?
I don't know about moblie, but your code can still be optimized in some ways. (see below)
2) can the 100 km terrain be problem if so how should I manage it?
Unfocused chunk -> remove the body (not just deactivated it).
Yes, it is easier said than done, you may just deactivate near chunk, but remove (delete) all bodies in chunk that is far away (> 3 chunk-distance, may be).
If the deleted chunk can come back to the scene, you may have to find a way to save it somewhere. (e.g. save only position of body, size, weight)
3) simulating 100 dynamic bodies with huge edge shape terrain is tottaly impossible ? ( but in the earn to die they did it)
They did, or you just think they did?
In some aspect, programming is an art.
Thing you see can be very different from how they are actually implemented.
You bottleneck may be only the terrain - reduce its level-of-detail may also help.
4) should I write my own simple physics for only this kind of game (a simple specific one) ?
No, except you want to learn && have a lot of time && really love Math.
5) should I use bullet physics instead of box2d for 2D purposes ? is it possible? and will I face with performance problems ?
I think you will still face in some degree.
Constraint is expensive for both Box2D and Bullet.
Are you sure you really need constraint?
In some cases, it can be avoided with compound shape / modify design of the game a bit.
I think if you change to C++ and Bullet, you will gain about at least 3x performance, but I am not sure about it at all.

Related

Game Dev - Working with Screen Coordinates vs World Coordinates

A friend and myself are new to game development, and we had a discussion regarding World Coordinates and Screen Coordinates.
We are following a wonderful online tutorial series for libGDX and they are using a 100 PPM (pixels per meter) scaling factor. If you re-size the screen, the scaling of objects no longer works. My friend is convinced that it is not a problem, and he may be right. But, I'm under the impression that when developing a game, the developers should typically only work with the pre-defined world coordinate system and let the camera transform it to the chosen screen coordinates. I do understand the need for reverse transformations when using mouseclicks, etc. But, the placing and scaling of objects in the world space is my concern.
I would like to reach out to this community for some professional feedback.
Thats one of the bigest problem of almost all Libgdx tutorials. They are great, but the pixel to meter/units conversation is just wrong.
Libgdx offers a great solution for that with Camera and an even better solution with the new Viewport classes (which under the hood work with Camera).
Its is really simple and will solve the problem of different screen sizes/aspect rations.
Just choose a Virtual_Width and Virtual_Height (think about it in meters or similar units).
For exampl, you have humans fighting each other in a 2D platformer game. LEts say our humans are 2m tall, so think about, how much screenspace should one human use? If we say, a human should take 1/10 of the screen space, our virtual height is 10*2=20. Now think about the primary aspect ration you are targeting. Lets say it is 16/9, so you have a virtual width of about 35.
Next, you need to think about what kind of Viewport you want. You sure want to use a Viewport, which supports Virtual_Width and Virtual_Heigth.
You may want a Viewport, which keeps the aspect ratio and fills the rest of the screen (if the screen has different aspect ratio) with black bars (FitViewport) or you may want the Viewport to fill the whole screen by stretching the units (StretchViewport).
Now just create the Viewport with your virtual width and heigth and update it in the resize() method with the given width and height.
Hope it helps.
It's be better name as Units per meter
And when you resize your screen you just set a new projective matrix, so everything works fine )
What you should worry about it's a aspect ratio.
Everything rest is doesn't matter.
So answering your question - Stay with world coordinates.
It also make simple add physics, light calculations, any dimensions ( 1.8 units instead 243 pixels )

Collision Detection in libgdx

My question is mostly related to the theory behind it. I make a 2D game for a project and i detect collisions by using the .overlaps method in the Rectangle class and the collisions are handled beautifully. First of all , is that considered to be a continuous or discrete collision technique. As i'm reading the theory i say it is discrete ,however i'm reading in online articles that the major disadvantage of discrete is that it detects collision after it actually happened. So,my question is the following : is it actually discrete and if it is why i see no disadvantages?
Thanks
This is discreet because we only know if two bounding boxes collided after we check if the imaginary/invisible boxes intersected meaning they already overlapped. So by the time you take action (update) due to that collision, the objects are not in the collided position. Worse case, if they are not in relative speed, they can pass through. Think of the classic helicopter game where you dodge obstacles by going up and down. Say you put the velocity of the chopper on x really high, depending on your frame rate which depends on the hardware, you will see different positions of actual collision. For continuous, one object has to be aware of the physics properties of the other objects it may collide with to predict possible collision.
In reality, for 2d games like the helicopter game I mentioned, it really doesn't matter much. You can simulate the result of the collision by doing changes on an object's rotation, velocity, gravity and through some nice animations. If your game objects have abstract shapes, you should use something like box2d. There's a good Intersector class as well.
Also, you can experiment with different bounding box sizes (bounds) of an object rather than creating the bounding box of the object equal to its width and height.

GTA2 like Car Physics, but extremely simplified

Okay so this problem has been bothering me for the longest time. Can anyone show me or point me to an algorithm that can control a car like that of GTA2? After 3 days of research all I could come up with was all of these algorithms for using pivot and joints on the wheels and separate wheels and such. Is that the only way to achieve simple car movement like that of GTA2?
I want to be able to use the algorithm on a rectangle without wheels but still be able to have the car drift. Is that possible? By the way, I am usign Box2D for the 2D game.
I know this is more suitable for gamedev but for some reason I can't post questions .
A simple answer that can turn into something quite big so I will try to explain by presenting different points in an increasing order of sophistication. I will be assuming a basic knowledge of physics.
Assume a fixed turning radius (not too bad if you are using a keyboard, quite annoying if you have an analog controller). Nothing like trying out different positions to find out what radius feels good.
Assume that you have wheels that are initially facing forward and as you press the turn key they progressively turn to the maximum possible. This basically means decreasing the radius from infinity to your smallest possible radius (you can figure out the relationship between the angle of the wheels and the radius easily). If you have an analog controller then the radius should be controlled by the continuous values of the analog input.
Let the forces enter! When you are turning in a car, you only turn due to a centripetal acceleration. That centripetal acceleration is caused by a force which is actually the friction of the car with the road. You can consider the friction a constant and the mass of your vehicle constant without major problems then you have a relatioship between the velocity of the car and the critical radius (the minimum radius you can turn given the velocity). The centripetal acceleration is a=v^2/r = Friction/mass so the critical radius r = v^2*mass/Friction. You can consider that no matter how much you turn you vehicle will drift and, at maximum, describe this curve. This should give you a nice simulation but still not the "losing control" feeling. For this see the next point! circular motion
The theory is exactly the same as in the point before but the main thing is that Friction in reality is not constant. In fact, the static friction will always be higher that the kinetic friction. In practice, you should have a static friction and a (smaller) kinetic friction. You calculate r according to the static friction and when your velocity is too big to achieve that r (this is when you would drift) you start calculating the new r using the kinetic friction. This will give you the losing control feeling but the vehicle will still not spin. Friction
In order to see the spin, you would have to consider the forces applied in every wheel (it is the fact that the different wheels are under different forces that makes the car spin) and consider some more advanced physics such as which wheels are the driving wheels and also consider the kinetic friction not a constant. However I believe this is out of your scope.
Alternatively you can do something that GTA2 seemed to do. The moment you know you are going to drift or are drifting too much (you set a threshold here) just programmatically make the vehicle lose control and spin.
Hope this helps, if you have any specific doubt just ask.
I found the http://www.banditracer.eu/carexample/ demonstrated a simple example for using Box2D to show car movement. The http://www.banditracer.eu/ has an open source game that you can observe to see if it has the drifting movement your looking for. You can check out the code and see how they handled the drifting movement and do the same for your project.

Bodies overlapping in 2D Physics simulation (Java)

I made a program in Java where circles can bounce into each other and gravitate towards each other.
For the most part (few circles on the screen), there are no noticeable bugs. The problem starts to happen when there is a large amount of circles on screen. Sometimes, the circles will overlap if it gets too crowded. It's as if the weight of all the other circles are crushing the circles together, causing them to overlap. Of course, there program doesn't know anything about how much a circle weighs, so it's not really crushing. Most likely, the piece of logic that handles resolving collisions is not able to handle crowded situations.
Circles are stored in an array, and each circle goes through the array using a for loop, comparing itself to the other circles. If the distance between the center of this circle and the center of the other circle is less than the sum of their radii, then the circles are colliding. The velocities of both circles are updated using an equation for collisions.
I think the problem occurs because if a circle is surrounded, it might receive an updated velocity into the circle behind it, while the circle behind it also receives an updated velocity into the former circle. In other words, the two circles get told to move toward each other, even though they are already touching. Once they overlap this way, I don't know why they don't undo their overlap.
I've tried restoring touching scenario if they are overlapping by finding the distance they are overlapped, then moving them apart from each other; each moves half the overlap distance apart. This doesn't change the circle's velocity, only their position.
This still doesn't solve the problem. If the circle is surrounded, and it overlaps with one of it's neighboring circles, its position is changed so they aren't overlapping, but this new position may cause it to overlap with another circle. Same problem.
If there was no gravity pushing the circles together, they would eventually spread out and resolve their overlapping issues, but the gravity prevents this from happening.
Further information:
Gravity is not taken into account when calculating new velocities after a collision.
Sounds like your hunches about what is causing the problem are correct in both cases.
Unfortunately, there's no easy way to fix this issue - it pretty much means rewriting your whole collision detection & resolution code from scratch. You have to work out the exact timing of the first collision, update everything only that far, resolve the collision (do your velocity update) then work out the exact timing of the next collision, then repeat...
Writing a good physics engine is hard, there's a good reason that there are many textbooks on the market about this subject!
The cheap 'fix' for your problem is to reduce the time interval for updates - e.g. instead of updating the physics in 33ms steps (~30fps), try updating in 16ms steps (~60fps). This won't prevent the problem, but it will make it much less likely to occur. Halving the time step will also double the time the processor has to spend doing physics updates!
If you use the cheap fix, the time step which will work best for you will be determined by how frequently collisions occur - more collisions means smaller time steps. How frequently collisions occur basically depends on how fast the circles tend to move and their population density (how much of a given area is filled by circles).
UPDATE: A little more info on the 'proper' approach.
The update would go something like this:
Start updating a frame. Let's say we want to update as far as time tF.
For every pair of circles, work out when you would expect a collision to occur (ignoring all the other circles). Let's call this time tC.
Find the smallest value of tC. Let's say this is for the collision between circles A and B, and let's call that collision cAB.
If tC <= tF, update all of the circles up to time tC. Otherwise, go to step 6.
Resolve collision cAB. Go back to step 2!
Update all the circles to time tF.
As you might imagine, this can get quite complicated. Step 2 can be quite tricky (and coputationally expensive) for non-circular objects (especially once you include things like angular momentum, etc.) although there are a lot of tricks you can do here to speed it up. It's also basically impossible to know how many times you'll be looping between steps 2 and 5.
Like I said, doing good physics simulation is hard. Doing it in real-time is even harder!

JBox2D collisions not bouncing

I have an Android application using JBox2D for physics simulation. The only dynamic object is a 0.07m radius circle, as well as several static circles and rectangles in a total game area of about 20m by 20m. I'm also using a few custom forces through the ApplyForce method.
Whenever any bodies collide, they do collide correctly however they don't bounce; everything just thuds together. All bodies have their densities, frictions and restitutions set (some objects have a restitution greater than 1).
Does anyone have any ideas why these collisions aren't working? I think it might be because the bodies aren't moving fast enough for JBox2D to count as proper collisions (there is a cutoff in Box2D).
Thanks!
setting Settings.velocityThreshold = 0.0001f; (or very small) solved it for me.
I found a partial solution to this - Box2D (at least JBox2D) ignores restitution if the velocity is below a certain threshold - by scaling all my objects up by a factor of 10, the threshold becomes relatively lower, and objects bounce.

Categories

Resources