} // Draw2DTexture

        /// <summary>
        /// Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, color, rotation, origin, scale, effects and layer.
        /// </summary>
        /// <param name="texture">A texture.</param>
        /// <param name="worldMatrix">The location to draw the sprite.</param>
        /// <param name="sourceRectangle">A rectangle that specifies (in texels) the source texels from a texture. Use null to draw the entire texture.</param>
        /// <param name="color">The color to tint the font.</param>
        public static void Draw3DTexture(Texture texture, Matrix worldMatrix, Rectangle?sourceRectangle, Color color)
        {
            if (!begined)
            {
                throw new InvalidOperationException("Sprite Manager: Draw was called, but Begin has not yet been called. Begin must be called successfully before you can call Draw.");
            }
            if (begin2D)
            {
                throw new InvalidOperationException("Sprite Manager: Begin was called in 2D mode.");
            }

            SpriteShader.Instance.SetParameters(worldMatrix * Matrix.CreateFromYawPitchRoll(0, 3.1416f, 0));
            spriteBatch.Draw(texture.Resource, Vector2.Zero, sourceRectangle, color);
            // Update statistics
            Statistics.TrianglesDrawn    += 2;
            Statistics.VerticesProcessed += 4;
        } // Draw3DTexture
        } // BeginLinearSpace

        /// <summary>
        /// Begins the render.
        /// </summary>
        internal void BeginGammaSpace(Matrix viewMatrix, Matrix projectionMatrix, Texture depthTexture, float farPlane)
        {
            try
            {
                // Set initial parameters
                this.viewMatrix           = viewMatrix;
                this.projectionMatrix     = projectionMatrix;
                spProjectionInverse.Value = Matrix.Invert(projectionMatrix);
                spDepthTexture.Value      = depthTexture;
                spFarPlane.Value          = farPlane;
                spHalfPixel.Value         = new Vector2(0.5f / depthTexture.Width, 0.5f / depthTexture.Height); // The half depth size produce flickering
                Resource.CurrentTechnique = Resource.Techniques["SpriteBatchGammaSpace"];
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Sprite Shader: Unable to begin the rendering.", e);
            }
        } // BeginGammaSpace
        } // GetTechniquesHandles

        #endregion

        #region Begin

        /// <summary>
        /// Begins the render.
        /// </summary>
        internal void Begin(Matrix viewMatrix, Matrix projectionMatrix, Texture diffuseAccumulationTexture, Texture specularAccumulationTexture, Texture normalTexture)
        {
            try
            {
                // Set initial parameters
                Matrix.Multiply(ref viewMatrix, ref projectionMatrix, out viewProjectionMatrix);
                spHalfPixel.Value                   = new Vector2(0.5f / diffuseAccumulationTexture.Width, 0.5f / diffuseAccumulationTexture.Height);
                spCameraPosition.Value              = Matrix.Invert(viewMatrix).Translation;
                spDiffuseAccumulationTexture.Value  = diffuseAccumulationTexture;
                spSpecularAccumulationTexture.Value = specularAccumulationTexture;
                spNormalTexture.Value               = normalTexture;
                spViewInverseMatrix.Value           = Matrix.Invert(Matrix.Transpose(Matrix.Invert(viewMatrix)));
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Blinn Phong Material: Unable to begin the rendering.", e);
            }
        } // Begin
Exemple #4
0
        } // Begin

        #endregion

        #region Render

        /// <summary>
        /// Draws a particle system.
        /// </summary>
        public void Render(ParticleSystem particleSystem, float duration, BlendState blendState, float durationRandomness,
                           Vector3 gravity, float endVelocity, Color minimumColor, Color maximumColor, Vector2 rotateSpeed,
                           Vector2 startSize, Vector2 endSize, Texture texture, int tilesX, int tilesY, int animationRepetition,
                           bool softParticles, float fadeDistance)
        {
            try
            {
                // Set Render States.
                EngineManager.Device.BlendState = blendState;

                // Set parameters
                // Set an effect parameter describing the current time. All the vertex shader particle animation is keyed off this value.
                spCurrentTime.Value = particleSystem.CurrentTime;
                // Surface
                spDuration.Value           = duration;
                spDurationRandomness.Value = durationRandomness;
                spGravity.Value            = gravity;
                spEndVelocity.Value        = endVelocity;
                spMinColor.Value           = minimumColor;
                spMaxColor.Value           = maximumColor;
                spRotateSpeed.Value        = rotateSpeed;
                spStartSize.Value          = startSize;
                spEndSize.Value            = endSize;
                // Texture
                spTexture.Value             = texture;
                spTiles.Value               = new Vector2(tilesX, tilesY);
                spAnimationRepetition.Value = animationRepetition;
                // Soft Particles
                if (softParticles)
                {
                    spFadeDistance.Value = fadeDistance;
                }

                Resource.CurrentTechnique = softParticles ? Resource.Techniques["SoftParticles"] : Resource.Techniques["HardParticles"];
                Resource.CurrentTechnique.Passes[0].Apply();

                // Render particle system.
                particleSystem.Render();
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Particle Shader: Unable to render the particle system.", e);
            }
        } // Render
        } // Draw3DBillboardTexture

        /// <summary>
        /// Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, color, rotation, origin, scale, effects and layer.
        /// </summary>
        /// <param name="texture">A texture.</param>
        /// <param name="worldMatrix">The location to draw the sprite.</param>
        /// <param name="color">The color to tint the font.</param>
        public static void Draw3DBillboardTexture(Texture texture, Matrix worldMatrix, Color color, Vector3 cameraPosition, Vector3 cameraUp, Vector3 cameraForward)
        {
            if (!begined)
            {
                throw new InvalidOperationException("Sprite Manager: Draw was called, but Begin has not yet been called. Begin must be called successfully before you can call Draw.");
            }
            if (begin2D)
            {
                throw new InvalidOperationException("Sprite Manager: Begin was called in 2D mode.");
            }

            float scale = new Vector3(worldMatrix.M11, worldMatrix.M12, worldMatrix.M13).Length();

            worldMatrix = Matrix.CreateBillboard(worldMatrix.Translation, cameraPosition, cameraUp, cameraForward);
            SpriteShader.Instance.SetParameters(Matrix.CreateScale(scale) * Matrix.CreateFromYawPitchRoll(0, 0, 3.1416f) * worldMatrix);
            spriteBatch.Draw(texture.Resource, Vector2.Zero, color);
            // Update statistics
            Statistics.TrianglesDrawn    += 2;
            Statistics.VerticesProcessed += 4;
        } // Draw3DBillboardTexture
Exemple #6
0
        } // SaveScreenshot

        #endregion

        #region Save As Jpeg

#if !XBOX
        /// <summary>
        /// Saves texture data as a .jpg.
        /// </summary>
        /// <remarks>
        /// The XNA functions produce a memory leak. JohnU function does not.
        /// http://xboxforums.create.msdn.com/forums/p/65527/515125.aspx
        /// </remarks>
        private static void SaveAsJpeg(Texture texture, String filename)
        {
            Rectangle textureRectangle = new Rectangle(0, 0, texture.Width, texture.Height);

            byte[] textureData = new byte[4 * texture.Width * texture.Height];
            Bitmap bitmap      = new Bitmap(texture.Width, texture.Height, PixelFormat.Format32bppArgb);

            texture.Resource.GetData(textureData);
            for (int i = 0; i < textureData.Length; i += 4)
            {
                byte blue = textureData[i];
                textureData[i]     = textureData[i + 2];
                textureData[i + 2] = blue;
            }

            BitmapData bitmapData = bitmap.LockBits(textureRectangle, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
            IntPtr     safePtr    = bitmapData.Scan0;

            System.Runtime.InteropServices.Marshal.Copy(textureData, 0, safePtr, textureData.Length);
            bitmap.UnlockBits(bitmapData);
            bitmap.Save(filename, ImageFormat.Jpeg);
        } // SaveAsJpeg
Exemple #7
0
        } // LuminanceTextureGeneration

        #endregion

        #region Luminance Adaptation
        
        /// <summary>
        /// Luminance Adaptation.
        /// </summary>
        public RenderTarget LuminanceAdaptation(Texture currentLuminanceTexture, RenderTarget lastLuminanceTexture, PostProcess postProcess)
        {
            if (currentLuminanceTexture == null || currentLuminanceTexture.Resource == null)
                throw new ArgumentNullException("currentLuminanceTexture");

            try
            {
                Resource.CurrentTechnique = Resource.Techniques["LuminanceAdaptation"];

                RenderTarget luminanceTexture = RenderTarget.Fetch(currentLuminanceTexture.Size, SurfaceFormat.Single, DepthFormat.None, RenderTarget.AntialiasingType.NoAntialiasing, true);

                // Set parameters
                spHalfPixel.Value = new Vector2(-0.5f / (luminanceTexture.Width / 2), 0.5f / (luminanceTexture.Height / 2));
                spSceneTexture.Value = currentLuminanceTexture;
                spTimeDelta.Value = Time.FrameTime;
                spExposureAdjustTimeMultiplier.Value = postProcess.ToneMapping.AutoExposureAdaptationTimeMultiplier;
                
                // To avoid a problem in the first frame.
                if (lastLuminanceTexture != null && !lastLuminanceTexture.IsDisposed)
                    spLastLuminanceTexture.Value = lastLuminanceTexture;
                else
                    spLastLuminanceTexture.Value = currentLuminanceTexture;

                luminanceTexture.EnableRenderTarget();
                Resource.CurrentTechnique.Passes[0].Apply();
                RenderScreenPlane();
                RenderTarget.DisableCurrentRenderTargets();

                // This luminance texture is not needed anymore.
                RenderTarget.Release(lastLuminanceTexture);

                return luminanceTexture;
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Post Process Shader: Unable to generate the luminace texture.", e);
            }
        } // LuminanceAdaptation
        } // End

        #endregion

        #region Draw Texture To Full Screen

        /// <summary>
        /// Draw textures onto fullscreen.
        /// This is useful for quick tests related to render targets.
        /// </summary>
        /// <param name="texture">Texture.</param>
        /// <param name="alphaBlend">Some surface formats do not allow alpha blending, but in some scenarios alpha blending is need.</param>
        public static void DrawTextureToFullScreen(Texture texture, bool alphaBlend = false)
        {
            if (spriteBatch == null)
            {
                throw new Exception("The Sprite Manager is not initialized.");
            }

            // This is not a batch operation, for that reason the immediate mode is selected.
            // Floating point textures only works in point filtering.
            // Besides, we don’t need more than this because the render target will match the screen resolution.
            // Also there is no need for alpha blending.
            spriteBatch.Begin(SpriteSortMode.Immediate, alphaBlend ? BlendState.AlphaBlend : BlendState.Opaque,
                              SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise);

            spriteBatch.Draw(texture.Resource,
                             new Rectangle(0, 0, EngineManager.Device.Viewport.Width, EngineManager.Device.Viewport.Height),
                             Color.White);
            // Update statistics
            Statistics.DrawCalls++;
            Statistics.TrianglesDrawn    += 2;
            Statistics.VerticesProcessed += 4;

            spriteBatch.End();
        } // DrawTextureToFullScreen
