• Advertisement
Sign in to follow this  

XNA - Non-Realistic Rendering Sample

This topic is 3365 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello... i am trying to copy the pencil sketch effect from the creators.xna.com website and i cannot get it to work... i can render my "normalDepth" but when displayed on the screen it comes out pure black... what i cleared the backbuffer to be i can also render my scene but nothing is drawn... i know the model that i am using works because when i add BasicEffect to it and render it that way it lags a ton but it will render. when the postprocessing comes around the pencil hashing works well but there is no edege detection and nothing is rendered =D if you can see anything please help... im now 7 hours into this and i still dont understand... HELP here is my game1.cs
using System;
using System.Collections.Generic;
using System.Linq;
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 Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace Gravity_B1
{
    public class RenderableObject
    {
        public Model Model;
        public Vector3 Position;
        public float Rotation;
        public RenderableObject(Model model, Vector3 pos, float rot)
        {
            Model = model;
            Position = pos;
            Rotation = rot;
        }
    }
    public class DrawableTexture // NOT FINISHED  ----------------------------------------
    {
        public Texture2D Texture;
        public Vector2 Position;
        public DrawableTexture()
        {
            
        }
    }
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        // Model Classes
        Tile tile;
        Map map;
        // Model Classes

        float rotation;
        // Our camera's view
        Vector3 cameraPosition = new Vector3(0.0f, 3.0f, 5.0f);

        Random random = new Random();
        BasicEffect Beffect;
        Effect postprocessEffect;
        Effect CartoonEffect;

        Texture2D sketchTexture;

        Vector2 sketchJitter;
        TimeSpan timeToNextJitter;

        //create render target
        RenderTarget2D sceneRenderTarget;
        RenderTarget2D normalDepthRenderTarget;

        float JitterSpeed = 0.05f;

        public Game1()
        {

            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferHeight = 480;
            graphics.PreferredBackBufferWidth = 640;
            graphics.IsFullScreen = false;
            graphics.ApplyChanges();
        }
        public List<RenderableObject> RenderableObjectList = new List<RenderableObject>();
        protected override void Initialize()
        {

            base.Initialize();
        }
        float aspectRatio;
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;

            //load postprocess and sketch
            postprocessEffect = Content.Load<Effect>("PostprocessEffect");
            CartoonEffect = Content.Load<Effect>("CartoonEffect");
            sketchTexture = Content.Load<Texture2D>("SketchTexture");

            Model tile_background = Content.Load<Model>("Model\\tile");
            Model Box = Content.Load<Model>("Model\\Block");
            Model Corner = Content.Load<Model>("Model\\Corner");

            
            //render targets
            // Create two custom rendertargets.
            PresentationParameters pp = graphics.GraphicsDevice.PresentationParameters;

            sceneRenderTarget = new RenderTarget2D(graphics.GraphicsDevice,
                pp.BackBufferWidth, pp.BackBufferHeight, 1,
                pp.BackBufferFormat, pp.MultiSampleType, pp.MultiSampleQuality);

            normalDepthRenderTarget = new RenderTarget2D(graphics.GraphicsDevice,
                pp.BackBufferWidth, pp.BackBufferHeight, 1,
                pp.BackBufferFormat, pp.MultiSampleType, pp.MultiSampleQuality);

            //Model Classes
            tile = new Tile(tile_background, this);
            map = new Map(Corner, Box, this);
            //Model Classes
            base.LoadContent();
        }
        protected override void UnloadContent()
        {
        }
        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            //Update Models
            RenderableObjectList.Clear();
            tile.Update();
            map.Update();
            //Update Models


            rotation += 0.01f;
            // Update the sketch overlay texture jitter animation.
            timeToNextJitter -= gameTime.ElapsedGameTime;

            if (timeToNextJitter <= TimeSpan.Zero)
            {
                sketchJitter.X = (float)random.NextDouble();
                sketchJitter.Y = (float)random.NextDouble();

                timeToNextJitter += TimeSpan.FromSeconds(JitterSpeed);
            }
        }
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice device = graphics.GraphicsDevice;
            Viewport viewport = device.Viewport;

            float aspectRatio = (float)viewport.Width / (float)viewport.Height;

            float time = (float)gameTime.TotalGameTime.TotalSeconds;

            Matrix rotation = Matrix.CreateRotationY(time * 0.5f);

            Matrix view = Matrix.CreateLookAt(new Vector3(0, 3, 3),
                                              Vector3.Zero,
                                              Vector3.Up);

            Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                                    aspectRatio,
                                                                    1000, 10000);
            //render to normal for sketch
            device.SetRenderTarget(0, normalDepthRenderTarget);
            device.Clear(Color.Black);
            //draw for sketch 
            DrawModel(rotation, view, projection, "NormalDepth");

            device.SetRenderTarget(0, sceneRenderTarget);
            device.Clear(Color.CornflowerBlue);
            //draw for scene 
            DrawModel(rotation, view, projection, "Lambert");
            
            //draw for backbuffer
            device.SetRenderTarget(0, null);
            ApplyPostprocess();


            base.Draw(gameTime);
        }
        void DrawModel(Matrix world, Matrix view, Matrix projection,
                           string effectTechniqueName)
        {
            // Set suitable renderstates for drawing a 3D model.
            RenderState renderState = graphics.GraphicsDevice.RenderState;

            renderState.AlphaBlendEnable = false;
            renderState.AlphaTestEnable = false;
            renderState.DepthBufferEnable = true;
            // Look up the bone transform matrices.
            Matrix[] transforms = new Matrix[RenderableObjectList[0].Model.Bones.Count];

            RenderableObjectList[0].Model.CopyAbsoluteBoneTransformsTo(transforms);

            if (effectTechniqueName == "NormalDepth")
            {
                foreach (ModelMesh mesh in RenderableObjectList[0].Model.Meshes)
                {
                    foreach (ModelMeshPart meshPart in mesh.MeshParts)
                    {
                        meshPart.Effect = CartoonEffect;
                    }
                }
            }
            if (effectTechniqueName == "Lambert")
            {
                foreach (ModelMesh mesh in RenderableObjectList[0].Model.Meshes)
                {
                    foreach (ModelMeshPart meshPart in mesh.MeshParts)
                    {
                        meshPart.Effect = CartoonEffect;
                    }
                }
            }

            // Draw the model.
            foreach (ModelMesh mesh in RenderableObjectList[0].Model.Meshes)
            {
                foreach (Effect effect in mesh.Effects)
                {
                    
                    // Specify which effect technique to use.
                    effect.CurrentTechnique = effect.Techniques[effectTechniqueName];

                    Matrix localWorld = transforms[mesh.ParentBone.Index] * world;

                    effect.Parameters["World"].SetValue(localWorld);
                    effect.Parameters["View"].SetValue(view);
                    effect.Parameters["Projection"].SetValue(projection);
                }
                mesh.Draw();
            }
        }  
        void ApplyPostprocess()
        {
            EffectParameterCollection parameters = postprocessEffect.Parameters;
            //sketch settings
            parameters["SketchThreshold"].SetValue(0.5f);
            parameters["SketchBrightness"].SetValue(0.3f);
            parameters["SketchJitter"].SetValue(sketchJitter);
            parameters["SketchTexture"].SetValue(sketchTexture);
            //scene render 
            Vector2 resolution = new Vector2(sceneRenderTarget.Width,
                                                 sceneRenderTarget.Height);
            //normal depth
            Texture2D normalDepthTexture = normalDepthRenderTarget.GetTexture();

            //edegedetect settings
            parameters["EdgeWidth"].SetValue(0.5f);
            parameters["EdgeIntensity"].SetValue(0.5f);
            parameters["ScreenResolution"].SetValue(resolution);
            parameters["NormalDepthTexture"].SetValue(normalDepthTexture);


            spriteBatch.Begin(SpriteBlendMode.None,
                              SpriteSortMode.Immediate,
                              SaveStateMode.None);
            postprocessEffect.CurrentTechnique = postprocessEffect.Techniques["EdgeDetectMonoSketch"];
            postprocessEffect.Begin();
            postprocessEffect.CurrentTechnique.Passes[0].Begin();

            spriteBatch.Draw(sceneRenderTarget.GetTexture(), Vector2.Zero, Color.White);

            spriteBatch.End();

            postprocessEffect.CurrentTechnique.Passes[0].End();
            postprocessEffect.End();
        }
    }
}

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement