//Creates a white 1*1 Texture that is used for the lines by scaling and rotating it
        public void CreatePixelTexture()
        {
            int TargetWidth = 1;
            int TargetHeight = 1;

            RenderTarget2D LevelRenderTarget = new RenderTarget2D(graphicsDevice, TargetWidth, TargetHeight, 1,
                graphicsDevice.PresentationParameters.BackBufferFormat, graphicsDevice.PresentationParameters.MultiSampleType,
                graphicsDevice.PresentationParameters.MultiSampleQuality, RenderTargetUsage.PreserveContents);

            DepthStencilBuffer stencilBuffer = new DepthStencilBuffer(graphicsDevice, TargetWidth, TargetHeight,
                graphicsDevice.DepthStencilBuffer.Format, graphicsDevice.PresentationParameters.MultiSampleType,
                graphicsDevice.PresentationParameters.MultiSampleQuality);

            graphicsDevice.SetRenderTarget(0, LevelRenderTarget);

            // Cache the current depth buffer
            DepthStencilBuffer old = graphicsDevice.DepthStencilBuffer;
            // Set our custom depth buffer
            graphicsDevice.DepthStencilBuffer = stencilBuffer;

            graphicsDevice.Clear(Color.White);

            graphicsDevice.SetRenderTarget(0, null);

            // Reset the depth buffer
            graphicsDevice.DepthStencilBuffer = old;
            pixel = LevelRenderTarget.GetTexture();
        }
示例#2
0
        public Texture2D PointScale(int scale, Texture2D sourceImage)
        {
            RenderTarget2D scaled = GraphicsHelper.CreateRenderTarget(game.GraphicsDevice, sourceImage.Width * scale, sourceImage.Height * scale);
            DepthStencilBuffer dsb = new DepthStencilBuffer(scaled.GraphicsDevice, scaled.Width, scaled.Height, scaled.GraphicsDevice.DepthStencilBuffer.Format);

            //stash the original graphics settings
            DepthStencilBuffer stashedDepthStencilBuffer = game.GraphicsDevice.DepthStencilBuffer;
            TextureFilter stashedFilter = game.GraphicsDevice.SamplerStates[0].MagFilter;

            //cram in the new settings
            game.GraphicsDevice.SetRenderTarget(0, scaled);
            game.GraphicsDevice.DepthStencilBuffer = dsb;
            game.GraphicsDevice.SamplerStates[0].MagFilter = TextureFilter.None;

            //draw to the render surface
            SpriteBatch batch = new SpriteBatch(game.GraphicsDevice);
            batch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
            game.GraphicsDevice.SamplerStates[0].MagFilter = TextureFilter.None;
            batch.Draw(sourceImage, new Rectangle(0, 0, sourceImage.Width * scale, sourceImage.Height * scale), Color.White);
            batch.End();

            //restore original settings
            game.GraphicsDevice.SetRenderTarget(0, null);
            game.GraphicsDevice.DepthStencilBuffer = stashedDepthStencilBuffer;
            game.GraphicsDevice.SamplerStates[0].MagFilter = stashedFilter;

            return scaled.GetTexture();
        }
示例#3
0
 public void BeginShadowMapping()
 {
     oldDepthStencil = GFX.Device.DepthStencilBuffer;
     oldViewPort = GFX.Device.Viewport;
     GFX.Device.SetRenderTarget(0, shadowMap);
     GFX.Device.DepthStencilBuffer = dsShadowMap;
     GFX.Device.Clear(Microsoft.Xna.Framework.Graphics.Color.TransparentBlack);
 }
        public Canvas(GraphicsDevice device)
        {
            this.device = device;

            CanvasShaderConstants.AuthorShaderConstantFile();
            CanvasVertexDeclarations.Initialize(this);
            CanvasPrimitives.Initialize(this);

            generic2DShader = new Shader();
            generic2DShader.CompileFromFiles(this, "Shaders/Basic2DP.hlsl", "Shaders/Basic2DV.hlsl");
            genericDepthStencil = new DepthStencilBuffer(device, 2048, 2048, DepthFormat.Depth24Stencil8);
        }
示例#5
0
            public RaderDrawer()
            {
                del = new VertexDeclaration( BaseGame.Device, new VertexElement[]{
                new VertexElement(0,0, VertexElementFormat.Vector3,
                VertexElementMethod.Default, VertexElementUsage.Position,0)} );

                sectorBuffer = new VertexBuffer( BaseGame.Device, typeof( Vector3 ),
                    partSum + 2, BufferUsage.WriteOnly );

                InitialVertexBuffer();

                depthBuffer = new DepthStencilBuffer( BaseGame.Device, texSize, texSize, BaseGame.Device.DepthStencilBuffer.Format );
                depthBufferSmall = new DepthStencilBuffer( BaseGame.Device, texSizeSmall, texSizeSmall, BaseGame.Device.DepthStencilBuffer.Format );

                LoadEffect();
            }
