Search code examples
variablesxnashared

XNA 4.0 shared basic effect variables?


I'm making game inspired by Settlers of Catan. ( www.facebook.com/Expanze ) I'm optimizing my code which renders hundreds instances of same model.

foreach (ModelMesh mesh in model.Meshes)
{
    foreach (BasicEffect effect in mesh.Effects)
    {
        effect.Alpha = 1.0f;
        effect.LightingEnabled = true;
        effect.DirectionalLight0.Direction = GameState.LightDirection;
        effect.DirectionalLight0.DiffuseColor = GameState.LightDiffusionColor;
        effect.DirectionalLight0.SpecularColor = GameState.LightSpecularColor;
        effect.DirectionalLight0.Enabled = true;
        effect.View = GameState.view;
        effect.Projection = GameState.projection;
        for (int loop1 = 0; loop1 < validItems; loop1++)
        {
             if (instance[loop1].Visible)
             {
                  instance[loop1].UpdateEffect(effect, meshNumber);
                  effect.World = transforms[mesh.ParentBone.Index] * instance[loop1].World;

                  mesh.Draw();

                  if(loop1 > 4)
                       break;
             }
        }
    }
    meshNumber++;
}

In : instance[loop1].UpdateEffect(effect, meshNumber);

I change ambient color : effect.AmbientLightColor = playerAmbientLightColor;

My problem is that changing color affects color of earlier instances which should be already drawn.

Two images, one with if(loop1 > 4) break, the second without these 2 lines : https://i.sstatic.net/DnfTA.jpg

https://i.sstatic.net/ngvO2.png


Solution

  • Inspired by or nearly identical to? Hahahaha.

    Likely what is happening here are your Draw() calls are being deferred and you're using the same instance of the Effect for each model. So what's happening if you're setting the values, calling Draw (deferred; read: not executed until later), switching models, and then setting the values FOR AN ALREADY USED Effect instance, then calling Draw again.

    When the deferred Draw calls get executed they use the most recent (read: last) settings/parameters passed to the Effect (or something along those lines).

    The solution is to create (clone, etc) a new instance of each Effect for each model.

    There could be other issues causing this; what draw modes are you using? What are your XNA settings? This is just a standard problem people run into.