Dynamic Mesh -> what Class ?

Discuss any questions about BEPUphysics or problems encountered.
Pavi
Posts: 12
Joined: Wed Feb 22, 2012 12:08 am

Dynamic Mesh -> what Class ?

Post by Pavi »

Hello,

i have a couple of problems that i am not able to solve on my own.

The first:

I am trying to add various dynamic objects of different shapes. For that I am using the MobileMesh Class right now, which makes a lot of problems. I have read a lot of forum threads, that talk about the rubustness of this Meshclass and that the scale is a factor. After increasing the scale of the scene, the result is better, but still not optimal and since it needs a lot of Scaleupdating in various parts, the work is not worth the result.

So my Question is, if and how to use convex Hull Shapes or any other solution that might give better results. Is there something like automatic fitting of compound primitive shapes?


The second:

When the Amount of objects (its the MobileMesh ones) reach a certain amount, the caracter controler out of the characterPlaygroundDemo sample starts to bug around. It starts to feel very laggy like in onlinegames where you get reset to previous positions and set forward because of the latency. Does this have anything to do with me using the multithreaded approach and the character controler not accessing the bufferd states?


The Third:

if the CharacterControler falls too fast, it manages to break through static meshes. Any solution?



So thats it for now,sry for bad english.
At last I just wanted to say how much I like the engine: A LOT!

regards
Pavi
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Dynamic Mesh -> what Class ?

Post by Norbo »

I am trying to add various dynamic objects of different shapes. For that I am using the MobileMesh Class right now, which makes a lot of problems. I have read a lot of forum threads, that talk about the rubustness of this Meshclass and that the scale is a factor. After increasing the scale of the scene, the result is better, but still not optimal and since it needs a lot of Scaleupdating in various parts, the work is not worth the result.
While simple primitives and compounds of simple primitives are more robust than a MobileMesh, a MobileMesh is still quite robust. If you're experiencing significant problems, it's likely that there's a core problem that needs to be addressed. Scale is indeed one possible factor. Note that you can modify the engine's interpretation of scale- check out the development fork BEPUphysicsDemos ConfigurationHelper.ApplyScale method to see an example. It's still best to stick within the default scale as that avoids some other oddities and numerical issues, but the engine can handle a big range.

It's important to handle these core issues directly, because simply switching from a MobileMesh to ConvexHulls or something will not truly solve the problem. It might hide it a bit, but it still might crop up here and there.

It might also be that the mesh is confusing the MobileMesh solidity initialization system. Sometimes, numerical issues can make it choose the wrong sidedness when solidity is enabled. Try using another solidity state- Counterclockwise or Clockwise preferably- to see if it improves. It will no longer have a solid volume, but it will run faster (and more robustly if the initializer is getting confused).

Still though, unless a MobileMesh is truly necessary, switching to a simpler representation after addressing any core issues is advisable.
So my Question is, if and how to use convex Hull Shapes or any other solution that might give better results. Is there something like automatic fitting of compound primitive shapes?
ConvexHullShapes will provide a convex wrapping around the mesh's vertices, and if that is sufficient, it's a good option. Simplifying the mesh is a good idea as well because the cost of collision detection with convex hulls is proportional to the number of vertices on the surface of the hull. A single ConvexHull can be an order of magnitude faster than a MobileMesh depending on the data.

Compound shapes can be used to bundle multiple shapes, like convex hull shapes or box shapes, into a single rigid object. There is no automatic primitive fitting for compound shapes. However, if the mesh is split into pieces and each one of those pieces is used to create a convex hull, the resulting compound will be very well fit. An algorithm like HACD would be great to automate this (I'd like to implement it some time, I just haven't had the time yet- if anyone reading this wants to contribute an implementation, that would be great :)).

If possible, using even simpler primitives like boxes and spheres will be even faster. Compounds of these simple shapes will be faster than compounds created from convex hulls created from tons of vertex data.

Here's a general ranking of shapes:

(Most expensive and best fitting)
-MobileMeshShape
-CompoundShape of ConvexHullShapes
-CompoundShape of exotic shapes like WrappedShapes, MinkowskiSumShapes, or TransformableShapes.
-CompoundShape of simple shapes like BoxShape, SphereShape, CylinderShape, etc.
-Single ConvexHullShape
-A single exotic shape like a WrappedShape, MinkowskiSumShape, or TransformableShape.
-Single simple shape like BoxShape, SphereShape, CylinderShape, etc.
(Least expensive and worst fitting)
When the Amount of objects (its the MobileMesh ones) reach a certain amount, the caracter controler out of the characterPlaygroundDemo sample starts to bug around. It starts to feel very laggy like in onlinegames where you get reset to previous positions and set forward because of the latency. Does this have anything to do with me using the multithreaded approach and the character controler not accessing the bufferd states?
If you are using asynchronous updating, that might contribute a little jitter- or even the occasional corrupted state- but that wouldn't explain warping around in a small area. Note that asynchronous updating is a separate concept from internal multithreading. When using asynchronous updating, the engine is running in parallel to other logic which uses information computed by the engine. Internal multithreading means the engine is capable of using threads to speed up computation. If you aren't doing asynchronous access and you aren't doing illegal actions from within immediate events executed on the internal threads, threading is not the source.

The CharacterController itself runs within the engine, so even if it was asynchronously updating, the CharacterController doesn't know or care as all of its actions take place within the physics thread(s). External control over movement commands would still need to be properly synchronized, of course.

In the absence of any threading oddities, my guess would be some bad initialization in the mobile meshes. If the mesh has bad geometry or just manages to confuse the solidity sidedness computation, things could get weird. Inconsistent contact generation could produce the mentioned effects. Setting a nonsolid sidedness as mentioned earlier in this post would be a good diagnostic. Scale issues can also cause some inconsistencies, but probably not of this particular kind.

However, scale/solidity issues should be just as bad with a single object as they are with 500 objects; they are not based on performance. If the problem seems to truly be linked to performance to the object count, something stranger might be going on.
if the CharacterControler falls too fast, it manages to break through static meshes. Any solution?
The CharacterController body should have its PositionUpdateMode set to Continuous by default by the constructor, so it shouldn't be able to fly through objects. I suspect this is related to the previous issues (sidedness confusion or scale issues are probable).
At last I just wanted to say how much I like the engine: A LOT!
:)
Pavi
Posts: 12
Joined: Wed Feb 22, 2012 12:08 am

Re: Dynamic Mesh -> what Class ?

Post by Pavi »

Thank you for the very extended help.

Sadly nothing you suggested helped me till now.

To get an idea of your interpretation of rubustness,so that i dont chase a problem that is not to be found, here is an screenshot showing the problem

the balls are a loaded testmodel (~200 Tris) that use MobileMesh. The ground is StaticMesh and they rolled into a pit of this mesh.
Image

I realized, that the character controler movement lagging is not a matter of performance, rather it starts when the balls intersect and stops as they are separate again. The Problem with the caracter controler falling through the static Mesh is unrelated and occurs without MobileMeshes in the Scene (just the staticMesh and the CC).

What i tried:

Solidity - the Problem was a lot worse when it was using Solid. The Objects just stuck half way through in the ground and collision with these carrots tended to catapult the CC through the level. So its already set to Counterclockwise as is the Ground. Any other setting is worse.

Your scale suggestion - tried it and could not see a difference with various settings for scale. Does the scale constant need to be >1 or <1 to achieve a positive effect?
Also

Code: Select all

CollisionDetectionSettings.ContactInvalidationLength 
CollisionDetectionSettings.ContactMinimumSeparationDistance

could not be found. Is this maybe an old example or what am i doing wrong (included everything the example did)?
Note that asynchronous updating is a separate concept from internal multithreading.
Of course, got the words mixed up ^^ i ment asynchronous. Tried to deactivate both multithreading and asynchronous updating, which did not solve the Problem, but made me realize that the simulation runs <60 fps with that amount of Balls.

Sometimes when i start the application it crashes at Thread.Sleep(0); "Object reference not set to an instance of an object.". But after restart it works.