示例#6
0
 /// <summary>
 /// Default constructor of form. It sets up the Xna environment
 /// </summary>
 public frmMain()
 {
     InitializeComponent();
     CreateDevice();
     defaultDepthStencil = gfxDevice.DepthStencilBuffer;
     // initialize the content manager
     GfxService gfxService = new GfxService(gfxDevice);
     GameServiceContainer services = new GameServiceContainer();
     services.AddService(typeof(IGraphicsDeviceService), gfxService);
     contentMgr = new ContentManager(services,"Content");
     spriteBatch = new SpriteBatch(gfxDevice);
     basicEffect = new BasicEffect(gfxDevice, new EffectPool());
     basicEffect.VertexColorEnabled = true;
     Initialize();
     // attach game and control loops
     (this.scrMainLayout.Panel2 as Control).KeyDown += new KeyEventHandler(this.scrMainLayoutPanel2_KeyDown);
     (this.scrMainLayout.Panel2 as Control).KeyUp += new KeyEventHandler(this.scrMainLayoutPanel2_KeyUp);
     (this.scrMainLayout.Panel2 as Control).MouseWheel += new MouseEventHandler(this.scrMainLayoutPanel2_MouseWheel);
     gameLoopEvent = new EventHandler(Application_Idle);
     Application.Idle += gameLoopEvent;
     long perfcount;
     QueryPerformanceCounter(out perfcount);
     lastTimeCount = perfcount;
 }
示例#7
0
        /// <summary>
        /// Start this post screen shader, will just call SetRenderTarget.
        /// All render calls will now be drawn on the sceneMapTexture.
        /// Make sure you don't reset the RenderTarget until you call Show()!
        /// </summary>
        public void Start()
        {
            // Only apply post screen shader if texture is valid and effect is valid
            if (sceneMapTexture == null ||
                xnaEffect == null ||
                startedPostScreen == true ||
                // Also skip if we don't use post screen shaders at all!
                BaseGame.UsePostScreenShaders == false)
                return;

            RenderToTexture.SetRenderTarget(sceneMapTexture.RenderTarget, true);
            startedPostScreen = true;

            remBackBufferSurface = null;
            if (sceneMapTexture.ZBufferSurface != null)
            {
                remBackBufferSurface = BaseGame.Device.DepthStencilBuffer;
                BaseGame.Device.DepthStencilBuffer =
                    sceneMapTexture.ZBufferSurface;
            } // if (sceneMapTexture.ZBufferSurface)
        }
示例#8
0
文件: Game1.cs 项目: Squid56/TestApp
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            rt = new RenderTarget2D(graphics.GraphicsDevice, TargetResolutionX, TargetResolutionY, 1, GraphicsDevice.PresentationParameters.BackBufferFormat, graphics.GraphicsDevice.PresentationParameters.MultiSampleType, graphics.GraphicsDevice.PresentationParameters.MultiSampleQuality);
            //            shadowDepthBuffer = CreateDepthStencil(rt, DepthFormat.Depth24Stencil8Single);
            //            shadowDepthBuffer = CreateDepthStencil(rt);
            shadowDepthBuffer = new DepthStencilBuffer(rt.GraphicsDevice, rt.Width,
                rt.Height, rt.GraphicsDevice.DepthStencilBuffer.Format,
                rt.MultiSampleType, rt.MultiSampleQuality);

            resolution = new SpriteBatch(graphics.GraphicsDevice);
            spriteObject.LoadContent(this, graphics.GraphicsDevice);
            soundObject.LoadContent(this);
        }
        /// <summary>
        /// Initialize depth buffer format and multisampling
        /// </summary>
        /// <param name="setPreferredDepthStencilFormat">Set preferred depth
        /// stencil format</param>
        public static void InitializeDepthBufferFormatAndMultisampling(
			DepthFormat setPreferredDepthStencilFormat)
        {
            backBufferDepthFormat = setPreferredDepthStencilFormat;
            remMultiSampleType =
                BaseGame.Device.PresentationParameters.MultiSampleType;
            if (remMultiSampleType == MultiSampleType.NonMaskable)
                remMultiSampleType = MultiSampleType.None;
            remMultiSampleQuality =
                BaseGame.Device.PresentationParameters.MultiSampleQuality;
            remDepthBuffer = BaseGame.Device.DepthStencilBuffer;
        }
        public void Initialize()
        {
            camera = new Camera();
             camera.UpdatePosition(new Vector3(0, 100, 0));

             textInfoPanel = new InfoPanelFor3Dview(Content);
             textInfoPanel.Camera = camera;
             AddSubRenderer(textInfoPanel);

             projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Device.Viewport.AspectRatio,
            Config.Instance.Rendering.NearClippingDistance, Config.Instance.Rendering.FarClippingDistance);

             effect = Content.Load<Effect>("effect");

             waterRenderer = new WaterRenderer(Content, SceneContent, camera);
             skyRenderer = new SkyRenderer(Content, camera);
             secondDepthBuffer = new DepthStencilBuffer(Device, Device.PresentationParameters.BackBufferWidth, Device.PresentationParameters.BackBufferHeight, Device.DepthStencilBuffer.Format);

             Mouse.SetPosition(Device.Viewport.Width / 2, Device.Viewport.Height / 2);
             originalMouseState = Mouse.GetState();
        }
