Juan Alberto wrote:
When you say "let the simulation run parallel to the Draw() method" you mean that by default the car simulation is not multithreaded?
In MyGame Simulation.Update() is called in MyGame.Update(), like this:
protected override void Update(GameTime gameTime)
{
...
// Advance physics simulation.
Simulation.Update(elapsedTime);
// Update game components.
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
...
}
Simulation.Update() is internally multithreaded by default. But in XNA MyGame.Update() and MyGame.Draw() are executed sequentially. That means, if Simulation.Update() takes 16ms and Draw() takes 11ms, then one frame takes >27 ms.
I have made following changes to MyGame.cs:
private Task simulationTask;
protected override void Update(GameTime gameTime)
{
simulationTask.Wait();
...
base.Update(gameTime);
simulationTask = Parallel.Start(() => Simulation.Update(elapsedTime));
}
protected override void Draw(GameTime gameTime)
{
...
}
Now, Simulation.Update() starts at the end of Update(), runs parallel to Draw() and ends at the beginning of the next Update(). In this case we get a frame time of nearly 16ms (+ the time of the base.Update() + overhead) because physics and graphics run in parallel.
One important thing is that the Draw() code must not access the rigid body data (e.g. RigidBody.Pose) directly because it is modified in parallel. Therefore, the game components must read and store the RigidBody.Pose in their Update() method and use only the stored values in their Draw() method.
This is one method to make the game more parallel.