Exemple #9
0
        } // ViewportArea

        #endregion

        #region Add Main Window Controls

        /// <summary>
        /// Add the editor's main window controls.
        /// </summary>
        public static void AddMainControls()
        {
            #region Canvas

            // The canvas cover the whole window. I will place the static controls there.
            // I don’t place the controls directly to the manager to allow having some functionality
            // provided by the canvas like the automatic placing of menu items, status bar, etc.
            Container canvas = new Container
            {
                Top             = 0,
                Left            = 0,
                Width           = Screen.Width,
                Height          = Screen.Height,
                Anchor          = Anchors.All,
                AutoScroll      = false,
                BackgroundColor = Color.Transparent,
                StayOnBack      = true,
                Passive         = true,
                CanFocus        = false,
            };

            #endregion

            #region Main Menu

            canvas.MainMenu = new MainMenu
            {
                Width    = Screen.Width,
                Anchor   = Anchors.Left | Anchors.Top,
                CanFocus = false
            };

            #region File

            MenuItem menuItemFile = new MenuItem("File", true);
            canvas.MainMenu.Items.Add(menuItemFile);
            menuItemFile.Items.AddRange(new[]
            {
                new MenuItem("New Scene")
                {
                    RightSideText = "Ctrl+N"
                },
                new MenuItem("Open Scene")
                {
                    RightSideText = "Ctrl+O"
                },
                new MenuItem("Save Scene")
                {
                    RightSideText = "Ctrl+S", SeparationLine = true
                },
                new MenuItem("Save Scene as...")
                {
                    RightSideText = "Ctrl+Shift+S"
                },
                new MenuItem("Exit", true)
                {
                    SeparationLine = true
                },
            });
            menuItemFile.Items[0].Click += delegate { StorageManager.ClearScene(); };
            menuItemFile.Items[1].Click += delegate { StorageManager.LoadScene(); };
            menuItemFile.Items[2].Click += delegate { StorageManager.SaveScene(); };

            #endregion

            #region Edit

            MenuItem menuItemEdit = new MenuItem("Edit", true);
            canvas.MainMenu.Items.Add(menuItemEdit);
            menuItemEdit.Items.AddRange(new[]
            {
                new MenuItem("Undo")
                {
                    RightSideText = "Ctrl+Z"
                },
                new MenuItem("Redo")
                {
                    RightSideText = "Ctrl+Y"
                },
                new MenuItem("Frame Selected (All 3D Views)")
                {
                    RightSideText = "Shift+F", SeparationLine = true
                },
                new MenuItem("Frame All (All 3D Views)")
                {
                    RightSideText = "Shift+A"
                },
                new MenuItem("Reset (All 3D Views)")
                {
                    RightSideText = "Shift+R"
                },
            });
            menuItemEdit.Items[0].Click += delegate { ActionManager.Undo(); };
            menuItemEdit.Items[1].Click += delegate { ActionManager.Redo(); };
            menuItemEdit.Items[2].Click += delegate
            {
                foreach (var editorViewport in EditorManager.EditorViewports)
                {
                    editorViewport.FrameObjects(EditorManager.SelectedObjects);
                }
            };
            menuItemEdit.Items[3].Click += delegate
            {
                foreach (var editorViewport in EditorManager.EditorViewports)
                {
                    editorViewport.FrameObjects(GameObject.GameObjects);
                }
            };
            menuItemEdit.Items[4].Click += delegate
            {
                foreach (var editorViewport in EditorManager.EditorViewports)
                {
                    editorViewport.Reset();
                }
            };

            #endregion

            #region Game Object

            MenuItem menuItemGameObject = new MenuItem("Game Object", true);
            canvas.MainMenu.Items.Add(menuItemGameObject);
            menuItemGameObject.Items.AddRange(new[]
            {
                new MenuItem("Create Empty 3D Game Object")
                {
                    RightSideText = "Ctrl+Shift+N"
                },
                new MenuItem("Create Empty 2D Game Object")
                {
                    RightSideText = "Ctrl+Shift+M"
                },
                new MenuItem("Create Other"),
            });
            menuItemGameObject.Items[2].Items.AddRange(new[]
            {
                new MenuItem("Camera"),
                new MenuItem("Particle System"),
                new MenuItem("HUD Texture"),
                new MenuItem("HUD Text"),
                new MenuItem("Directional Light")
                {
                    SeparationLine = true
                },
                new MenuItem("Point Light"),
                new MenuItem("Spot Light"),
                new MenuItem("Sphere")
                {
                    SeparationLine = true
                },
                new MenuItem("Box"),
                new MenuItem("Plane"),
                new MenuItem("Cylinder"),
                new MenuItem("Cone"),
                new MenuItem("Empty Model"),
            });
            // Create Empty 3D Game Object
            menuItemGameObject.Items[0].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D();
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Camera
            menuItemGameObject.Items[2].Items[0].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D();
                gameObject3D.AddComponent <Camera>();
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Particle System
            menuItemGameObject.Items[2].Items[1].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D();
                gameObject3D.AddComponent <ParticleEmitter>();
                gameObject3D.AddComponent <ParticleRenderer>();
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // HUD Texture
            menuItemGameObject.Items[2].Items[2].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D();
                gameObject3D.AddComponent <HudTexture>();
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // HUD Text
            menuItemGameObject.Items[2].Items[3].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D();
                gameObject3D.AddComponent <HudText>();
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Directional Light
            menuItemGameObject.Items[2].Items[4].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D();
                gameObject3D.AddComponent <DirectionalLight>();
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Point Light
            menuItemGameObject.Items[2].Items[5].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D();
                gameObject3D.AddComponent <PointLight>();
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Spot Light
            menuItemGameObject.Items[2].Items[6].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D();
                gameObject3D.AddComponent <SpotLight>();
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Sphere
            menuItemGameObject.Items[2].Items[7].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D(new Sphere(), Material.DefaultMaterial);
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Box
            menuItemGameObject.Items[2].Items[8].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D(new Box(), Material.DefaultMaterial);
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Plane
            menuItemGameObject.Items[2].Items[9].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D(new Plane(), Material.DefaultMaterial);
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Cylinder
            menuItemGameObject.Items[2].Items[10].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D(new Cylinder(), Material.DefaultMaterial);
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Cone
            menuItemGameObject.Items[2].Items[11].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D(new Cone(), Material.DefaultMaterial);
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };
            // Empty Model
            menuItemGameObject.Items[2].Items[12].Click += delegate
            {
                GameObject3D gameObject3D = new GameObject3D(null, Material.DefaultMaterial);
                EditorManager.RemoveAllObjectFromSelection();
                EditorManager.AddObjectToSelection(gameObject3D);
            };

            #endregion

            #region Component

            MenuItem menuItemComponent = new MenuItem("Component", true);
            canvas.MainMenu.Items.Add(menuItemComponent);
            menuItemComponent.Items.AddRange(new[]
            {
                new MenuItem("Model"),
                new MenuItem("Particles"),
                new MenuItem("Physics"),
                new MenuItem("Audio"),
                new MenuItem("Rendering"),
            });

            #endregion

            #region Window

            MenuItem menuItemWindow = new MenuItem("Window", true);
            canvas.MainMenu.Items.Add(menuItemWindow);
            menuItemWindow.Items.AddRange(new[]
            {
                new MenuItem("Layouts"),
                new MenuItem("Hierarchy")
                {
                    RightSideText = "Ctrl+6", SeparationLine = true,
                },
                new MenuItem("Heads Up Display Editor")
                {
                    RightSideText = "Ctrl+7"
                },
            });
            menuItemWindow.Items[0].Items.AddRange(new []
            {
                new MenuItem("4 Split"),
                new MenuItem("3 Split"),
                new MenuItem("Wide"),
                new MenuItem("Toggle")
                {
                    RightSideText = "F12", SeparationLine = true,
                },
            });
            menuItemWindow.Items[0].Items[0].Click += delegate { EditorManager.Layout = EditorManager.LayoutOptions.FourSplit; };
            menuItemWindow.Items[0].Items[1].Click += delegate { EditorManager.Layout = EditorManager.LayoutOptions.ThreeSplit; };
            menuItemWindow.Items[0].Items[2].Click += delegate { EditorManager.Layout = EditorManager.LayoutOptions.Wide; };
            menuItemWindow.Items[0].Items[3].Click += delegate { EditorManager.ToggleLayout(); };

            #endregion

            #region Help

            MenuItem menuItemHelp = new MenuItem("Help", true);
            canvas.MainMenu.Items.Add(menuItemHelp);
            menuItemHelp.Items.AddRange(new[]
            {
                new MenuItem("About"),
                new MenuItem("Documentation")
                {
                    RightSideText = "F1", SeparationLine = true,
                },
            });
            menuItemHelp.Items[1].Click += delegate { System.Diagnostics.Process.Start("http://xnafinalengine.codeplex.com/documentation"); };

            #endregion

            #endregion

            #region Top Panel

            ToolBarPanel topPanel = new ToolBarPanel();
            canvas.ToolBarPanel = topPanel;
            ToolBar toolBarTopPanel = new ToolBar
            {
                Parent  = topPanel,
                Movable = true,
                FullRow = true
            };

            #region Button Space

            Button buttonSpace = new Button
            {
                Text     = "Global",
                Left     = 10,
                Top      = 10,
                Height   = 15,
                Parent   = toolBarTopPanel,
                CanFocus = false,
            };
            buttonSpace.Click += delegate
            {
                if (Gizmo.Space == Gizmo.SpaceMode.Local)
                {
                    Gizmo.Space      = Gizmo.SpaceMode.Global;
                    buttonSpace.Text = "Global";
                }
                else
                {
                    Gizmo.Space      = Gizmo.SpaceMode.Local;
                    buttonSpace.Text = "Local";
                }
                buttonSpace.Focused = false;
            };

            #endregion

            #region Buttons Play, Pause and Stop

            Texture playTexture        = new Texture("Editor\\PlayIconNotPressed");
            Texture playPressedTexture = new Texture("Editor\\PlayIcon");
            Button  buttonPlay         = new Button
            {
                Left   = Screen.Width / 2 - 50,
                Top    = 2,
                Height = 32,
                Width  = 32,
                Glyph  = new Glyph(playTexture)
                {
                    SizeMode = SizeMode.Normal
                },
                Parent   = toolBarTopPanel,
                CanFocus = false,
            };
            buttonPlay.Click += delegate { buttonPlay.Glyph.Texture = buttonPlay.Glyph.Texture == playTexture ? playPressedTexture : playTexture; };
            Texture pauseTexture        = new Texture("Editor\\PauseIconNotPressed");
            Texture pausePressedTexture = new Texture("Editor\\PauseIcon");
            Button  buttonPause         = new Button
            {
                Left   = buttonPlay.Left + 34,
                Top    = 2,
                Height = 32,
                Width  = 32,
                Glyph  = new Glyph(pauseTexture)
                {
                    SizeMode = SizeMode.Normal
                },
                Parent   = toolBarTopPanel,
                CanFocus = false,
            };
            buttonPause.Click += delegate { buttonPause.Glyph.Texture = buttonPause.Glyph.Texture == pauseTexture ? pausePressedTexture : pauseTexture; };
            Texture stopTexture        = new Texture("Editor\\StopIconNotPressed");
            Texture stopPressedTexture = new Texture("Editor\\StopIcon");
            Button  buttonStop         = new Button
            {
                Left   = buttonPlay.Left + 68,
                Top    = 2,
                Height = 32,
                Width  = 32,
                Glyph  = new Glyph(stopTexture)
                {
                    SizeMode = SizeMode.Normal
                },
                Parent   = toolBarTopPanel,
                CanFocus = false,
            };
            buttonStop.Click += delegate { buttonStop.Glyph.Texture = buttonStop.Glyph.Texture == stopTexture ? stopPressedTexture : stopTexture; };

            #endregion

            // Adjust top panel height.
            topPanel.Height        = buttonStop.Top + buttonStop.Height + 2;
            toolBarTopPanel.Height = buttonStop.Top + buttonStop.Height + 2;

            #endregion

            #region Viewport Space

            // The canvas cover the whole window. I will place the static controls there.
            // I don’t place the controls directly to the manager to allow having some functionality
            // provided by the canvas like the automatic placing of menu items, status bar, etc.
            ViewportsSpace = new Container
            {
                Top             = 0,
                Left            = 0,
                Width           = canvas.ClientWidth - 420,
                Height          = canvas.ClientHeight,
                Anchor          = Anchors.All,
                AutoScroll      = false,
                BackgroundColor = Color.Transparent,
                StayOnBack      = true,
                Passive         = false,
                CanFocus        = false,
                Parent          = canvas,
            };

            #endregion

            #region Right Panel

            Panel rightPanel = new Panel
            {
                StayOnBack = true,
                Passive    = true,
                Parent     = canvas,
                Width      = 420,
                Left       = canvas.ClientWidth - 420,
                Height     = canvas.ClientHeight,
                Anchor     = Anchors.Right | Anchors.Top | Anchors.Bottom,
                Color      = new Color(64, 64, 64),
            };

            TabControl rightPanelTabControl = new TabControl
            {
                Parent = rightPanel,
                Left   = 2,
                Top    = 2,
                Width  = rightPanel.ClientWidth - 2,
                Height = rightPanel.ClientHeight - 2,
                Anchor = Anchors.All
            };
            rightPanelTabControl.AddPage();
            rightPanelTabControl.TabPages[0].Text = "Inspector";
            inspector = rightPanelTabControl.TabPages[0];
            rightPanelTabControl.AddPage();
            rightPanelTabControl.TabPages[1].Text = "Layers";
            var label = new Label
            {
                Parent = rightPanelTabControl.TabPages[1],
                Width  = 50,
                Top    = 15,
                Left   = rightPanelTabControl.TabPages[1].ClientWidth - 132,
                Text   = "Active",
                Height = 10,
            };
            label.ToolTip.Text = "Active layers are updated.";
            label = new Label
            {
                Parent = rightPanelTabControl.TabPages[1],
                Width  = 50,
                Top    = 15,
                Left   = rightPanelTabControl.TabPages[1].ClientWidth - 72,
                Text   = "Visible",
                Height = 10,
            };
            label.ToolTip.Text = "Visible layers are rendered.";
            for (int i = 0; i < 30; i++)
            {
                CommonControls.LayerBox(i, rightPanelTabControl.TabPages[1]);
            }

            #endregion
        } // AddMainControls
        /// <summary>
        /// Load the resources.
        /// </summary>
        protected override void LoadContent()
        {
            hitMaterial = new BlinnPhong {
                DiffuseColor = new Color(0.10f, 0.10f, 0.85f)
            };
            mat1 = new BlinnPhong {
                DiffuseColor = new Color(0.85f, 0.65f, 0f)
            };
            mat2 = new BlinnPhong {
                DiffuseColor = new Color(0.5f, 0.9f, 0.5f)
            };

            #region Physics Simulation Settings

            // Setup gravity.
            PhysicsManager.Gravity = new Vector3(0, -9.81f, 0);

            #endregion

            #region Camera

            camera = new GameObject3D();
            camera.AddComponent <Camera>();
            camera.AddComponent <SoundListener>();
            camera.Transform.LookAt(Vector3.Zero, Vector3.Forward, Vector3.Up);
            var script = (ScriptCustomCameraScript)camera.AddComponent <ScriptCustomCameraScript>();
            script.SetPosition(new Vector3(0, 15, 45), new Vector3(0, 5, 0));
            camera.Camera.RenderTargetSize = Size.FullScreen;
            camera.Camera.FarPlane         = 500;
            camera.Camera.NearPlane        = 1f;
            camera.Camera.ClearColor       = Color.Black;
            camera.Camera.FieldOfView      = 180f / 7f;
            camera.Camera.PostProcess      = new PostProcess();
            camera.Camera.PostProcess.ToneMapping.ToneMappingFunction = ToneMapping.ToneMappingFunctionEnumerate.FilmicALU;
            camera.Camera.PostProcess.ToneMapping.AutoExposureEnabled = false;
            camera.Camera.PostProcess.ToneMapping.LensExposure        = 0f;
            camera.Camera.PostProcess.MLAA.EdgeDetection          = MLAA.EdgeDetectionType.Both;
            camera.Camera.PostProcess.MLAA.Enabled                = false;
            camera.Camera.PostProcess.Bloom.Threshold             = 2;
            camera.Camera.PostProcess.FilmGrain.Enabled           = true;
            camera.Camera.PostProcess.FilmGrain.Strength          = 0.03f;
            camera.Camera.PostProcess.AnamorphicLensFlare.Enabled = false;
            camera.Camera.AmbientLight = new AmbientLight
            {
                Color     = new Color(20, 20, 25),
                Intensity = 0.5f,
                AmbientOcclusionStrength = 1f
            };

            #endregion

            #region Models and Physics

            // Make the floor (Kinematic) //
            // First, we create a bepu box entity that we will be used in our rigidbody component.
            // Notice that we don't specify the mass, so we are creating a kinematic entity.
            // Kinematic rigidbodies are moved through the transform component of the gameobject which it belongs.
            // Kinematic rigidbodies don't respond to collisions and can't collide with other kinematic rigidbodies. However, they can
            // collide with dynamic rigidbodies affecting them.
            var bepuGround = new Box(Vector3.Zero, 50, 1, 50);
            // Now, we create the game object and we add a rigidbody component to it.
            floor = new GameObject3D(new XNAFinalEngine.Assets.Box(50, 1, 50), new BlinnPhong {
                SpecularIntensity = 0.3f, SpecularPower = 200
            });
            var floorRb = (RigidBody)floor.AddComponent <RigidBody>();
            // Finally, we set the entity created previously to the rigidbody component
            floorRb.Entity = bepuGround;

            // Make a Cube (Dynamic) //
            // Now, we create a 1x1x1 bepu box entity that will appear 20 units above the floor.
            // Notice that this time we specify the entity's mass in order to create a dynamic entity.
            // Dynamic rigidbodies are affected by gravity and respond to collisions with other rigidbodies.
            // Dynamic rigidbodies are under the control of physics so they don't have to be moved or rotated through the transform component.
            var bepuCube = new Box(new Vector3(0, 20, 2), 1, 1, 1, 1);
            cube = new GameObject3D(new XNAFinalEngine.Assets.Box(1, 1, 1), new BlinnPhong {
                DiffuseColor = new Color(0.8f, 0.8f, 0.85f)
            });
            var cubeRb = (RigidBody)cube.AddComponent <RigidBody>();
            cubeRb.Entity = bepuCube;
            // Create a script for test collisions
            var          crt     = (CollisionResponseTestScript)cube.AddComponent <CollisionResponseTestScript>();
            GameObject2D debugGo = new GameObject2D();
            debugGo.Transform.Position = new Vector3(15f, Screen.Height - 90, 0f);
            crt.DebugText = (HudText)debugGo.AddComponent <HudText>();

            // Make an obstacle (Kinematic) //
            var bepuObstacle = new Box(new Vector3(0.5f, 1f, 0.5f), 4, 1, 1.5f);
            obstacle = new GameObject3D(new XNAFinalEngine.Assets.Box(4, 1, 1.5f), new BlinnPhong {
                DiffuseColor = new Color(0.9f, 0.2f, 0.15f), SpecularPower = 20
            });
            obstacle.Transform.Position = new Vector3(0.5f, 1f, 0.5f);
            var obstacleRb = (RigidBody)obstacle.AddComponent <RigidBody>();
            obstacleRb.Entity = bepuObstacle;

            // Make a wall of boxes //
            MakeWall(6, 9);

            // Make a sphere obstacle (Dynamic) //
            // The sphere model is not center in its model space, instead is displaced 10 units on Z.
            GameObject3D sphere;
            // First we creates this sphere with no physics representation.
            //sphere = new GameObject3D(new FileModel("SphereTransformed"), new BlinnPhong { DiffuseColor = new Color(1f, 0f, 0f), SpecularPower = 20 });
            // Then we creates the same sphere and asign a dynamic physic object representation.
            sphere = new GameObject3D(new FileModel("SphereTransformed"), new BlinnPhong {
                DiffuseColor = new Color(0.79f, 0.75f, 0.2f), SpecularPower = 20
            });
            // The initial motion state place the sphere just a little above.
            MotionState motionState = new MotionState {
                Position = new Vector3(0f, 10f, 0f), Orientation = Quaternion.Identity
            };
            // We create the physic object. The offset that creates Bepu is hide transparently.
            // Moreover the initial motion state takes in consideration this offset and places the sphere in the same x, z coordinates as the other sphere.
            ((RigidBody)sphere.AddComponent <RigidBody>()).CreateDynamicEntityFromModelFilter(motionState, 1);

            // Static mesh.
            var lamboBody = new GameObject3D(new FileModel("LamborghiniMurcielago\\Murcielago-Body"
#if XBOX
                                                           + "Xbox"
#endif
                                                           ), new BlinnPhong {
                DiffuseColor = Color.Gray
            });
            lamboBody.Transform.Position = new Vector3(-3, 3, 3);
            ((StaticCollider)lamboBody.AddComponent <StaticCollider>()).CreateStaticCollidableFromModelFilter();

            // Very Simple Crosshair //
            GameObject2D crosshair = new GameObject2D();
            crosshair.Transform.Position = new Vector3(Screen.Width / 2f, Screen.Height / 2f, 0f);
            var crossText = (HudText)crosshair.AddComponent <HudText>();
            crossText.Text.Append("+");

            #endregion

            #region Shadows and Lights

            Shadow.DistributeShadowCalculationsBetweenFrames = true;

            var pointLight = new GameObject3D();
            pointLight.AddComponent <PointLight>();
            pointLight.PointLight.Color     = new Color(180, 200, 250);
            pointLight.PointLight.Intensity = 4f;
            pointLight.PointLight.Range     = 60;
            pointLight.Transform.Position   = new Vector3(4.8f, 10f, 10);
            pointLight.PointLight.Shadow    = new CubeShadow {
                LightDepthTextureSize = 1024
            };

            var pointLight2 = new GameObject3D();
            pointLight2.AddComponent <PointLight>();
            pointLight2.PointLight.Color     = new Color(100, 110, 170);
            pointLight2.PointLight.Intensity = 1f;
            pointLight2.PointLight.Range     = 30;
            pointLight2.Transform.Position   = new Vector3(-12f, 10, -3);

            #endregion

            #region Demo Legend

            #region Legend Background

            Texture2D bg      = new Texture2D(EngineManager.Device, 1, 1, false, SurfaceFormat.Color);
            Color[]   bgColor = new Color[] { new Color(0f, 0f, 0f, 0.55f) };
            bg.SetData(bgColor);

            var bgTexture        = new XNAFinalEngine.Assets.Texture(bg);
            var backgroundLegend = new GameObject2D();
            backgroundLegend.Transform.Position = new Vector3(0f, 0f, 1f);
            var bgHudTex = (HudTexture)backgroundLegend.AddComponent <HudTexture>();
            bgHudTex.Texture = bgTexture;
            bgHudTex.DestinationRectangle = new Rectangle(0, Screen.Height - 115, Screen.Width, Screen.Height);

            #endregion

            var demoLegend = new GameObject2D();
            demoLegend.Transform.Position = new Vector3(Screen.Width - 380f, Screen.Height - 105f, 0f);
            var legend = (HudText)demoLegend.AddComponent <HudText>();
            legend.Color = new Color(1f, 1f, 1f, 1f);
            legend.Text.Append(" Controls\n");
            legend.Text.Append("\n");
            legend.Text.Append("- Press Left Ctrl to fire a Blue box.\n");
            legend.Text.Append("- Press Space to apply an Up impulse to the white box.\n");
            legend.Text.Append("- Press Left Shift to cast a ray that paints yellow and \n");
            legend.Text.Append("  applies an Up impulse to the GO that hits.\n");
            legend.Text.Append("- Press keys A, S, W, D, Q, E to move and rotate the red box");

            #endregion
        } // LoadContent