示例#11
0
文件: Game1.cs 项目: Squid56/TestApp
        /*
        public RenderTarget2D CreateRenderTarget(GraphicsDevice device, int numberLevels,
            SurfaceFormat surface)
        {
            MultiSampleType type = device.PresentationParameters.MultiSampleType;

            // If the card can't use the surface format
            if (!GraphicsAdapter.DefaultAdapter.CheckDeviceFormat(DeviceType.Hardware,
                GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Format, TextureUsage.None,
                QueryUsages.None, ResourceType.RenderTarget, surface))
            {
                // Fall back to current display format
                surface = device.DisplayMode.Format;
            }
            // Or it can't accept that surface format with the current AA settings
            else if (!GraphicsAdapter.DefaultAdapter.CheckDeviceMultiSampleType(DeviceType.Hardware,
                surface, device.PresentationParameters.IsFullScreen, type))
            {
                // Fall back to no antialiasing
                type = MultiSampleType.None;
            }

            int width, height;
            //int width=TargetResolutionX, height=TargetResolutionY;

            // See if we can use our buffer size as our texture
            CheckTextureSize(device.PresentationParameters.BackBufferWidth, device.PresentationParameters.BackBufferHeight,
                out width, out height);

            // Create our render target
            return new RenderTarget2D(device,
                width, height, numberLevels, surface,
                type, 0);

        }

        public static bool CheckTextureSize(int width, int height, out int newwidth, out int newheight)
        {
            bool retval = false;

            GraphicsDeviceCapabilities Caps;
            Caps = GraphicsAdapter.DefaultAdapter.GetCapabilities(DeviceType.Hardware);

            if (Caps.TextureCapabilities.RequiresPower2)
            {
                retval = true;  // Return true to indicate the numbers changed

                // Find the nearest base two log of the current width, and go up to the next integer
                double exp = Math.Ceiling(Math.Log(width) / Math.Log(2));
                // and use that as the exponent of the new width
                width = (int)Math.Pow(2, exp);
                // Repeat the process for height
                exp = Math.Ceiling(Math.Log(height) / Math.Log(2));
                height = (int)Math.Pow(2, exp);
            }
            if (Caps.TextureCapabilities.RequiresSquareOnly)
            {
                retval = true;  // Return true to indicate numbers changed
                width = Math.Max(width, height);
                height = width;
            }

            newwidth = Math.Min(Caps.MaxTextureWidth, width);
            newheight = Math.Min(Caps.MaxTextureHeight, height);
            return retval;
        }

        public static DepthStencilBuffer CreateDepthStencil(RenderTarget2D target)
        {
            return new DepthStencilBuffer(target.GraphicsDevice, target.Width,
                target.Height, target.GraphicsDevice.DepthStencilBuffer.Format,
                target.MultiSampleType, target.MultiSampleQuality);
        }

        public static DepthStencilBuffer CreateDepthStencil(RenderTarget2D target, DepthFormat depth)
        {
            if (GraphicsAdapter.DefaultAdapter.CheckDepthStencilMatch(DeviceType.Hardware,
               GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Format, target.Format,
                depth))
            {
                return new DepthStencilBuffer(target.GraphicsDevice, target.Width,
                    target.Height, depth, target.MultiSampleType, target.MultiSampleQuality);
            }
            else
                return CreateDepthStencil(target);
        }
        */
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            Rectangle r1 = new Rectangle(0, 0, TargetResolutionX, TargetResolutionY);
            Rectangle r2 = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);

            graphics.GraphicsDevice.SetRenderTarget(0, rt);

            // Cache the current depth buffer
            old = GraphicsDevice.DepthStencilBuffer;
            // Set our custom depth buffer
            GraphicsDevice.DepthStencilBuffer = shadowDepthBuffer;

            graphics.GraphicsDevice.Clear(Color.Wheat);

            if (FirstStart)
                spriteObject.DoStart(this, gameTime, TargetResolutionX, TargetResolutionY);
            else
                spriteObject.Draw(this, gameTime, TargetResolutionX, TargetResolutionY, soundObject, LevelRefresh, pl);

            graphics.GraphicsDevice.SetRenderTarget(0, null);
            // Reset the depth buffer
            GraphicsDevice.DepthStencilBuffer = old;

            resolution.Begin(SpriteBlendMode.None);
            resolution.Draw(rt.GetTexture(),r2,r1,Color.White,0.0f, Vector2.Zero, SpriteEffects.None, 1.0f);
            resolution.End();
            base.Draw(gameTime);
        }