I tried ConvexHullShape but it refuses to work

Code: Select all

TriangleMesh.GetVerticesAndIndicesFromModel(model, out staticTriangleVertices, out staticTriangleIndices);
ConvexHullShape cvh = new ConvexHullShape(staticTriangleVertices);
Entity newEnt = new Entity(cvh);
space.add(newEnt);
Thx again, I did not expect such a long response

regards
Pavi
Pavi
Posts: 12
Joined: Wed Feb 22, 2012 12:08 am

Re: Dynamic Mesh -> what Class ?

Post by Pavi »

So i managed to create ConvexHullShapes, which work fine and I set up the Modeldrawer. After adding a few ConvexHullShapes, the Modeldrawer starts to bug around and every further created object is not rendered (empty Boundingbox)

Image

what is going on?

Code: Select all

    
public initBepu(Game game,GraphicsDevice graphics, Camera cam)
        {
 space = new Space();


            //Asynchronous
            physicsThread = new Thread(PhysicsLoop);
            physicsThread.IsBackground = true;
            physicsThread.Start();
            space.ThreadManager.AddThread();
            space.BufferedStates.Enabled = true;
            


            //Multithreading
            space.Solver.AllowMultithreading = true;

            if (Environment.ProcessorCount > 1)
            {
                //On windows, just throw a thread at every processor.  The thread scheduler will take care of where to put them.
                for (int i = 0; i < Environment.ProcessorCount; i++)
                {
                    space.ThreadManager.AddThread();
                }
            }
            
            //Physicssettings
            space.ForceUpdater.Gravity = new Vector3(0, -9.81f, 0);
            
            
            //Solversettings
            space.TimeStepSettings.TimeStepDuration = 1 / 60f;

            MotionSettings.DefaultPositionUpdateMode = PositionUpdateMode.Continuous;
            MotionSettings.UseExtraExpansionForContinuousBoundingBoxes = true;
            SolverSettings.DefaultMinimumIterations = 50;
            space.Solver.IterationLimit = 5;

            //float scale = 0.1f;
 
            //CollisionResponseSettings.MaximumPositionCorrectionSpeed *= scale;
            //CollisionResponseSettings.BouncinessVelocityThreshold *= scale;
            //CollisionResponseSettings.StaticFrictionVelocityThreshold *= scale;
            //CollisionDetectionSettings.ContactInvalidationLength *= scale;
            //CollisionDetectionSettings.ContactMinimumSeparationDistance *= scale;
            //CollisionDetectionSettings.MaximumContactDistance *= scale;
            //CollisionDetectionSettings.DefaultMargin *= scale;
            //CollisionDetectionSettings.AllowedPenetration *= scale;

            LineDrawer = new BasicEffect(graphics);
            if (graphics.GraphicsProfile == GraphicsProfile.HiDef)
                ModelDrawer = new InstancedModelDrawer(game);
            else
                ModelDrawer = new BruteModelDrawer(game);

            ContactDrawer = new ContactDrawer(game);
            BoundingBoxDrawer = new BoundingBoxDrawer(game);
}

void PhysicsLoop()
        {
            double dt;
            double time;

            double previousTime = Stopwatch.GetTimestamp() / Stopwatch.Frequency; //Give the engine a reasonable starting point.

            while (true)
            {
                time = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; //compute the current time
                dt = time - previousTime; //find the time passed since the previous frame
                previousTime = time;

                space.Update((float)dt);

                Thread.Sleep(0); //Explicitly give other threads (if any) a chance to execute
            }
        }
This is the code I use to create the space and all the settings/updating involved. I Checked all the Demogames for things they do different, tried out everything, and I'm kind of frustrated right now, because since 2 days nothing changed anything. I just dont see what i am doing different to the examples, that run perfectly.

regards
Pavi
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Dynamic Mesh -> what Class ?

Post by Norbo »

To get an idea of your interpretation of rubustness,so that i dont chase a problem that is not to be found, here is an screenshot showing the problem

