I'm maintaining Farseer Physics Engine, a .net port of Box2D. While trying to simplify the engine and make it more user friendly, I changed the linked lists in the engine to be arrays. However, this change did more that I anticipated; it changed the outcome of the simulation. The simulation used to be exactly like Box2D, but now it is different.
I simply changed code like this:
for (Body body = BodyList; body != null; body = body.Next)
to this:
foreach (Body body in BodyList)
The sequence in which the bodies are solved should not have changed. Can anyone elaborate on this?
So you changed that one line of code and get a different result? Are you changing how bodies are added to the world? It should be easy to confirm the body order.
I changed several lines of code, but all of them were iterations of the linked list. I changed the add and remove method to be:
BodyList.Add(body);
instead of the hookup to the linked list. The order of bodies should have remained unchanged. But if it changed, could that be the reason?
Yes, changing the body order matters. In floating point, adding numbers in different orders leads to different results.
While the topic is under discussion, is there a particular reason that linked lists are used in Box2d as opposed to arrays? I've always thought that linked lists tend to have significantly worse cache performance than arrays, but maybe I'm missing some of the motivation.
I could use an array of body pointers. That would have worse cache performance. First you have to get the array element, then the element data. I would also need some extra logic to ensure the array is big enough.
I'm not sure how I would use an array of bodies. If I resize the array, the pointers become invalid. I could return an index when you create a body, but then the array would have holes as bodies are freed. Traversing the body array would then involve extra logic to see if the body is allocated or destroyed. Also, it may be cumbersome for users to have to use an index rather than the object itself. If I return the current body pointer from the index, there will likely be many bugs where users hold onto that pointer and it becomes invalid.
Finally, when islands are created the set of bodies is likely no to be contiguous in memory.
Ah, of course - that all makes perfect sense, thanks for explaining.
Using arrays (List<>) over linked lists in C# have little to no performance overhead when you do nothing but traverse the list. All the array resizing happens inside the list and the garbage collector makes sure of the rest.
I found out what caused the trouble. It was the fact that Box2D traverses the linked list backwards than the order the bodies are created in.
I converted a single foreach loop to be a reverse for loop inside World.Solve() and now it works perfectly.