示例#12
0
        void CreateCascadeShadows(int shadowMapSize)
        {
            int width = shadowMapSize * GFXShaderConstants.NUM_SPLITS;
            int height = shadowMapSize;
            shadowMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.Vector2);
            dsShadowMap = new DepthStencilBuffer(GFX.Device, width, height, GFX.Device.DepthStencilBuffer.Format);
            renderViews = new ShadowRenderView[GFXShaderConstants.NUM_SPLITS];

            for (int i = 0; i < GFXShaderConstants.NUM_SPLITS; i++)
            {
                Viewport splitViewport = new Viewport();
                splitViewport.MinDepth = 0;
                splitViewport.MaxDepth = 1;
                splitViewport.Width = shadowMapSize;
                splitViewport.Height = shadowMapSize;
                splitViewport.X = i * shadowMapSize;
                splitViewport.Y = 0;
                renderViews[i] = new ShadowRenderView(this, splitViewport, i, Matrix.Identity, Matrix.Identity, Vector3.Zero, 0.1f, 1000.0f);
            }
        }
示例#13
0
        /// <summary>
        /// Create
        /// </summary>
        private void Create()
        {
            SurfaceFormat format = SurfaceFormat.Color;
            // Try to use R32F format for shadow mapping if possible (ps20),
            // else just use A8R8G8B8 format for shadow mapping and
            // for normal RenderToTextures too.
            if (sizeType == SizeType.ShadowMap && BaseGame.CanUsePS20)
            {
                // Can do R32F format?
                if (CheckRenderTargetFormat(SurfaceFormat.Single))
                    format = SurfaceFormat.Single;
                // Else try R16F format, thats still much better than A8R8G8B8
                else if (CheckRenderTargetFormat(SurfaceFormat.HalfSingle))
                    format = SurfaceFormat.HalfSingle;
                // And check a couple more formats (mainly for the Xbox360 support)
                else if (CheckRenderTargetFormat(SurfaceFormat.HalfVector2))
                    format = SurfaceFormat.HalfVector2;
                else if (CheckRenderTargetFormat(SurfaceFormat.Luminance16))
                    format = SurfaceFormat.Luminance16;
                // Else nothing found, well, then just use the 8 bit Color format.

            #if XBOX360
                // Try to force Surface format on the Xbox360, CheckRenderTargetFormat
                // does not work on the Xbox at all!
                format = SurfaceFormat.Single;
            #endif
            } // if (sizeType)

            try
            {
                // Create render target of specified size.
                renderTarget = new RenderTarget2D(BaseGame.Device,
                    texWidth, texHeight, 1, format,
                    MultiSampleType, MultiSampleQuality);
                if (format != SurfaceFormat.Color)
                    usesHighPercisionFormat = true;

                // Create z buffer surface for shadow map render targets
                // if they don't fit in our current resolution.
                if (sizeType == SizeType.FullScreenWithZBuffer ||
                    sizeType == SizeType.HalfScreenWithZBuffer ||
                    sizeType == SizeType.ShadowMap &&
                    (texWidth > BaseGame.Width ||
                    texHeight > BaseGame.Height))
                {
                    zBufferSurface = new DepthStencilBuffer(BaseGame.Device,
                        texWidth, texHeight,
                        // Lets use the same stuff as the back buffer.
                        BackBufferDepthFormat,
                        // Don't use multisampling, render target does not support that.
                        MultiSampleType, MultiSampleQuality);
                } // if (sizeType)

                loaded = true;
            } // try
            catch (Exception ex)
            {
                // Everything failed, make this unuseable.
                Log.Write("Creating RenderToTexture failed: " + ex.ToString());
                renderTarget = null;
                internalXnaTexture = null;
                loaded = false;
            } // catch
        }