the balls are a loaded testmodel (~200 Tris) that use MobileMesh. The ground is StaticMesh and they rolled into a pit of this mesh.
...
I realized, that the character controler movement lagging is not a matter of performance, rather it starts when the balls intersect and stops as they are separate again. The Problem with the caracter controler falling through the static Mesh is unrelated and occurs without MobileMeshes in the Scene (just the staticMesh and the CC).
That is not expected behavior.

Are each of those individual balls mobile meshes? Does the character only do strange things when standing on mobilemeshes undergoing penetration, or does it do strange things always- even when on a StaticMesh?

I don't have a good explanation for the character falling through the StaticMesh at this point.
Your scale suggestion - tried it and could not see a difference with various settings for scale. Does the scale constant need to be >1 or <1 to achieve a positive effect?
If scaling issues are present, applying a greater scale will allow the engine to handle larger shapes better. Applying a smaller scale will allow the engine to handle smaller shapes better. If there are no scaling issues present, then the scaling won't help (or might even hurt).
Also
CollisionDetectionSettings.ContactInvalidationLength
CollisionDetectionSettings.ContactMinimumSeparationDistance

could not be found. Is this maybe an old example or what am i doing wrong (included everything the example did)?
It's actually a very new example that's designed for the version currently in development. In v1.1.0 and before, those two lines have a "Squared" appended on the end of their names. To scale properly, the scaling factor should be squared for those two properties too.
So i managed to create ConvexHullShapes, which work fine and I set up the Modeldrawer. After adding a few ConvexHullShapes, the Modeldrawer starts to bug around and every further created object is not rendered (empty Boundingbox)
...
what is going on?
Unfortunately, I have no idea. Those lines can happen when a single batch exceeds some limits, but convex hulls should not be capable of doing this unless each one has an immense number of triangles. Further, it looks like some of the 'triangle strings' are only associated with the StaticMesh and not some convex hull graphic. That's very strange.

Code: Select all

            //Asynchronous
            physicsThread = new Thread(PhysicsLoop);
            physicsThread.IsBackground = true;
            physicsThread.Start();
            space.ThreadManager.AddThread();
            space.BufferedStates.Enabled = true;
            


            //Multithreading
            space.Solver.AllowMultithreading = true;

            if (Environment.ProcessorCount > 1)
            {
                //On windows, just throw a thread at every processor.  The thread scheduler will take care of where to put them.
                for (int i = 0; i < Environment.ProcessorCount; i++)
                {
                    space.ThreadManager.AddThread();
                }
            }
This is creating a asynchronously updating space and adding the number of logical cores in your computer + 1 to the space to use as internal computing threads. It will function, but suboptimally.

Instead, be sure to only add as many threads as the engine should use. For example, if the graphics/logic use 1 core and you've got 4 total logical cores, then BEPUphysics could be given 3 threads safely. Giving the engine more would cause it to conflict with other threads- some core would have to do more than one thread's worth of work. Built-in load balancing lessens the impact, but it will still suffer overhead from unnecessary work splitting and contention.

Also, space.Solver.AllowMultithreading defaults to true.
MotionSettings.UseExtraExpansionForContinuousBoundingBoxes = true;
SolverSettings.DefaultMinimumIterations = 50;
space.Solver.IterationLimit = 5;
Unless there's a demonstrated need for it, I would recommend disabling UseExtraExpansionForContinuousBoundingBoxes. It can be quite a bit more expensive.

Additionally, setting the default minimum iterations to 50 will do nothing if the space.Solver.IterationLimit is set to 5- the solver can only execute up to IterationLimit iterations. Unless there's a complicated articulated structure or a simulation where you know you can use less accuracy, I would recommend keeping these values at their defaults.


There appear to be a lot of different issues in play. I would recommend isolating pieces and testing them out in the BEPUphysicsDemos one at a time. If you can replicate a problem reliably in the BEPUphysicsDemos, I can take a look at it and give more precise advice.
Pavi
Posts: 12
Joined: Wed Feb 22, 2012 12:08 am

Re: Dynamic Mesh -> what Class ?

Post by Pavi »

