Demonstrates how to use a custom effect and a texture to render a 3D object.
Complete Sample
The code in the topic shows you the technique for creating an effect to apply a texture. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.
Using a custom effect and a texture
To use a custom effect and a texture
-
Create a vertex declaration that contains a position and a texture coordinate.
-
Create a vertex buffer from the vertex declaration.
vertexDeclaration = new VertexDeclaration(new VertexElement[] { new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(12, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0) } ); vertexBuffer = new VertexBuffer( graphics.GraphicsDevice, vertexDeclaration, number_of_vertices, BufferUsage.None ); -
Create a custom effect using the Effect class.
-
Load the Effect object using the ContentManager.Load<Effect> method to load the .fx file.
-
Load a Texture2D object using the ContentManager.Load<Texture2D> method to load the asset.
-
Call SetValue to initialize each effect parameter using the corresponding game property.
-
Initialize the CurrentTechnique to a technique that exists in the .fx file.
effect = Content.Load<Effect>("ReallySimpleTexture"); Texture2D texture = Content.Load<Texture2D>("XNA_pow2"); effect.Parameters["WorldViewProj"].SetValue(worldViewProjection); effect.Parameters["UserTexture"].SetValue(texture); effect.CurrentTechnique = effect.Techniques["TransformAndTexture"]; -
Render the effect.
-
Set the RasterizerState property to turn culling off so that all primitives will be drawn regardless of the order of the vertices.
-
Loop through each pass in the effect calling DrawPrimitives.
graphics.GraphicsDevice.Clear(Color.SteelBlue); RasterizerState rasterizerState1 = new RasterizerState(); rasterizerState1.CullMode = CullMode.None; graphics.GraphicsDevice.RasterizerState = rasterizerState1; foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Apply(); graphics.GraphicsDevice.DrawPrimitives( PrimitiveType.TriangleList, 0, // start vertex 12 // number of primitives to draw ); }