示例#14
0
        /// <summary>
        /// Create
        /// </summary>
        private void Create()
        {
            /*obs
            #if XBOX360
            // Limit to current resolution on Xbox360 (we won't create a depth
            // buffer below)
            if (texWidth > BaseGame.Width)
                texWidth = BaseGame.Width;
            if (texHeight > BaseGame.Height)
                texHeight = BaseGame.Height;
            #endif
             */

            SurfaceFormat format = SurfaceFormat.Color;
            // Try to use R32F format for shadow mapping if possible (ps20),
            // else just use A8R8G8B8 format for shadow mapping and
            // for normal RenderToTextures too.
            if (sizeType == SizeType.ShadowMap && BaseGame.CanUsePS20)
            {
                // Can do R32F format?
                if (CheckRenderTargetFormat(SurfaceFormat.Single))
                    format = SurfaceFormat.Single;
                // Else try R16F format, thats still much better than A8R8G8B8
                else if (CheckRenderTargetFormat(SurfaceFormat.HalfSingle))
                    format = SurfaceFormat.HalfSingle;
                // And check a couple more formats (mainly for the Xbox360 support)
                else if (CheckRenderTargetFormat(SurfaceFormat.HalfVector2))
                    format = SurfaceFormat.HalfVector2;
                else if (CheckRenderTargetFormat(SurfaceFormat.Luminance16))
                    format = SurfaceFormat.Luminance16;
                // Else nothing found, well, then just use the 8 bit Color format.

            /*obs
            #if XBOX360
                // Try to force Surface format on the Xbox360, CheckRenderTargetFormat
                // does not work on the Xbox at all!
                format = SurfaceFormat.Single;
            #endif
             */
            } // if (sizeType)

            try
            {
                // Create render target of specified size.
                renderTarget = new RenderTarget2D(
                    BaseGame.Device,
                    texWidth, texHeight, 1,
                    format,
                    BaseGame.MultiSampleType, BaseGame.MultiSampleQuality);
                if (format != SurfaceFormat.Color)
                    usesHighPercisionFormat = true;

                // Unsupported on Xbox360, will crash with InvalidOperationException
            //obs: #if !XBOX360
                //*always required, some gfx cards want always the same depth buffer size
                // * as the renderTarget size!
                // Create z buffer surface for shadow map render targets
                // if they don't fit in our current resolution.
                if (sizeType == SizeType.FullScreenWithZBuffer ||
                    sizeType == SizeType.HalfScreenWithZBuffer ||
                    sizeType == SizeType.ShadowMap &&
                    (texWidth > BaseGame.Width ||
                    texHeight > BaseGame.Height))// ||
                    //alwaysCreateRenderTargetDepthBuffer)
                //*/
                {
                    zBufferSurface =
                        new DepthStencilBuffer(
                        BaseGame.Device,
                        texWidth, texHeight,
                        // Lets use the same stuff as the back buffer.
                        BaseGame.BackBufferDepthFormat,
                        // Don't use multisampling, render target does not support that.
                        //obs: MultiSampleType.None, 0);
                        BaseGame.MultiSampleType, BaseGame.MultiSampleQuality);
                } // if
            //#endif
                loaded = true;
            } // try
            catch (Exception ex)
            {
                // Everything failed, make this unuseable.
                Log.Write("Creating RenderToTexture failed: " + ex.ToString());
                renderTarget = null;
                internalXnaTexture = null;
                loaded = false;
            } // catch
        }
示例#15
0
        /// <summary>
        /// Creates and Initializes a new RendererScene with a camera named "Default" as the active camera.
        /// </summary>
        public Scene()
        {
            entityID = new LowestAvailableID();
            defaultPosition = Vector3.Zero;
            updateToggle = false;

            layers = new List<SceneLayer>();
            SceneLayer layer = new SceneLayer();
            layers.Add(layer);

            entityList = new Dictionary<int, Entity>();
            drawableEntities = new List<SceneLayer>();
            transparentEntities = new List<SceneLayer>();
            deleteQueue = new List<int>();
            TransparentWalls = true;

            cameraDictionary = new Dictionary<string, Camera>();

            CurrentCamera = new Camera();

            cameraDictionary.Add("Default", CurrentCamera);
            currentFrustum = new BoundingFrustum(CurrentCamera.Projection);

            shadowRenderTarget = GfxComponent.CreateRenderTarget(GraphicOptions.graphics.GraphicsDevice,
                1, SurfaceFormat.Single);
            shadowDepthBuffer =
                GfxComponent.CreateDepthStencil(shadowRenderTarget,
                DepthFormat.Depth24Stencil8Single);

            worldLight.Position = new Vector3(7000, 4000, 10000);
            worldLight.TargetPosition = Vector3.Zero;
            worldLight.View = Matrix.Identity;
            worldLight.Projection = Matrix.Identity;

            PercentOfDayComplete = 0.5f;
        }
示例#16
0
 void DestroyShadows()
 {
     if (shadowMap != null)
     {
         shadowMap.Dispose();
         shadowMap = null;
     }
     if (dsShadowMap != null)
     {
         dsShadowMap.Dispose();
         dsShadowMap = null;
     }
 }