Norbo wrote:
Are each of those individual balls mobile meshes? Does the character only do strange things when standing on mobilemeshes undergoing penetration, or does it do strange things always- even when on a StaticMesh?
Yes they are each mobile meshes in the first screenshot. the ModelDrawer bugs are not created when using mobile meshes. The character does just lag a alot and changes speed (no teleporting), but only when mobilemeshes penetrate each other. The CC stands on StaticMesh while that happens.

Well, thanks for your help, I'm gonna start over and constantly check when something starts to fail.
Pavi
Posts: 12
Joined: Wed Feb 22, 2012 12:08 am

Re: Dynamic Mesh -> what Class ?

Post by Pavi »

Code: Select all

using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Threading;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


using CharacterControler.Character;
using BEPUphysics;
using BEPUphysics.MathExtensions;
using BEPUphysics.CollisionShapes.ConvexShapes;
using BEPUphysics.DataStructures;
using BEPUphysics.Collidables;

using BEPUphysicsDrawer.Lines;
using BEPUphysicsDrawer.Models;

namespace Sensoria
{
    public class Sensoria : Microsoft.Xna.Framework.Game
    {
        CharacterControllerInput character;
        GraphicsDeviceManager graphics;

        Camera cam;

        KeyboardState PreviousKeyboardInput;
        GamePadState PreviousGamePadInput;

        public Space space;

        public ModelDrawer ModelDrawer;
        public BoundingBoxDrawer BoundingBoxDrawer;
        public BasicEffect LineDrawer;



        public Sensoria()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            space = new Space();
            space.ForceUpdater.Gravity = new Vector3(0, -9.81f, 0f);

            if (Environment.ProcessorCount > 1)
            {
                for (int i = 0; i < Environment.ProcessorCount-1; i++)
                {
                    space.ThreadManager.AddThread();
                }
            }
        }

        protected override void Initialize()
        {
            cam = new Camera(this);
            Vector3 startPosition = new Vector3(0.0f, 400.0f, 0.0f);
            cam.Position = startPosition;
            Components.Add(cam);

            //LOADING CHARACTER CONTROLER
            character = new CharacterControllerInput(space, cam);
            character.Activate();
            character.CharacterController.Body.Tag = "noDisplayObject";
            character.UseCameraSmoothing = true;


            LineDrawer = new BasicEffect(GraphicsDevice);
            if (graphics.GraphicsProfile == GraphicsProfile.HiDef)
                ModelDrawer = new InstancedModelDrawer(this);
            else
                ModelDrawer = new BruteModelDrawer(this);

            //ContactDrawer = new ContactDrawer(gameIn);
            BoundingBoxDrawer = new BoundingBoxDrawer(this);


            base.Initialize();
        }

        protected override void LoadContent()
        {
            ///CREATE LEVEL
            Model newModel = Content.Load<Model>("playground");
            Vector3[] staticTriangleVertices;
            int[] staticTriangleIndices;
            TriangleMesh.GetVerticesAndIndicesFromModel(newModel, out staticTriangleVertices, out staticTriangleIndices);

            var newEntity = new StaticMesh(staticTriangleVertices, staticTriangleIndices,
                new AffineTransform(
                Vector3.One,
                Quaternion.Identity,
                Vector3.Zero));

            newEntity.Sidedness = TriangleSidedness.Counterclockwise;

            space.Add(newEntity);
            ModelDrawer.Add(newEntity);

        }

      
        protected override void UnloadContent()
        {
        }

    
        protected override void Update(GameTime gameTime)
        {
            //update Bepu
            space.Update();
            ModelDrawer.Update();

            KeyboardState keyState = Keyboard.GetState();
            GamePadState gamePadState = GamePad.GetState(new PlayerIndex(), new GamePadDeadZone());

            character.Update(space.TimeStepSettings.TimeStepDuration, PreviousKeyboardInput, keyState, PreviousGamePadInput, gamePadState);

            PreviousKeyboardInput = keyState;
            PreviousGamePadInput = gamePadState;
            
            base.Update(gameTime);
        }


        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            LineDrawer.LightingEnabled = false;
            LineDrawer.VertexColorEnabled = true;
            LineDrawer.World = Matrix.Identity;
            LineDrawer.View = cam.View;
            LineDrawer.Projection = cam.Projection;