Exemple #11
0
        } // Begin

        #endregion

        #region Render

        /// <summary>
        /// Render the spot light.
        /// </summary>
        public void Render(Color diffuseColor, Vector3 position, Vector3 direction, float intensity,
                           float range, float innerConeAngle, float outerConeAngle, Texture shadowTexture, Texture lightMaskTexture,
                           Matrix worldMatrix, bool renderClipVolumeInLocalSpace, Model clipVolume = null)
        {
            try
            {
                #region Set Parameters

                spLightColor.Value     = diffuseColor;
                spLightPosition.Value  = Vector3.Transform(position, viewMatrix);
                spLightIntensity.Value = intensity;
                spInvLightRadius.Value = 1 / range;
                Vector3 directionVS = Vector3.TransformNormal(direction, viewMatrix);
                directionVS.Normalize();
                spLightDirection.Value      = directionVS;
                spLightInnerConeAngle.Value = innerConeAngle * (3.141592f / 180.0f);
                spLightOuterConeAngle.Value = outerConeAngle * (3.141592f / 180.0f);

                if (lightMaskTexture != null)
                {
                    Matrix lightViewMatrix       = Matrix.CreateLookAt(position, position + direction, Vector3.Up);
                    Matrix lightProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(outerConeAngle * (float)Math.PI / 180.0f, // field of view
                                                                                       1.0f,                                     // Aspect ratio
                                                                                       1f,                                       // Near plane
                                                                                       range);                                   // Far plane
                    spViewToLightViewProjMatrix.Value = Matrix.Invert(viewMatrix) * lightViewMatrix * lightProjectionMatrix;
                    spLightMaskTexture.Value          = lightMaskTexture;
                }
                else
                {
                    spLightMaskTexture.Value = Texture.BlackTexture; // To avoid a potential exception.
                }
                // Compute the light world matrix.
                Matrix boundingLightObjectWorldMatrix;
                if (clipVolume != null)
                {
                    boundingLightObjectWorldMatrix = renderClipVolumeInLocalSpace ? Matrix.Identity : worldMatrix;
                }
                else
                {
                    // Scale according to light radius, and translate it to light position.
                    boundingLightObjectWorldMatrix = Matrix.CreateScale(range) * Matrix.CreateTranslation(position); // TODO: when the cone model is exported I have to include the rotation into consideration.
                }
                spWorldViewProjMatrix.Value = boundingLightObjectWorldMatrix * viewMatrix * projectionMatrix;
                spWorldViewMatrix.Value     = boundingLightObjectWorldMatrix * viewMatrix;

                if (shadowTexture != null)
                {
                    spShadowTexture.Value     = shadowTexture;
                    Resource.CurrentTechnique = lightMaskTexture != null ? spotLightWithShadowsWithMaskTechnique : spotLightWithShadowsTechnique;
                }
                else
                {
                    spShadowTexture.Value     = Texture.BlackTexture; // To avoid a potential exception.
                    Resource.CurrentTechnique = lightMaskTexture != null ? spotLightWithMaskTechnique : spotLightTechnique;
                }

                #endregion

                // TODO: Implement the stencil optimization.

                // Calculate the distance between the camera and light center.
                float cameraToCenter = Vector3.Distance(Matrix.Invert(viewMatrix).Translation, position) - nearPlane;
                // If we are inside the light volume, draw the sphere's inside face.
                if (cameraToCenter <= range)
                {
                    EngineManager.Device.DepthStencilState = interiorOfBoundingVolumeDepthStencilState;
                    EngineManager.Device.RasterizerState   = RasterizerState.CullClockwise;
                }
                else
                {
                    EngineManager.Device.DepthStencilState = DepthStencilState.DepthRead;
                    EngineManager.Device.RasterizerState   = RasterizerState.CullCounterClockwise;
                }

                Resource.CurrentTechnique.Passes[0].Apply();
                if (clipVolume != null)
                {
                    clipVolume.Render();
                }
                else
                {
                    boundingLightObject.Render();
                }
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Light Pre Pass Spot Light: Unable to render.", e);
            }
        } // Render
        /// <summary>
        /// Creates the configuration controls of this asset.
        /// </summary>
        public static void AddControls(Texture asset, Window owner, ComboBox comboBoxResource)
        {
            // In asset creation I need to look on the CurrentCreatedAsset property to have the last asset.
            // I can't use CurrentCreatedAsset in edit mode.
            // However I can use asset for creation (maybe in a disposed state but don't worry) and edit mode,
            // and only update the values when I know that CurrentCreatedAsset changes.
            
            #region Group Image

            var groupImage = CommonControls.Group("Image", owner);
            var imageBoxImage = CommonControls.ImageBox(asset, groupImage);
            groupImage.AdjustHeightFromChildren();

            #endregion
            
            #region Group Properties

            GroupBox groupProperties = CommonControls.Group("Properties", owner);

            var widthTextBox = CommonControls.TextBox("Width", groupProperties, asset.Width.ToString());
            widthTextBox.Enabled = false;

            var heightTextBox = CommonControls.TextBox("Height", groupProperties, asset.Height.ToString());
            heightTextBox.Enabled = false;

            #region Prefered Sampler State

            var comboBoxPreferredSamplerState = CommonControls.ComboBox("Prefered Sampler State", groupProperties);
            comboBoxPreferredSamplerState.Items.Add("AnisotropicClamp");
            comboBoxPreferredSamplerState.Items.Add("AnisotropicWrap");
            comboBoxPreferredSamplerState.Items.Add("LinearClamp");
            comboBoxPreferredSamplerState.Items.Add("LinearWrap");
            comboBoxPreferredSamplerState.Items.Add("PointClamp");
            comboBoxPreferredSamplerState.Items.Add("PointWrap");
            
            comboBoxPreferredSamplerState.ItemIndexChanged += delegate { asset.PreferredSamplerState = GetSamplerState(comboBoxPreferredSamplerState.ItemIndex); };
            comboBoxPreferredSamplerState.Draw += delegate
            {
                if (comboBoxPreferredSamplerState.ListBoxVisible)
                    return;
                // Identify current index
                if (asset.PreferredSamplerState == SamplerState.AnisotropicClamp)
                    comboBoxPreferredSamplerState.ItemIndex = 0;
                else if (asset.PreferredSamplerState == SamplerState.AnisotropicWrap)
                    comboBoxPreferredSamplerState.ItemIndex = 1;
                else if (asset.PreferredSamplerState == SamplerState.LinearClamp)
                    comboBoxPreferredSamplerState.ItemIndex = 2;
                else if (asset.PreferredSamplerState == SamplerState.LinearWrap)
                    comboBoxPreferredSamplerState.ItemIndex = 3;
                else if (asset.PreferredSamplerState == SamplerState.PointClamp)
                    comboBoxPreferredSamplerState.ItemIndex = 4;
                else if (asset.PreferredSamplerState == SamplerState.PointWrap)
                    comboBoxPreferredSamplerState.ItemIndex = 5;
                else
                {
                    if (customSamplerState == null)
                    {
                        comboBoxPreferredSamplerState.Items.Add("Custom");
                        customSamplerState = asset.PreferredSamplerState;
                    }
                    comboBoxPreferredSamplerState.ItemIndex = 6;
                }
            };

            #endregion

            groupProperties.AdjustHeightFromChildren();

            #endregion

            // If it is asset creation time.
            if (comboBoxResource != null)
            {
                comboBoxResource.ItemIndexChanged += delegate
                {
                    // Update properties if the resource changes.
                    imageBoxImage.Texture = ((Texture)AssetWindow.CurrentCreatedAsset);
                    widthTextBox.Text     = ((Texture)AssetWindow.CurrentCreatedAsset).Width.ToString();
                    heightTextBox.Text    = ((Texture)AssetWindow.CurrentCreatedAsset).Height.ToString();
                };
                // If the user creates the asset (pressed the create button) then update the changeable properties.
                owner.Closed += delegate
                {
                    if (owner.ModalResult != ModalResult.Cancel)
                        ((Texture)AssetWindow.CurrentCreatedAsset).PreferredSamplerState = GetSamplerState(comboBoxPreferredSamplerState.ItemIndex);
                };
            }
        } // AddControls
        } // GetParameters

        #endregion

        #region Render

        /// <summary>
        /// Render.
        /// </summary>
        public RenderTarget Render(RenderTarget texture, Texture depthTexture, PostProcess postProcess, RenderTarget destinationTexture)
        {
            if (texture == null || texture.Resource == null)
            {
                throw new ArgumentNullException("texture");
            }
            if (postProcess == null)
            {
                throw new ArgumentNullException("postProcess");
            }
            if (postProcess.MLAA == null || !(postProcess.MLAA.Enabled))
            {
                throw new ArgumentException("MLAA Shader: MLAA properties can not be null.");
            }
            try
            {
                // Fetch render targets.
                RenderTarget blendingWeightTexture = RenderTarget.Fetch(texture.Size, SurfaceFormat.Color, DepthFormat.None, RenderTarget.AntialiasingType.NoAntialiasing);

                // Set render states
                EngineManager.Device.BlendState        = BlendState.Opaque;
                EngineManager.Device.DepthStencilState = DepthStencilState.None;
                EngineManager.Device.RasterizerState   = RasterizerState.CullCounterClockwise;

                // Set parameters
                spHalfPixel.Value      = new Vector2(-0.5f / (texture.Width / 2), 0.5f / (texture.Height / 2));
                spPixelSize.Value      = new Vector2(1f / texture.Width, 1f / texture.Height);
                spSceneTexture.Value   = texture; EngineManager.Device.SamplerStates[11] = SamplerState.LinearClamp; // The scene texture has two samplers.
                spDepthTexture.Value   = depthTexture;
                spThresholdColor.Value = postProcess.MLAA.ThresholdColor;
                spThresholdDepth.Value = postProcess.MLAA.ThresholdDepth;
                spAreaTexture.Value    = areaTexture;

                switch (postProcess.MLAA.EdgeDetection)
                {
                case MLAA.EdgeDetectionType.Both:  Resource.CurrentTechnique = Resource.Techniques["EdgeDetectionColorDepth"]; break;

                case MLAA.EdgeDetectionType.Color: Resource.CurrentTechnique = Resource.Techniques["EdgeDetectionColor"]; break;

                case MLAA.EdgeDetectionType.Depth: Resource.CurrentTechnique = Resource.Techniques["EdgeDetectionDepth"]; break;
                }

                // To avoid an exception that is produced with adaptative exposure is enable in the first camera rendered.
                // It seems the lastLuminanceTexture is still link to this sampler and when the technique is apply did not like this situation.
                // I am not sure why.
                // A possible solution is to reservate a small number of samplers for linear and anisotropic access and the rest for point.
                EngineManager.Device.SamplerStates[12] = SamplerState.PointClamp;

                foreach (EffectPass pass in Resource.CurrentTechnique.Passes)
                {
                    if (pass.Name == "EdgeDetection")
                    {
                        // Store the edge texture into the result texture to reduce memory consumption.
                        destinationTexture.EnableRenderTarget();
                        destinationTexture.Clear(Color.Black);
                    }
                    else if (pass.Name == "BlendingWeight")
                    {
                        spEdgeTexture.Value = destinationTexture;
                        blendingWeightTexture.EnableRenderTarget();
                        blendingWeightTexture.Clear(new Color(0, 0, 0, 0));
                    }
                    else
                    {
                        // For testing

                        /*RenderTarget.Release(blendingWeightTexture);
                         * return destinationTexture;*/
                        spBlendedWeightsTexture.Value = blendingWeightTexture;
                        destinationTexture.EnableRenderTarget();
                        destinationTexture.Clear(Color.Black);
                    }

                    pass.Apply();
                    RenderScreenPlane();

                    if (pass.Name == "EdgeDetection")
                    {
                        destinationTexture.DisableRenderTarget();
                    }
                    else if (pass.Name == "BlendingWeight")
                    {
                        blendingWeightTexture.DisableRenderTarget();
                    }
                    else
                    {
                        destinationTexture.DisableRenderTarget();
                    }
                }
                // It's not used anymore.
                RenderTarget.Release(blendingWeightTexture);
                return(destinationTexture);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("MLAA Shader: Unable to render.", e);
            }
        } // Render