示例#17
0
		/// <summary>
		/// Initialize
		/// </summary>
		protected override void Initialize()
		{
#if !XBOX360
			// Add screenshot capturer. Works only on windows platform.
			// Note: Don't do this in constructor,
			// we need the correct window name for screenshots!
			this.Components.Add(new ScreenshotCapturer(this));
#endif

			// Remember device
			device = graphics.GraphicsDevice;

			// Remember resolution
			width = graphics.GraphicsDevice.Viewport.Width;
			height = graphics.GraphicsDevice.Viewport.Height;
			backBufferDepthFormat = graphics.PreferredDepthStencilFormat;
			remMultiSampleType = device.PresentationParameters.MultiSampleType;
			
            //if (remMultiSampleType == MultiSampleType.NonMaskable)
			//	remMultiSampleType = MultiSampleType.None;
			
            remMultiSampleQuality = device.PresentationParameters.MultiSampleQuality;
			remDepthBuffer = device.DepthStencilBuffer;

			// Update resolution if it changes and restore device after it was lost
			Window.ClientSizeChanged += new EventHandler(Window_ClientSizeChanged);
			graphics.DeviceReset += new EventHandler(graphics_DeviceReset);
			graphics_DeviceReset(null, EventArgs.Empty);
			
			// Create matrices for our shaders, this makes it much easier to manage
			// all the required matrices and we have to do this ourselfs since there
			// is no fixed function support and theirfore no Device.Transform class.
			WorldMatrix = Matrix.Identity;
			aspectRatio = (float)width / (float)height;
			ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(
				FieldOfView, aspectRatio, NearPlane, FarPlane);

			// ViewMatrix is updated in camera class
			ViewMatrix = Matrix.CreateLookAt(
				new Vector3(0, 0, 15), Vector3.Zero, Vector3.Up);

            // Init global manager classes, which will be used all over the place ^^
            lineManager2D = new LineManager2D();
            //lineManager3D = new LineManager3D();
            ui = new UIRenderer();
            // Create font and numbers font
			font = new TextureFont();

			// Make sure we can use PS1 or PS2, see UsePS and UsePS20
			if (device.GraphicsDeviceCapabilities.PixelShaderVersion.Major >= 2 &&
				GameSettings.Default.PerformanceSettings < 2)
				GameSettings.Default.PerformanceSettings = 2;
			else if (
				device.GraphicsDeviceCapabilities.PixelShaderVersion.Major >= 1 &&
				GameSettings.Default.PerformanceSettings < 1)
				GameSettings.Default.PerformanceSettings = 1;

			// Init post screen glow
			glowShader =
				//new PostScreenMenu();
				new PostScreenGlow();

			// Init effect manager
			effectManager = new EffectManager();

			// Init light position
			LightDirection = new Vector3(2, -7, 5);

			base.Initialize();

			device.RenderState.DepthBufferEnable = true;

			// Always create depth buffer from now on
			RenderToTexture.alwaysCreateRenderTargetDepthBuffer = true;
		} // Initialize()
示例#18
0
        public ShadowMap(string contentManagerName, int resolution)
            : base()
        {
            mResolutionX = resolution;
            mResolutionY = resolution;


            //MDS_TEMP
            bool hasMikeUpdatedThisCode = false;
            if (hasMikeUpdatedThisCode && IsF32Supported())
            {
                mRenderTargetTexture = new RenderTargetTexture(SurfaceFormat.Single, mResolutionX, mResolutionY);
            }
            else
            {
                mRenderTargetTexture = new RenderTargetTexture(SurfaceFormat.Color, mResolutionX, mResolutionY);
            }

            mShadowDepthBuffer = new DepthStencilBuffer(FlatRedBallServices.GraphicsDevice, mResolutionX, mResolutionY, DepthFormat.Depth24Stencil8);

            mLightSourceCamera = new Camera(contentManagerName, mResolutionX, mResolutionY);
            mLightSourceCamera.AspectRatio = mResolutionX / mResolutionY;

            //Create a default bounding box
            Vector3 bboxMin = new Vector3(-5.0f, -5.0f, -100.0f);
            Vector3 bboxMax = new Vector3(5.0f, 5.0f, 100.0f);
            mBoundingBox = new BoundingBox(bboxMin, bboxMax);
        }
示例#19
0
        void InitializeRenderTargets()
        {
            PresentationParameters pp = device.PresentationParameters;

            shadowMapW = pp.BackBufferWidth;
            shadowMapH = pp.BackBufferHeight;

            // Create new floating point render target
            renderTarget1 = new RenderTarget2D(graphics.GraphicsDevice,
                                                    shadowMapW,
                                                    shadowMapH,
                                                    1, SurfaceFormat.Vector4);

            renderTarget2 = new RenderTarget2D(graphics.GraphicsDevice,
                                                    shadowMapW,
                                                    shadowMapH,
                                                    1, SurfaceFormat.Vector4);

            // Create depth buffer to use when rendering to the shadow map
            shadowDepthBuffer = new DepthStencilBuffer(graphics.GraphicsDevice,
                                                       shadowMapW,
                                                       shadowMapH,
                                                       DepthFormat.Depth24);
        }
