Extending Box2D with custom joints with ease - Suggestion

Hey guys,

I just extended Box2D with a custom joint that I needed for my application. I think the design of Box2D is great, but I have a suggestion.

Since b2Joint is abstract, I thought that I could add custom b2Joint extending classes without worrying about other parts of Box2D.

However, I had to:
* Add my type to b2JointType in Joint.h
* Add a case to b2Joint::Create and b2Joint::Destroy

This is not that hard, but it's not optimal. It'll be annoying to have to merge my additions to newer releases of Box2D whenever they get released.

How about adding a value to JointType that's named e_customJoint and let the users manage what type it is?

From what I can see, b2Joint::Create and b2Joint::Destroy are only referenced from b2World.

If you rewrote b2World::CreateJoint as a template, you could propagate this to b2Joint::Create, the code would be more efficient and wouldn't require the user to modify Joint.cpp.

For example, b2World::CreateJoint could be:

template<typename T>
b2Joint* b2World::CreateJoint(const T* def)
{
...
b2Joint* j = b2Joint::Create<T>(def, &m_blockAllocator);
...
}

If you add a typedef of the kind of class each Def instantiates, b2Joint::Create could be pretty simple. For example:

struct b2RopeJointDef
{
...
typename b2RopeJoint Joint;
...
};

template<typename T>
b2Joint* b2Joint::Create(const T* def, b2BlockAllocator* allocator)
{
typedef typename T::Joint Joint;
b2Joint* joint = NULL;
void* mem = allocator->Allocate(sizeof(Joint));
return new (mem) Joint((T*)def);
}

I don't want to suggest any template abuse, just this small modification that won't mess up any backwards compatibility; the interface remains the same.

yohan
While I agree that it would be great if Box2D supported self-contained joints, I think it is more important to keep the code as simple as possible, and avoid stuff like templates whenever possible. One of the big strengths of Box2D is that the code is very easy to understand, even for people with no C++ background. It is probably one of the many reasons Box2D has been ported to every widely use programming language, and also the reason I ported it to C# a few years back.

On another note, might I ask what kind of joint you have implemented?
Hi,

I understand.

I read the manual, and noted "Since Box2D is written in C++, you are expected to be experienced in C++ programming. Box2D should not be your first C++ programming project.".

But yeah, your points are valid but not making these kinds of small changes results in having to mod the core of Box2D. Pros and Cons 🙂.

I wanted to create a soft-body using a custom joint connected to all particles.

Sorry for the late reply,

Johan

Original thread: https://box2d.org/forum/viewtopic.php?t=9001