Exemple #14
0
        } // GetParameters

        #endregion

        #region Render

        /// <summary>
        /// Generate Bloom Texture.
        /// </summary>
        internal RenderTarget Render(Texture sceneTexture, Texture luminanceTexture, PostProcess postProcess)
        {
            if (postProcess == null)
            {
                throw new ArgumentNullException("postProcess");
            }
            if (sceneTexture == null || sceneTexture.Resource == null)
            {
                throw new ArgumentNullException("sceneTexture");
            }
            if (postProcess.Bloom == null)
            {
                throw new ArgumentException("Bloom Shader: Bloom properties can not be null.");
            }
            try
            {
                // Fetch auxiliary render target.
                Size bloomSize;
                if (sceneTexture.Size == Size.FullScreen) // A common case
                {
                    bloomSize = Size.QuarterScreen;
                }
                else if (sceneTexture.Size == Size.SplitFullScreen) // The second common case
                {
                    bloomSize = Size.SplitQuarterScreen;
                }
                else
                {
                    bloomSize = new Size(sceneTexture.Width / 4, sceneTexture.Height / 4);
                }
                RenderTarget bloomTexture = RenderTarget.Fetch(bloomSize, SurfaceFormat.Color, DepthFormat.None, RenderTarget.AntialiasingType.NoAntialiasing);

                // Set Render States.
                EngineManager.Device.BlendState        = BlendState.Opaque;
                EngineManager.Device.DepthStencilState = DepthStencilState.None;
                EngineManager.Device.RasterizerState   = RasterizerState.CullCounterClockwise;

                // Set Parameters.
                spHalfPixel.Value = new Vector2(-0.5f / (bloomTexture.Width / 2), 0.5f / (bloomTexture.Height / 2));

                // Lens Exposure
                #region Tone Mapping

                spAutoExposure.Value = postProcess.ToneMapping.AutoExposureEnabled;
                if (postProcess.ToneMapping.AutoExposureEnabled)
                {
                    spLastLuminanceTexture.Value = luminanceTexture;
                }
                else
                {
                    spLastLuminanceTexture.Value = null;
                    spLensExposure.Value         = postProcess.ToneMapping.LensExposure;
                }

                #endregion

                spBloomThreshold.Value = postProcess.Bloom.Threshold;
                spSceneTexture.Value   = sceneTexture;

                for (int i = 0; i < 16; i++)
                {
                    EngineManager.Device.SamplerStates[i] = SamplerState.PointClamp; // TODO. Bug in the samplers.
                }
                // Render it.
                bloomTexture.EnableRenderTarget();
                Resource.CurrentTechnique.Passes[0].Apply();
                RenderScreenPlane();
                bloomTexture.DisableRenderTarget();

                // Blur it.
                BlurShader.Instance.Filter(bloomTexture, bloomTexture, 1);

                return(bloomTexture);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Bloom Shader: Unable to render.", e);
            }
        } // Render
        } // Begin3D

        /// <summary>
        /// Begins a sprite batch operation in 3D.
        /// </summary>
        public static void Begin3DGammaSpace(Matrix viewMatrix, Matrix projectionMatrix, Texture depthTexture, float farPlane)
        {
            if (spriteBatch == null)
            {
                throw new Exception("The Sprite Manager is not initialized.");
            }
            if (begined)
            {
                throw new InvalidOperationException("Sprite Manager: Begin has been called before calling End after the last call to Begin. Begin cannot be called again until End has been successfully called.");
            }

            // In PC BlendState.AlphaBlend is a little more expensive than BlendState.Opaque when alpha = 1.
            // But PC is the powerful platform so no need to choose between the two.
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState3D, DepthStencilState.None, RasterizerState.CullCounterClockwise, SpriteShader.Instance.Resource);

            SpriteShader.Instance.BeginGammaSpace(viewMatrix, projectionMatrix, depthTexture, farPlane);

            begined = true;
            begin2D = false;
        } // Begin3D
        } // GetParameters

        #endregion

        #region Render

        /// <summary>
        /// Generate Bloom Texture.
        /// </summary>
        internal RenderTarget Render(Texture halfDepthTexture, Texture bloomTexture, PostProcess postProcess, Matrix viewMatrix, Matrix projectionMatrix, float farPlane, Vector3 cameraPosition)
        {
            if (postProcess == null)
            {
                throw new ArgumentNullException("postProcess");
            }
            if (halfDepthTexture == null || halfDepthTexture.Resource == null)
            {
                throw new ArgumentNullException("halfDepthTexture");
            }
            if (postProcess.AnamorphicLensFlare == null)
            {
                throw new ArgumentException("Anamorphic Lens Flare Shader: Anamorphic lens flare properties can not be null.");
            }
            try
            {
                // Fetch auxiliary render target.
                RenderTarget lensFlareTexture = RenderTarget.Fetch(halfDepthTexture.Size, SurfaceFormat.Color, DepthFormat.None, RenderTarget.AntialiasingType.NoAntialiasing);

                // Set Render States.
                EngineManager.Device.BlendState        = BlendState.Opaque;
                EngineManager.Device.DepthStencilState = DepthStencilState.None;
                EngineManager.Device.RasterizerState   = RasterizerState.CullCounterClockwise;

                #region First pass: sun rendering and occlusion test.

                lensFlareTexture.EnableRenderTarget();
                lensFlareTexture.Clear(Color.Black);
                // Set Parameters
                spHalfPixel.Value    = new Vector2(0.5f / lensFlareTexture.Width, 0.5f / lensFlareTexture.Height);
                spDepthTexture.Value = halfDepthTexture;
                spFarPlane.Value     = farPlane;
                cameraPosition.Z     = cameraPosition.Z - (farPlane - 10);
                Matrix worldMatrix = Matrix.CreateScale((farPlane * 2.25f) / 100) * Matrix.CreateTranslation(cameraPosition);
                spWorldViewProj.Value = worldMatrix * viewMatrix * projectionMatrix;
                spWorldView.Value     = worldMatrix * viewMatrix;
                spSunColor.Value      = new Color(1.0f, 0.9f, 0.70f);
                // Render
                Resource.CurrentTechnique.Passes[0].Apply();
                sunObject.Render();
                lensFlareTexture.DisableRenderTarget();

                #endregion

                // The second and third pass were removed to improve performance.

                #region Fourth pass: high blur vertical

                RenderTarget highBlurredSunTextureVertical = RenderTarget.Fetch(halfDepthTexture.Size, SurfaceFormat.Color, DepthFormat.None, RenderTarget.AntialiasingType.NoAntialiasing);
                highBlurredSunTextureVertical.EnableRenderTarget();
                highBlurredSunTextureVertical.Clear(Color.Black);
                spHalfPixel.Value    = new Vector2(-0.5f / (lensFlareTexture.Width / 2), 0.5f / (lensFlareTexture.Height / 2));
                spSceneTexture.Value = lensFlareTexture; // bloomTexture;
                Resource.CurrentTechnique.Passes[3].Apply();
                RenderScreenPlane();
                highBlurredSunTextureVertical.DisableRenderTarget();

                #endregion

                #region Fifth pass: high blur horizontal

                RenderTarget highBlurredSunTexture = RenderTarget.Fetch(halfDepthTexture.Size, SurfaceFormat.Color, DepthFormat.None, RenderTarget.AntialiasingType.NoAntialiasing);
                highBlurredSunTexture.EnableRenderTarget();
                highBlurredSunTexture.Clear(Color.Black);
                spSceneTexture.Value = highBlurredSunTextureVertical;
                Resource.CurrentTechnique.Passes[4].Apply();
                RenderScreenPlane();
                highBlurredSunTexture.DisableRenderTarget();
                RenderTarget.Release(highBlurredSunTextureVertical);

                #endregion

                #region Last pass: composite images

                lensFlareTexture.EnableRenderTarget();
                lensFlareTexture.Clear(Color.Black);
                // Set Parameters
                spHighBlurredSunTexture.Value = highBlurredSunTexture;
                spDispersal.Value             = postProcess.AnamorphicLensFlare.Dispersal;
                spHaloWidth.Value             = postProcess.AnamorphicLensFlare.HaloWidth;
                spIntensity.Value             = postProcess.AnamorphicLensFlare.Intensity;
                spDistortion.Value            = postProcess.AnamorphicLensFlare.ChromaticDistortion;
                spDirtTexture.Value           = postProcess.AnamorphicLensFlare.DirtTexture ?? Texture.BlackTexture;
                // uv coordinates of the sun position on the screen.
                Vector4 sunPosProjected = Vector4.Transform(new Vector4(cameraPosition.X, cameraPosition.Y, cameraPosition.Z, 1), viewMatrix * projectionMatrix * BiasMatrix());
                sunPosProjected    = sunPosProjected / sunPosProjected.W;
                spSunPosProj.Value = new Vector2(sunPosProjected.X, 1 - sunPosProjected.Y);
                // Render
                Resource.CurrentTechnique.Passes[5].Apply();
                RenderScreenPlane();
                lensFlareTexture.DisableRenderTarget();

                #endregion

                // Release the rest of the render targets.
                RenderTarget.Release(highBlurredSunTexture);
                return(lensFlareTexture);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Anamorphic Lens Flare Shader: Unable to render.", e);
            }
        } // Render