示例#20
0
 internal void m0000fa(RenderTarget2D p0)
 {
     if (!((this.f0000bd == null) || this.f0000bd.IsDisposed))
     {
         this.f0000bd.Dispose();
     }
     this.f0000bd = new DepthStencilBuffer(p0.GraphicsDevice, p0.Width, p0.Height, p0.GraphicsDevice.DepthStencilBuffer.Format, p0.MultiSampleType, p0.MultiSampleQuality);
 }
        void GenerateNormalMap()
        {
            Texture2D heightmap = new Texture2D(GFX.Device, width, depth, 1, TextureUsage.None, SurfaceFormat.Single);
            heightmap.SetData<float>(heightValues);

            Vector2 invRes = Vector2.One / new Vector2(heightmap.Width, heightmap.Height);
            Shader normalTangentShader = ResourceManager.Inst.GetShader("NormalTangentHeightmap");
            normalTangentShader.SetupShader();
            GFX.Device.SetVertexShaderConstant(0, invRes);
            GFX.Device.SetPixelShaderConstant(0, invRes);
            GFX.Device.SetPixelShaderConstant(1, Vector4.One / MaximumHeight);
            GFX.Device.Textures[0] = heightmap;
            GFX.Inst.SetTextureFilter(0, TextureFilter.Linear);

            RenderTarget2D normTanTarget = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, SurfaceFormat.Vector4);
            DepthStencilBuffer dsOld = GFX.Device.DepthStencilBuffer;
            DepthStencilBuffer dsNew = new DepthStencilBuffer(GFX.Device, heightmap.Width, heightmap.Height, dsOld.Format);
            GFX.Device.DepthStencilBuffer = dsNew;
            GFX.Device.SetRenderTarget(0, normTanTarget);
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);
            GFX.Device.DepthStencilBuffer = dsOld;

            normalTexture = normTanTarget.GetTexture();
        }
 public virtual void Dispose()
 {
     if (_renderTargets != null)
     {
         foreach (RenderTarget2D x in _renderTargets)
             x.Dispose();
         _renderTargets.Clear();
         _renderTargets = null;
     }
     if (!_blender.OpacityMap.IsNull)
         _blender.OpacityMap.Invalidate();
     _blender = null;
     _renderQuadVB = null;
     _sceneDepthBuffer = null;
     _toTexRenderState = null;
 }
示例#23
0
文件: GFX.cs 项目: nhippenmeyer/CS248
        void InitializeTextures()
        {
            int width = (int)DisplayRes.X;
            int height = (int)DisplayRes.Y;

            DSBufferScene = new DepthStencilBuffer(GFX.Device, width, height, Device.DepthStencilBuffer.Format);

            dsBufferLarge = new DepthStencilBuffer(Device, 2048, 2048, Device.DepthStencilBuffer.Format);
        }
示例#24
0
        protected override void UnloadContent() {
            base.UnloadContent();

            if (drawDepthBuffer != null) {
                drawDepthBuffer.Dispose();
                drawDepthBuffer = null;
            }

            if (drawBuffer != null) {
                drawBuffer.Dispose();
                drawBuffer = null;
            }

            if (spriteBatch != null) {
                spriteBatch.Dispose();
                spriteBatch = null;
            }

            Font.Dispose();

            if (contentManager != null) {
                contentManager.Dispose();
                contentManager = null;
            }

        }
        public Lighting(World world)
        {
            this.world = world;

            pSunColor = Shaders.Common.Parameters["vSunColor"];
            pSunVector = Shaders.Common.Parameters["vSunVector"];
            pAmbientColor = Shaders.Common.Parameters["vAmbientColor"];
            pAmbientLight = Shaders.Common.Parameters["fAmbient"];
            pNumberOfLights = Shaders.Common.Parameters["iNumLights"];
            pSunIntensity = Shaders.Common.Parameters["fSunIntensity"];
            pFogColor = Shaders.Common.Parameters["vFogColor"];

            //Shaders.Common.Parameters["tCloudShadowMap"].SetValue(world.Game.Content.Load<Texture2D>(@"textures\sky\clouds"));

            Random r = new Random();
            if (lights[0] == null)
            {
                for (int i = 0; i < lights.Length; i++)
                {
                    Vector3 color = new Vector3(r.Next(1000) / 1000.0f, r.Next(1000) / 1000.0f, r.Next(1000) / 1000.0f);
                    lights[i] = new PointLight(Vector3.Zero, color, Shaders.Common.Parameters["lights"].Elements[i]);
                }
            }

            // setup the shadowmap render target
            GraphicsDevice g = world.GraphicsDevice;
            PresentationParameters pp = world.GraphicsDevice.PresentationParameters;
            int shadowWidth = pp.BackBufferWidth;
            int shadowHeight = pp.BackBufferHeight;

            smapTarget = new RenderTarget2D(g, shadowWidth, shadowHeight, 1, SurfaceFormat.Single);
            smapStencilBuffer = new DepthStencilBuffer(g, shadowWidth, shadowHeight, g.DepthStencilBuffer.Format);
        }
示例#26
0
        internal void CreateDepthStencilBuffer(RenderTarget2D renderTarget)
        {
#if XNA4
            throw new NotImplementedException();

            
#else
            if (mDepthStencilBuffer != null && mDepthStencilBuffer.IsDisposed == false)
                mDepthStencilBuffer.Dispose();

            mDepthStencilBuffer = new DepthStencilBuffer(
                renderTarget.GraphicsDevice,
                renderTarget.Width, renderTarget.Height,
                renderTarget.GraphicsDevice.DepthStencilBuffer.Format,
                renderTarget.MultiSampleType, renderTarget.MultiSampleQuality);
#endif
        }
