bug/requrest: body creation

Hello

I was playing with the library (1.4.3), when weird things stared to happen: assertions failed etc.
The reason is following:

When adding shape to body definition, via b2BodyDef::AddShape( const b2ShapeDef*), the shape definition stores pointer passed as parameter. So it is required to have the shape definition existing in current scope when b2World::CreateBody(const b2BodyDef* ) is called.

IMHO this is a bad design, from following reasons:
1. Docs promised me something along the lines of 'not worrying about object def scope'. OK, I know, docs never are up-to date 😉
2. This definitely breaks encapsulation: actions performed on one object (body def) affects different (thou somehow associated) action performed on another object (world, in this case).

So, my problem popped up in following code layout:

Code:
   b2BodyDef bodyDef;
   createShape( &bodyDef, _outline ); // create shape(s) based on _outline, adds to body using AddShape()
   _pBody = _pWorld->CreateBody(&bodyDef);


where shapes were created on stack in createShape() method, and added to body object created elsewhere and passed as pointer. _outline variable used here is polygon definition not associated with Box2D in any way.

This is minor inconvenience, which should be at least documented. But no problem - code is available 🙂
But, IMO, it would be better to store deep copies of shape defs added to body def. Of course this harms performance, but not that much. If needed, could be improved by creating shared data sections with reference counters (lot of work unfortunately).

Also: adding/removing shapes from existing body would be cool.

Regards!

EDIT: yeah, I know, this is duplicate of: viewtopic.php?f=4&t=108 . Sorry 😳
Your points are well taken, and I'm not entire happy with the design myself. This design has been in place since 1.0.0, so it is not related to 1.4.3.

Quote:
1. Docs promised me something along the lines of 'not worrying about object def scope'.


Good point, I'll update the manual.

Quote:
2. This definitely breaks encapsulation: actions performed on one object (body def) affects different (thou somehow associated) action performed on another object (world, in this case).


This is not quite true. Once the body is created, the world does not reference your shape or body definitions.

Your point about allowing a createShape function is valid. Perhaps I will do a deep copy of shape defs. When bigger shapes come, I can have the shape definition point to some shared data. I wonder if a change to a deep copy now would break some peoples code.

A number of people have asked about adding/deleting shapes. We discussed this in a another thread (forget which one) and it should be possible (but not trivial). I've added this to the TODO list.

Thanks for your feedback!
I doubt if a change to deep copy can break preexisting code - I'm pretty sure that the only functionality a shallow copy offers here that a deep copy wouldn't is the ability to add the exact same shape to a body multiple times, which is a Bad Thing To Do. Otherwise, I can't imagine any difference at all, except for the speed hit during the b2ShapeDef->b2BodyDef copy.

Actually, on the speed front, I wonder if it is even such a big deal anyways - for the more weighty definitions, is there any likely situation where body definition construction would be part of the main loop? I can't think of many reasons you'd want to create a new segment soup every frame, and even if you did you'd already have issues thanks to the b2BodyDef->b2Shape copy. Anyhow, doing something like that would seem to fall pretty fairly outside the normal use of the engine.
I had to work around that in my XML-based loader, as I have to defer object creation until the object gets added to the world (after being fully processed). This became especially acute for "class" objects, as they are purely stored data that can be inherited by "instance" objects. Deep copy would have saved me a bunch of trouble. 😀

(I got stymied in the b2JointDef case, as that expects a b2Body, not b2BodyDef, so I'll have to create some sort of template flavor of b2Joint Def...)

The equivalent on the OpenGL draw list side got away with allocating vertex, normal, color, index, texcoord, and edge array data on the stack (with _alloca) even though the gl array calls take a pointer. It's entirely possible I'm getting away with it because the drawlist processing functionality takes place almost entirely within the scope of a single recursive function, so it hasn't gone out of scope yet at the time the draw operations using them get called.
I'm now considering the creation of unbound shapes. The body def would then contain a list of shapes, not shape defs.

Shapes would be created by the world given a shape def. This would allow for:
- asynchronous collision queries
- user shape destruction (not sure about addition yet)
- user retention of shape pointers for other purposes.

Comments?
If I understand right, you mean that there would be a CreateShape(b2ShapeDef* sd) function that would return the shape (without any lingering reference to the shape def) so that you could do other things with that directly? That sounds logical to me, though I'd find it best if it was still allowed to add a b2ShapeDef to a b2BodyDef directly in the current fashion, as to add another step would break a lot of existing code and complicate the most common uses of the engine. If that ability remains, I'm all for the change.

FWIW, the scoping issue is biting me at the moment while moving convex decomposition code from Java to C++, because one of the utility functions does essentially exactly what was outlined by macson_g (takes a non-convex poly, decomposes it and turns it into a b2BodyDef, which would ideally happen in one step from the user's point of view). In Java, it's not an issue because everything is new-ed onto the heap anyways and just gets garbage collected whenever, but without gc, it's rude for a function to unexpectedly allocate memory that needs to be cleaned up after the fact, and it's a bit inconvenient to require the user to preallocate it. If I'm right that your proposed plan would fix this by putting the shapes on the heap as they are added to the body def, that sounds good to me.
okay, I think I am having the same issue that is happening here but let me describe and have you all give me your input.
Code:
b2BodyDef bd;
for(int i = 0; i < numPolys; ++i)
{
   b2PolyDef pd;
   pd.vertexCount = gons[i].nVertices;
   pd.density = 0.0f;
   pd.friction = 0.2f;
   pd.restitution = 0.3f;
   for(int k = 0; k < pd.vertexCount; ++k)
   {
      pd.vertices[k].Set(gons[i].x[k], gons[i].y[k]);
   }
   bd.AddShape(&pd);
}
body = gPhysSystem.AddBody(&bd);


so gPhysSystem.AddBody() just calls b2World::CreateBody, and body is a b2Body pointer so I can do stuff with the body...not really important just fyi.

My understanding is that to get a body you need a body def and to get a body def you need a shape def, and that a body can have multiple shapes which is accomplished by giving your body def multiple shape defs via the b2BodyDef::AddShape function. But it is my understanding that the shape def needs to stay inscope untill the body is created from the body def, but I'm having a hard time seeing how I can actually reuse the shape def. Is there something I'm missing?

Let me know if you need more explanation, and thanks for your help.
Yeah, you can't re-use a shape def on the same body. All the shape defs must remain in scope until the body is created.

In 2.0 you will create shapes directly from shape defs. The body def will hold a list of shapes, not shape defs. This will eliminate the scoping problem.
Christmas Wish List:

  • Spiderman 3
  • Box2D 2.0
  • Harry Potter 5
  • Wii
  • Box2D 2.0
  • New PC
  • New Bourne movie
  • Box 2D 2.0
😎
Unattached shapes are great idea, and really the only "proper" solution to many problems. You could consider also adding/removing shapes from bodies during simulation. This feature would allow for sane implementation of: breaking bodies! I think every object could follow this pattern. Bodies and joints could be created, then added to the world. But that is completely different issue.

note to allanon: Spiderman 3 is pitiful, and sorry, believe me 😉

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