Browse Source

Wait until the end of a physics update before destroying bodies (issue #193)

Bart van Strien 14 years ago
parent
commit
fafe0d7039

+ 5 - 0
src/modules/physics/box2d/Body.cpp

@@ -329,6 +329,11 @@ namespace box2d
 		return 2;
 	}
 
+	void Body::destroy()
+	{
+		world->destroyBody(this);
+	}
+
 } // box2d
 } // physics
 } // love

+ 5 - 0
src/modules/physics/box2d/Body.h

@@ -346,6 +346,11 @@ namespace box2d
 		* Get the World this Body resides in.
 		*/
 		World * getWorld() const;
+		
+		/**
+		 * Mark the body for destruction
+		 **/
+		void destroy();
 	private:
 
 		/**

+ 13 - 0
src/modules/physics/box2d/World.cpp

@@ -123,6 +123,14 @@ namespace box2d
 		persist.process();
 		remove.process();
 		result.process();
+		
+		// Really destroy all marked bodies.
+		for (std::vector<Body*>::iterator i = destructBodies.begin(); i < destructBodies.end(); i++)
+		{
+			Body * b = *i;
+			b->release();
+		}
+		destructBodies.clear();
 	}
 
 	void World::Add(const b2ContactPoint* point)
@@ -272,6 +280,11 @@ namespace box2d
 		t.upperBound = scaleUp(aabb.upperBound);
 		return t;
 	}
+	
+	void World::destroyBody(Body * b)
+	{
+		destructBodies.push_back(b);
+	}
 
 } // box2d
 } // physics

+ 10 - 0
src/modules/physics/box2d/World.h

@@ -40,6 +40,7 @@ namespace box2d
 {
 
 	class Contact;
+	class Body;
 
 	/**
 	* The World is the "God" container class,
@@ -83,6 +84,9 @@ namespace box2d
 
 		// The length of one meter in pixels.
 		int meter;
+		
+		// The list of to be destructed bodies.
+		std::vector<Body*> destructBodies;
 
 	public:
 
@@ -241,6 +245,12 @@ namespace box2d
 		* @return The scaled AABB.
 		**/
 		b2AABB scaleUp(const b2AABB & aabb);
+		
+		/**
+		 * Mark a body for destruction.
+		 * To be called from Body
+		 **/
+		void destroyBody(Body * b);
 
 	};
 

+ 1 - 1
src/modules/physics/box2d/wrap_Body.cpp

@@ -462,7 +462,7 @@ namespace box2d
 		p->own = false;
 
 		Body * t = (Body *)p->data;
-		t->release();
+		t->destroy();
 
 		return 0;
 	}