示例#27
0
        void InitializeTextures()
        {
            int width = GFX.Device.PresentationParameters.BackBufferWidth;
            int height = GFX.Device.PresentationParameters.BackBufferHeight;

            TexGen = GFX.Inst.ComputeTextureMatrix(new Vector2(width, height));

            ColorMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.Color);
            DepthMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.Single);
            NormalMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.HalfVector2);
            DataMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.Color);
            LightMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.Color);

            depthStencilScene = new DepthStencilBuffer(GFX.Device, width, height, GFX.Device.DepthStencilBuffer.Format);

            EmissiveMap = new RenderTarget2D(GFX.Device, width / 4, height / 4, 1, SurfaceFormat.Color);

            ParticleBuffer = new RenderTarget2D(GFX.Device, width / 8, height / 8, 1, SurfaceFormat.Color);

            BackBufferTexture = new ResolveTexture2D(GFX.Device, width, height, 1, SurfaceFormat.Color);

            CubeMap = new RenderTargetCube(GFX.Device, CubeMapSize, 1, SurfaceFormat.Color);
        }
示例#28
0
        protected override void LoadContent() {
            base.LoadContent();

            contentManager = new ContentManager(Services);

            spriteBatch = new SpriteBatch(graphics.GraphicsDevice);

            if (currentScreen != null)
                currentScreen.OnCreateDevice();

            Font.Init(this);

            if (enableDrawScaling) {
                PresentationParameters pp = graphics.GraphicsDevice.PresentationParameters;

                drawBuffer = new RenderTarget2D(graphics.GraphicsDevice,
                                                FixedDrawingWidth, FixedDrawingHeight, 1,
                                                SurfaceFormat.Color,
                                                pp.MultiSampleType, pp.MultiSampleQuality);

                drawDepthBuffer = new DepthStencilBuffer(graphics.GraphicsDevice,
                                                FixedDrawingWidth, FixedDrawingHeight,
                                                pp.AutoDepthStencilFormat,
                                                pp.MultiSampleType, pp.MultiSampleQuality);    
            }
        }
示例#29
0
        private Texture2D DrawShadowMap()
        {
            GraphicsDevice GraphicsDevice = GraphicOptions.graphics.GraphicsDevice;
            // Set the depth buffer function that best fits our stencil type
            // and projection (a reverse projection would use GreaterEqual)
            GraphicsDevice.RenderState.DepthBufferFunction =
                CompareFunction.LessEqual;
            oldRenderTarget = GraphicsDevice.GetRenderTarget(0) as RenderTarget2D;
            // Set Render Target for shadow map
            GraphicsDevice.SetRenderTarget(0, shadowRenderTarget);
            // Cache the current depth buffer
            oldDepthStencil = GraphicsDevice.DepthStencilBuffer;
            // Set our custom depth buffer
            GraphicsDevice.DepthStencilBuffer = shadowDepthBuffer;

            // Render the shadow map
            GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 1.0f, 0);
            GraphicsDevice.Clear(ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

            //Set renderstates
            GraphicsDevice.RenderState.CullMode = CullMode.None;
            GraphicsDevice.RenderState.DepthBufferEnable = true;
            GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
            GraphicsDevice.RenderState.AlphaBlendEnable = false;

            EffectTechnique technique = RendererAssetPool.UniversalEffect.Techniques.ShadowMap;
            foreach (SceneLayer layer in layers)
            {
                foreach (KeyValuePair<int, Object3> ent in layer.entityDictionary3D)
                {
                    if (ent.Value.CastsShadow)
                         ent.Value.Draw(technique);
                }

                foreach (KeyValuePair<int, VertexGroup> ent in layer.entityDictionaryVertex)
                {
                    if (ent.Value.CastsShadow)
                         ent.Value.Draw(technique);
                }
            }

            // Set render target back to the back buffer
            GraphicsDevice.SetRenderTarget(0, oldRenderTarget);
            // Reset the depth buffer
            GraphicsDevice.DepthStencilBuffer = oldDepthStencil;

            // Return the shadow map as a texture
            return shadowRenderTarget.GetTexture();
        }
        public void BeginRectUpdates(int mipLevel, ClipStackEntry stackEntry)
        {
            // grab a local reference to the graphics device
            GraphicsDevice device = GFXDevice.Instance.Device;

            // record the viewport (if PC)
            _sceneViewport = device.Viewport;
            _sceneDepthBuffer = device.DepthStencilBuffer;

            // replace it with our scratch render target for this mip level
            device.Viewport = _viewSlice;
            device.SetRenderTarget(0, _renderTargets[mipLevel]);
            device.DepthStencilBuffer = null;

            // set up the device to render our quad to a section of the texture
            device.RenderState.AlphaBlendEnable = false;
            device.RenderState.DepthBufferEnable = false;
            device.RenderState.CullMode = CullMode.None;
            //device.Indices = _renderQuadIB.Instance;
            device.VertexDeclaration = GFXDevice.Instance.GetVertexDeclarationVPT();
        }