Exemple #17
0
        } // GetParametersHandles

        #endregion

        #region Begin

        /// <summary>
        /// Begins the render.
        /// </summary>
        internal void Begin(Matrix viewMatrix, Matrix projectionMatrix, float aspectRatio, float farPlane, Size cameraSize, Texture depthTexture)
        {
            try
            {
                // Set initial parameters
                spViewProjection.Value   = viewMatrix * projectionMatrix;
                spProjection.Value       = projectionMatrix;
                spProjectionInvert.Value = Matrix.Invert(projectionMatrix);

                spViewportScale.Value = new Vector2(0.5f / aspectRatio, -0.5f);
                spFarPlane.Value      = farPlane;
                spHalfPixel.Value     = new Vector2(0.5f / cameraSize.Width, 0.5f / cameraSize.Height); // The half depth size produce flickering.
                spDepthTexture.Value  = depthTexture;
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Particle Shader: Unable to begin the rendering.", e);
            }
        } // Begin
Exemple #18
0
        /// <summary>
        /// Process
        /// </summary>
        /// <param name="sceneTexture">Linear space HDR scene texture.</param>
        /// <param name="depthTexture">Depth texture.</param>
        /// <param name="halfDepthTexture">Half resolution depth texture.</param>
        /// <param name="postProcess">Post process parameters.</param>
        /// <param name="luminanceTexture">This texture stores the previous luminance information.</param>
        /// <param name="destinationTexture">The gamma space post process texture of the linear space scene texture.</param>
        public static void BeginAndProcess(PostProcess postProcess, Texture sceneTexture, Texture depthTexture, Texture halfDepthTexture,
                                           ref RenderTarget luminanceTexture, RenderTarget destinationTexture,
                                           Matrix viewMatrix, Matrix projectionMatrix, float farPlane, Vector3 cameraPosition, Vector3[] boundingFrustum)
        {
            if (destinationTexture == null)
            {
                throw new ArgumentNullException("destinationTexture");
            }
            if (sceneTexture == null || sceneTexture.Resource == null)
            {
                throw new ArgumentNullException("sceneTexture");
            }
            if (sceneTexture == null || sceneTexture.Resource == null)
            {
                throw new ArgumentNullException("depthTexture");
            }

            //try
            {
                // Set render states
                EngineManager.Device.BlendState        = BlendState.Opaque;
                EngineManager.Device.DepthStencilState = DepthStencilState.None;
                EngineManager.Device.RasterizerState   = RasterizerState.CullCounterClockwise;

                // To avoid a potential exception. TODO: Rearrange the samplers or separete the auto exposure function to another FX file.
                for (int i = 0; i < 16; i++)
                {
                    EngineManager.Device.Textures[i]      = null;
                    EngineManager.Device.SamplerStates[i] = SamplerState.PointClamp;
                }

                PostProcessingPass.depthTexture = depthTexture;
                PostProcessingPass.postProcess  = postProcess;

                // Retrieve the post process shader instance reference.
                postProcessingShader = PostProcessingShader.Instance;

                // Tone Mapping Auto Exposure.
                if (postProcess != null && postProcess.ToneMapping.AutoExposureEnabled)
                {
                    // Luminance Map Generation. Transform the color information to just luminance. It also gives a downsample texture.
                    RenderTarget currentLuminanceTexture = postProcessingShader.LuminanceTextureGeneration(sceneTexture, postProcess);

                    // Luminance Adaptation
                    luminanceTexture = postProcessingShader.LuminanceAdaptation(currentLuminanceTexture, luminanceTexture, postProcess);
                    RenderTarget.Release(currentLuminanceTexture);
                }

                // Generate bloom texture
                RenderTarget bloomTexture = null;
                if (postProcess != null && postProcess.Bloom != null && postProcess.Bloom.Enabled)
                {
                    bloomTexture = BloomShader.Instance.Render(sceneTexture, luminanceTexture, postProcess);
                }

                RenderTarget lensFlareTexture = null;
                if (postProcess != null && postProcess.AnamorphicLensFlare != null && postProcess.AnamorphicLensFlare.Enabled)
                {
                    lensFlareTexture = AnamorphicLensFlareShader.Instance.Render(halfDepthTexture, bloomTexture, postProcess, viewMatrix, projectionMatrix, farPlane, cameraPosition);
                }

                // If MLAA is active the shader needs an extra render target.)
                if (postProcess != null && postProcess.MLAA != null && postProcess.MLAA.Enabled)
                {
                    postProcessedSceneTexture = RenderTarget.Fetch(sceneTexture.Size, SurfaceFormat.Color, DepthFormat.None, RenderTarget.AntialiasingType.NoAntialiasing);
                    mlaaTexture = destinationTexture;
                }
                else
                {
                    postProcessedSceneTexture = destinationTexture;
                }

                postProcessedSceneTexture.EnableRenderTarget();
                // Post process the scene texture.
                postProcessingShader.Render(sceneTexture, depthTexture, postProcess, bloomTexture, lensFlareTexture, luminanceTexture, boundingFrustum, cameraPosition, viewMatrix);
                // Release textures (they return to the pool).
                if (bloomTexture != null)
                {
                    RenderTarget.Release(bloomTexture);
                }
                if (lensFlareTexture != null)
                {
                    RenderTarget.Release(lensFlareTexture);
                }
            }

            /*catch (Exception e)
             * {
             *  throw new InvalidOperationException("Post Process: Unable to render.", e);
             * }*/
        } // BeginAndProcess
