The memory leaks in Box2d are all about object pooling. When you have mass of objects, box2d will generate lots of object instances (like b2Contact and b2DynamicTreeNode), and even after they are destroyed, they are still there - in the pools, they will be garbage collected only after they have been pulled out the pool. This will cause very high memory consumption and frequent garbage collection.
I found two positions of memory leak in Box2d.
One for the pooling of b2Contacts in b2ContactsFactory. The b2Fixture and b2Contact references is not immediately cleared in b2ContactsFactory.Destroy function. The codes below can clear them correctly:
Code: Select all
public function Destroy(contact:b2Contact) : void{
if (contact.m_manifold.m_pointCount > 0)
{
contact.m_fixtureA.m_body.SetAwake(true);
contact.m_fixtureB.m_body.SetAwake(true);
}
var type1:int = contact.m_fixtureA.GetType();
var type2:int = contact.m_fixtureB.GetType();
//b2Settings.b2Assert(b2Shape.e_unknownShape < type1 && type1 < b2Shape.e_shapeTypeCount);
//b2Settings.b2Assert(b2Shape.e_unknownShape < type2 && type2 < b2Shape.e_shapeTypeCount);
var reg:b2ContactRegister = m_registers[type1][type2];
if (true)
{
reg.poolCount++;
contact.m_next = reg.pool;
reg.pool = contact;
// Bug fix
contact.m_fixtureA = null;
contact.m_fixtureB = null;
contact.m_nodeA.contact = null;
contact.m_nodeA.prev = null;
contact.m_nodeA.next = null;
contact.m_nodeA.other = null;
contact.m_nodeB.contact = null;
contact.m_nodeB.prev = null;
contact.m_nodeB.next = null;
contact.m_nodeB.other = null;
}
var destroyFcn:Function = reg.destroyFcn;
destroyFcn(contact, m_allocator);
}
And there is also memory leak in b2DynamicTree.FreeNode function. the b2DynamicTreeNode will maintain a b2Fixture instance in userData variable. The code below can clear it correctly:
Code: Select all
private function FreeNode(node:b2DynamicTreeNode):void
{
node.parent = m_freeList;
m_freeList = node;
// Bug fix
node.userData = null;
}
These codes are all tested in my game, hope it helps
😉