            ModelDrawer.Draw(cam.View, cam.Projection);
            BoundingBoxDrawer.Draw(LineDrawer, space);
        }
    }
}

To me this is the most basic code i need for the character controler moving on a static mesh. As you can see the start position is at y=400 and that drop is high enough to fall through the level ~80% of the times. The other 20% im stuck in the level and can jump on the surface. at this basic stage there are already Problems, so I'm clueless.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Dynamic Mesh -> what Class ?

Post by Norbo »

It seems I am unable to reproduce the issue in the BEPUphysicsDemos.

Could you reproduce the problem in a runnable BEPUphysicsDemos demo so that I can try it out directly? It allows me to test and diagnose much faster.
Pavi
Posts: 12
Joined: Wed Feb 22, 2012 12:08 am

Re: Dynamic Mesh -> what Class ?

Post by Pavi »

i did reproduce it. I made following changes to the StaticMeshDemo (Shift + 1):

CharacterController.cs:

Body = Body = new Cylinder(Vector3.Zero, 1.7f, .6f, 10); --> Body = Body = new Cylinder(Vector3.Zero, 1.7f, .2f, 10);

StaticMeshDemo.cs

game.Camera.Position = new Vector3(0, 10, 40); -> game.Camera.Position = new Vector3(0, 400, 0);

remove the Box creation


I changed the Cylinder width because the final levels will be pretty narrow.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Dynamic Mesh -> what Class ?

Post by Norbo »

That's interesting- I've looked into it and this is caused by a very particular interaction of factors. Continuous collision detection correctly identifies the collision, but the contacts computed due to the collision are not sufficient to stop the character from going through. The slenderness of the cylinder allows the character to penetrate the ground more and encourages border impacts to compute horizontal contacts.

A combination of impact angle, relative triangle configuration at the impact site on the mesh, and the one-sidedness of the mesh then stop the triangle border behavior improvement system from catching the failure. The final effect is the character halting as CCD tries to stop it from going through, until eventually it gives up. Setting the mesh to double sided should tend to 'catch' the cylinder, but it still won't behave perfectly.