Exemple #19
0
        } // LuminanceAdaptation

        #endregion

        #region Render

        /// <summary>
        /// Render.
        /// </summary>
        public void Render(Texture sceneTexture, Texture depthTexture, PostProcess postProcess, RenderTarget bloomTexture, RenderTarget lensFlareTexture, RenderTarget luminanceTexture,
                           Vector3[] boundingFrustum, Vector3 cameraPosition, Matrix viewMatrix)
        {
            if (sceneTexture == null || sceneTexture.Resource == null)
                throw new ArgumentNullException("sceneTexture");
            //try
            {
                if (postProcess != null)
                {
                    // Select technique with the tone mapping function.
                    switch (postProcess.ToneMapping.ToneMappingFunction)
                    {
                        case ToneMapping.ToneMappingFunctionEnumerate.FilmicALU        : Resource.CurrentTechnique = Resource.Techniques["PostProcessingFilmicALU"];
                            spFilmLutTexture.Value = filmLutTexture;
                            break;
                        case ToneMapping.ToneMappingFunctionEnumerate.FilmicUncharted2 : Resource.CurrentTechnique = Resource.Techniques["PostProcessingFilmicUncharted2"];
                            spShoulderStrength.Value = postProcess.ToneMapping.Uncharted2ShoulderStrength;
                            spLinearStrength.Value = postProcess.ToneMapping.Uncharted2LinearStrength;
                            spLinearAngle.Value = postProcess.ToneMapping.Uncharted2LinearAngle;
                            spToeStrength.Value = postProcess.ToneMapping.Uncharted2ToeStrength;
                            spToeNumerator.Value = postProcess.ToneMapping.Uncharted2ToeNumerator;
                            spToeDenominator.Value = postProcess.ToneMapping.Uncharted2ToeDenominator;
                            spLinearWhite.Value = postProcess.ToneMapping.Uncharted2LinearWhite;
                            break;
                        case ToneMapping.ToneMappingFunctionEnumerate.Reinhard         : Resource.CurrentTechnique = Resource.Techniques["PostProcessingReinhard"];
                            spLuminanceSaturation.Value = postProcess.ToneMapping.ToneMappingLuminanceSaturation;
                            break;
                        case ToneMapping.ToneMappingFunctionEnumerate.ReinhardModified : Resource.CurrentTechnique = Resource.Techniques["PostProcessingReinhardModified"];
                            spLuminanceSaturation.Value = postProcess.ToneMapping.ToneMappingLuminanceSaturation;
                            spWhiteLevel.Value = postProcess.ToneMapping.ToneMappingWhiteLevel;
                            break;
                        case ToneMapping.ToneMappingFunctionEnumerate.Exponential      : Resource.CurrentTechnique = Resource.Techniques["PostProcessingExponential"];
                            spLuminanceSaturation.Value = postProcess.ToneMapping.ToneMappingLuminanceSaturation;
                            spWhiteLevel.Value = postProcess.ToneMapping.ToneMappingWhiteLevel;
                            break;
                        case ToneMapping.ToneMappingFunctionEnumerate.Logarithmic      : Resource.CurrentTechnique = Resource.Techniques["PostProcessingLogarithmic"];
                            spLuminanceSaturation.Value = postProcess.ToneMapping.ToneMappingLuminanceSaturation;
                            spWhiteLevel.Value = postProcess.ToneMapping.ToneMappingWhiteLevel;
                            break;
                        case ToneMapping.ToneMappingFunctionEnumerate.DragoLogarithmic : Resource.CurrentTechnique = Resource.Techniques["PostProcessingDragoLogarithmic"];
                            spLuminanceSaturation.Value = postProcess.ToneMapping.ToneMappingLuminanceSaturation;
                            spWhiteLevel.Value = postProcess.ToneMapping.ToneMappingWhiteLevel;
                            spBias.Value = postProcess.ToneMapping.DragoBias;
                            break;
                        case ToneMapping.ToneMappingFunctionEnumerate.Duiker           : Resource.CurrentTechnique = Resource.Techniques["PostProcessingDuiker"]; break;
                    }
                    // Set parameters
                    spHalfPixel.Value = new Vector2(-0.5f / (sceneTexture.Width / 2), 0.5f / (sceneTexture.Height / 2));
                    spFrustumCorners.Value = boundingFrustum;
                    spSceneTexture.Value = sceneTexture;

                    #region Fog

                    spDepthTexture.Value = depthTexture;
                    spCameraPosition.Value = cameraPosition;
                    Resource.Parameters["viewI"].SetValue(Matrix.Invert(Matrix.Transpose(Matrix.Invert(viewMatrix))));

                    #endregion

                    #region Tone Mapping

                    spAutoExposureEnabled.Value = postProcess.ToneMapping.AutoExposureEnabled;
                    if (postProcess.ToneMapping.AutoExposureEnabled)
                        spLastLuminanceTexture.Value = luminanceTexture;
                    else
                        spLensExposure.Value = postProcess.ToneMapping.LensExposure;

                    #endregion

                    #region Bloom

                    if (postProcess.Bloom != null && postProcess.Bloom.Enabled)
                    {
                        spBloomEnabled.Value = true;
                        spBloomScale.Value = postProcess.Bloom.Scale;
                        spBloomTexture.Value = bloomTexture;
                    }
                    else
                        spBloomEnabled.Value = false;

                    #endregion

                    #region Lens Flare

                    spLensFlareTexture.Value = lensFlareTexture ?? Texture.BlackTexture;

                    #endregion

                    #region Levels

                    // Adjust Levels
                    if (postProcess.AdjustLevels != null && postProcess.AdjustLevels.Enabled)
                    {
                        spAdjustLevelsEnabled.Value = true;
                        spInputBlack.Value = postProcess.AdjustLevels.InputBlack;
                        spInputWhite.Value = postProcess.AdjustLevels.InputWhite;
                        spInputGamma.Value = postProcess.AdjustLevels.InputGamma;
                        spOutputBlack.Value = postProcess.AdjustLevels.OutputBlack;
                        spOutputWhite.Value = postProcess.AdjustLevels.OutputWhite;
                    }
                    else
                        spAdjustLevelsEnabled.Value = false;
                    // Adjust Levels Individual Channels
                    if (postProcess.AdjustLevelsIndividualChannels != null && postProcess.AdjustLevelsIndividualChannels.Enabled)
                    {
                        spAdjustLevelsIndividualChannelsEnabled.Value = true;
                        spInputBlackRgb.Value = postProcess.AdjustLevelsIndividualChannels.InputBlack;
                        spInputWhiteRgb.Value = postProcess.AdjustLevelsIndividualChannels.InputWhite;
                        spInputGammaRgb.Value = postProcess.AdjustLevelsIndividualChannels.InputGamma;
                        spOutputBlackRgb.Value = postProcess.AdjustLevelsIndividualChannels.OutputBlack;
                        spOutputWhiteRgb.Value = postProcess.AdjustLevelsIndividualChannels.OutputWhite;
                    }
                    else
                        spAdjustLevelsIndividualChannelsEnabled.Value = false;

                    #endregion

                    #region Color Correction

                    if (postProcess.ColorCorrection != null && postProcess.ColorCorrection.Enabled)
                    {
                        if (postProcess.ColorCorrection.FirstLookupTable == null || postProcess.ColorCorrection.LerpOriginalColorAmount == 0)
                        {
                            // No color correction
                            spColorCorrectOneLutEnabled.Value = false;
                            spColorCorrectTwoLutEnabled.Value = false;
                        }
                        else
                        {
                            spLookupTableScale.Value = ((float)(postProcess.ColorCorrection.FirstLookupTable.Size) - 1f) / (float)(postProcess.ColorCorrection.FirstLookupTable.Size);
                            spLookupTableOffset.Value = 1f / (2f * (float)(postProcess.ColorCorrection.FirstLookupTable.Size));
                            if (postProcess.ColorCorrection.SecondLookupTable == null || postProcess.ColorCorrection.LerpLookupTablesAmount == 0)
                            {
                                // Lerp between two lookup tables
                                spColorCorrectOneLutEnabled.Value = true;
                                spColorCorrectTwoLutEnabled.Value = false;
                                spFirstlookupTable.Value = postProcess.ColorCorrection.FirstLookupTable;
                                spLerpOriginalColorAmount.Value = postProcess.ColorCorrection.LerpOriginalColorAmount;
                            }
                            else
                            {
                                // One lookup table
                                spColorCorrectOneLutEnabled.Value = false;
                                spColorCorrectTwoLutEnabled.Value = true;
                                spFirstlookupTable.Value = postProcess.ColorCorrection.FirstLookupTable;
                                spSecondlookupTable.Value = postProcess.ColorCorrection.SecondLookupTable;
                                spLerpOriginalColorAmount.Value = postProcess.ColorCorrection.LerpOriginalColorAmount;
                                spLerpLookupTablesAmount.Value = postProcess.ColorCorrection.LerpLookupTablesAmount;
                            }
                        }
                    }
                    else
                    {
                        spColorCorrectOneLutEnabled.Value = false;
                        spColorCorrectTwoLutEnabled.Value = false;
                    }


                    #endregion

                    #region Film Grain

                    if (postProcess.FilmGrain != null && postProcess.FilmGrain.Enabled && postProcess.FilmGrain.Strength != 0)
                    {
                        spFilmGrainEnabled.Value = true;
                        spFilmGrainStrength.Value = postProcess.FilmGrain.Strength;
                        spAccentuateDarkNoisePower.Value = postProcess.FilmGrain.AccentuateDarkNoisePower;
                        spRandomNoiseStrength.Value = postProcess.FilmGrain.RandomNoiseStrength;
                        spRandomValue.Value = randomNumber.Next(1, 10000) / 100.0f;
                    }
                    else
                        spFilmGrainEnabled.Value = false;

                    #endregion

                    // Render post process effect.
                    Resource.CurrentTechnique.Passes[0].Apply();
                    RenderScreenPlane();
                }
                else
                {
                    SpriteManager.DrawTextureToFullScreen(sceneTexture, false);
                }
            }
            /*catch (Exception e)
            {
                throw new InvalidOperationException("Post Process Shader: Unable to render.", e);
            }*/
        } // Render