xna中使用自定义的shader来绘制model

来源:互联网 发布:朝阳永续数据库 编辑:程序博客网 时间:2024/05/16 15:38

XNA中的 Model.Draw()  函数会使用导入model所使用的Content Processor指定的Effect来进行绘制,因此,如果选择的默认的Content Processor,即Model - XNA Framework,则会使用BasicEffect来进行绘制。

若想用自定义的shader绘制model,需要创建一个自定义的ContentPipeline,在ContentPipeline中指定所用的shader,然后用此ContentPipeline来作为model的Content Processor。

步骤:

1.创建一个Content Pipeline Extension Library 项目,命名为CustomContentProcessor

2.CustomContentProcessor类重写为:

 [ContentProcessor(DisplayName = "CustomEffectModelProcessor.CustomContentProcessor")]    public class CustomContentProcessor : ModelProcessor    {        protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)        {            EffectMaterialContent myMaterial = new EffectMaterialContent();            string effectPath = Path.GetFullPath("MyEffect.fx");            myMaterial.Effect = new ExternalReference<EffectContent>(effectPath);            return base.ConvertMaterial(myMaterial, context);        }    }
3. 将model 的Content Processor指定为 CustomContentProcessor

4.自己写一个 MyEffect.fx 文件

5.绘制model的代码

            foreach (ModelMesh mesh in myModel.Meshes)            {                foreach (Effect effect in mesh.Effects)                {                    effect.Parameters["View"].SetValue(view);                    effect.Parameters["Projection"].SetValue(projection);                    effect.Parameters["World"].SetValue(Matrix.CreateRotationY(roty));                    effect.Parameters["ColorMap"].SetValue(bodyTex);                }                mesh.Draw();            }