Given the combination of factors required to cause this, I would expect it to be fairly rare (as in, it won't happen in many locations).

Here's some temporary workarounds. Any one of this should be sufficient:
-Fatten up the character. This lets the CCD system stop the character sooner, meaning contacts are more likely to be vertical.
-Decrease the Space.TimeStepDuration from 1/60f to something like 1/120f instead. More frequent time steps mean the character can't get so far through.
-Avoid dropping the character at high speeds on triangle borders.

I'll see if I can get a solution into the development fork soon.

However, this issue does not explain the other problems you are experiencing. If you can reproduce the rest in a demo, I could look at those too.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Dynamic Mesh -> what Class ?

Post by Norbo »

I've uploaded a new version to the development fork. It appears to fix the specific case in question. I'm now testing it and working on making some related improvements to handle objects being stuck between triangles in general (whether they spawned there, got rammed into place, or otherwise).
Pavi
Posts: 12
Joined: Wed Feb 22, 2012 12:08 am

Re: Dynamic Mesh -> what Class ?

Post by Pavi »

Hi,

I recreated the MobileMesh Problems.

Code: Select all

             int numColumns = 4;
            int numRows = 4;
            int numHigh = 1;
            float separation = 8;

            ball = game.Content.Load<Model>("360 thick Sphere");
            TriangleMesh.GetVerticesAndIndicesFromModel(ball, out staticTriangleVertices, out staticTriangleIndices);

            MobileMesh toAdd;
            for (int i = 0; i < numRows; i++)
                for (int j = 0; j < numColumns; j++)
                    for (int k = 0; k < numHigh; k++)
                    {
                        toAdd = new MobileMesh(staticTriangleVertices, staticTriangleIndices,
                        new AffineTransform(new Vector3(0.01f,0.01f,0.01f),
                         Quaternion.Identity,
                         new Vector3(
                            (separation * i - numRows * separation / 2) - 200,
                            30f + k * separation,
                            separation * j - numColumns * separation / 2 )),
                         MobileMeshSolidity.Counterclockwise, 10);
                        Space.Add(toAdd);
                    }
just add this to the same Demo instead of the Box creation. After a short while they start to penetrate each other, and the performance drops so drastically that the CC lags.

The new codeversion works great, I can't thank you enough.
Pavi
Posts: 12
Joined: Wed Feb 22, 2012 12:08 am

Re: Dynamic Mesh -> what Class ?

Post by Pavi »

I could only recreate the ConvexHull graphics bug while using one of my Models. Its just a simple Ball created in 3dsmax exported with kW-Exporter into .X file format.

http://dl.dropbox.com/u/4405602/Ball.X

with this I call this code, again in the static mesh demo like the mobilemeshes:

Code: Select all

 int numColumns = 20;
            int numRows = 20;
            int numHigh = 1;
            float separation = 1;

            ball = game.Content.Load<Model>("Ball");
            TriangleMesh.GetVerticesAndIndicesFromModel(ball, out staticTriangleVertices, out staticTriangleIndices);
            ConvexHullShape cvh = new ConvexHullShape(staticTriangleVertices);
            Entity toAdd;
            for (int i = 0; i < numRows; i++)
                for (int j = 0; j < numColumns; j++)
                    for (int k = 0; k < numHigh; k++)
                    {
                        toAdd = new Entity(cvh, 10.0f);
                        toAdd.Position = new Vector3(
                            (separation * i - numRows * separation / 2) - 150,
                            30f + k * separation,
                            separation * j - numColumns * separation / 2);
                        
                        Space.Add(toAdd);
                    }
this loads a long time until it start and not always does it create the bugs.
Pavi
Posts: 12
Joined: Wed Feb 22, 2012 12:08 am

Re: Dynamic Mesh -> what Class ?

Post by Pavi »

At last i could somewhat reproduce the startup crashing. It happens about every other programstart, that it instantly crashes. Reason for this is the asynchronous updating which is identically to the one in the example. At following points it just crashes. If i could see some value problems with the debugger at that point i wrote them in the brackets.

System.NullReferenceExceptions:
  • -EntityBase.cs -> if (activityInformation.DeactivationManager.useStabilization && activityInformation.allowStabilization &&
    (activityInformation.isSlowing || activityInformation.velocityTimeBelowLimit > activityInformation.DeactivationManager.lowVelocityTimeMinimum)) [activityInformation.DeactivationManager = null]

    -ContinuousPositionUpdater.cs -> continuousUpdateables.Elements.UpdateTimeOfImpacts(timeStepSettings.TimeStepDuration);

    -SimulationIslandMember.cs -> if (velocity < DeactivationManager.velocityLowerLimitSquared) [Deactivationmanager = null]



System.IndexOutOfRangeException:
  • -RawList.cs -> throw new IndexOutOfRangeException("Index is outside of the list's bounds."); [index = 0]
System.DivideByZeroException:
  • -Solver.cs -> var updateable = solverUpdateables.Elements[(i * prime) % solverUpdateables.count];
sadly I could not reproduce it in the example. I hope my description helps.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Dynamic Mesh -> what Class ?

Post by Norbo »

It sounds like there's illegal actions being performed on a separate thread. For example, up in the previous code posted, threads should not be added to the Space's thread manager from the main thread. In addition, the buffered states should not be enabled from the main thread. Instead, perform all initialization either on the physics thread or from a synchronized context.

Asynchronous updating is full of little tricky problems like this. If at all possible, I would suggest looking into an easier approach, like just enabling internal multithreading and running it in sequence.

There's other options too, like running on separate threads but locking their frame-by-frame progression together. This would let you dedicate a few cores to physics and one core to graphics without have a 'free running' asynchronous update.

I'm working my way through the rest of the reports and I'll update if something new gets put up on the development fork.
Post Reply