示例#1
0
        public MaterialPtr RenderPreview()
        {
            string textureName  = "RttTex_Character_" + Guid.NewGuid().ToString();
            string materialName = "RttMat_Character_" + Guid.NewGuid().ToString();

            TexturePtr rttTexture =
                TextureManager.Singleton.CreateManual(
                    textureName,
                    ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                    TextureType.TEX_TYPE_2D,
                    GameManager.Instance.renderWindow.Width,
                    GameManager.Instance.renderWindow.Height,
                    0,
                    PixelFormat.PF_R8G8B8,
                    (int)TextureUsage.TU_RENDERTARGET);

            RenderTexture renderTexture = rttTexture.GetBuffer().GetRenderTarget();

            renderTexture.AddViewport(camera);
            renderTexture.GetViewport(0).SetClearEveryFrame(false);
            renderTexture.GetViewport(0).BackgroundColour = new ColourValue(0, 0, 0, 0);
            renderTexture.Update();

            MaterialPtr materialPtr = MaterialManager.Singleton.Create(materialName, ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME);

            materialPtr.GetTechnique(0).GetPass(0).SetSceneBlending(SceneBlendType.SBT_TRANSPARENT_ALPHA);
            materialPtr.GetTechnique(0).GetPass(0).CreateTextureUnitState().SetTextureName(textureName);

            return(materialPtr);
        }
示例#2
0
        private void InitCameraViewFromTarget()
        {
            int textureSize = 1024;

            cameraTexture = TextureManager.Instance.Create(
                TextureManager.Instance.GetUniqueName("RemoteView"), Texture.Type.Type2D,
                new Vec2I(textureSize, textureSize), 1, 0, PixelFormat.R8G8B8, Texture.Usage.RenderTarget);

            RenderTexture renderTexture = cameraTexture.GetBuffer().GetRenderTarget();

            rmCamera = SceneManager.Instance.CreateCamera("RemoteView");
            rmCamera.ProjectionType = ProjectionTypes.Perspective;
            rmCamera.PolygonMode    = PolygonMode.Wireframe;

            renderTexture.AddViewport(rmCamera);
        }
示例#3
0
            ///////////////

            private bool CreateRenderTexture()
            {
                Vec2I size = new Vec2I(512, 256);

                string textureName = TextureManager.Instance.GetUniqueName("RenderToTextureExample");

                texture = TextureManager.Instance.Create(textureName, Texture.Type.Type2D, size, 1, 0,
                                                         PixelFormat.R8G8B8, Texture.Usage.RenderTarget);
                if (texture == null)
                {
                    return(false);
                }

                renderTexture = texture.GetBuffer().GetRenderTarget();
                //you can update render texture manually by means renderTexture.Update() method. For this task set AutoUpdate = false;
                renderTexture.AutoUpdate = true;

                //create camera
                string cameraName = SceneManager.Instance.GetUniqueCameraName("RenderToTextureExample");

                camera         = SceneManager.Instance.CreateCamera(cameraName);
                camera.Purpose = Camera.Purposes.Special;
                camera.AllowMapCompositorManager = false;

                //add viewport
                viewport = renderTexture.AddViewport(camera);
                viewport.BackgroundColor = new ColorValue(0, 0, 0, 1);
                viewport.ShadowsEnabled  = false;
                viewport.MaterialScheme  = "";

                //add listener
                renderTargetListener = new SceneRenderTargetListener(this);
                renderTexture.AddListener(renderTargetListener);

                return(true);
            }
        private bool CreateRenderTarget()
        {
            DestroyRenderTarget();

            if (RendererWorld.Instance == null)
            {
                return(false);
            }

            Vec2I textureSize = GetDemandTextureSize();

            if (textureSize.X < 1 || textureSize.Y < 1)
            {
                return(false);
            }

            string textureName = TextureManager.Instance.GetUniqueName("WPFRenderTexture");

            int hardwareFSAA = 0;

            if (!RendererWorld.InitializationOptions.AllowSceneMRTRendering)
            {
                if (!int.TryParse(RendererWorld.InitializationOptions.FullSceneAntialiasing, out hardwareFSAA))
                {
                    hardwareFSAA = 0;
                }
            }

            texture = TextureManager.Instance.Create(textureName, Texture.Type.Type2D, textureSize,
                                                     1, 0, Engine.Renderer.PixelFormat.R8G8B8, Texture.Usage.RenderTarget, false, hardwareFSAA);

            if (texture == null)
            {
                return(false);
            }

            currentTextureSize = textureSize;

            renderTexture                     = texture.GetBuffer().GetRenderTarget();
            renderTexture.AutoUpdate          = false;
            renderTexture.AllowAdditionalMRTs = true;

            camera = SceneManager.Instance.CreateCamera(
                SceneManager.Instance.GetUniqueCameraName("UserControl"));
            camera.Purpose = Camera.Purposes.MainCamera;

            //update camera settings
            camera.NearClipDistance = cameraNearFarClipDistance.Minimum;
            camera.FarClipDistance  = cameraNearFarClipDistance.Maximum;
            camera.AspectRatio      = (float)texture.Size.X / (float)texture.Size.Y;
            camera.FixedUp          = cameraFixedUp;
            camera.Position         = cameraPosition;
            camera.Direction        = cameraDirection;
            camera.Fov               = cameraFov;
            camera.ProjectionType    = cameraProjectionType;
            camera.OrthoWindowHeight = cameraOrthoWindowHeight;

            viewport = renderTexture.AddViewport(camera);

            //Initialize HDR compositor for HDR render technique
            if (EngineApp.RenderTechnique == "HDR")
            {
                viewport.AddCompositor("HDR", 0);
                viewport.SetCompositorEnabled("HDR", true);
            }

            //Initialize Fast Approximate Antialiasing (FXAA)
            {
                bool   useMRT = RendererWorld.InitializationOptions.AllowSceneMRTRendering;
                string fsaa   = RendererWorld.InitializationOptions.FullSceneAntialiasing;
                if ((useMRT && (fsaa == "" || fsaa == "RecommendedSetting") && IsActivateFXAAByDefault()) ||
                    fsaa == "FXAA")
                {
                    if (RenderSystem.Instance.HasShaderModel3())
                    {
                        InitializeFXAACompositor();
                    }
                }
            }

            //add listener
            renderTargetListener = new ViewRenderTargetListener(this);
            renderTexture.AddListener(renderTargetListener);

            if (guiRenderer == null)
            {
                guiRenderer = new GuiRenderer(viewport);
            }
            else
            {
                guiRenderer.ChangeViewport(viewport);
            }

            if (controlManager == null)
            {
                controlManager = new ScreenControlManager(guiRenderer);
            }

            //initialize D3DImage output
            if (d3dImageIsSupported && allowUsingD3DImage)
            {
                // create a D3DImage to host the scene and monitor it for changes in front buffer availability
                if (d3dImage == null)
                {
                    d3dImage = new D3DImage();
                    d3dImage.IsFrontBufferAvailableChanged += D3DImage_IsFrontBufferAvailableChanged;
                    CompositionTarget.Rendering            += D3DImage_OnRendering;
                }

                // set output to background image
                Background = new ImageBrush(d3dImage);

                // set the back buffer using the new scene pointer
                HardwarePixelBuffer            buffer = texture.GetBuffer(0, 0);
                GetD3D9HardwarePixelBufferData data   = new GetD3D9HardwarePixelBufferData();
                data.hardwareBuffer = buffer._GetRealObject();
                data.outPointer     = IntPtr.Zero;
                unsafe
                {
                    GetD3D9HardwarePixelBufferData *pData = &data;
                    if (!RenderSystem.Instance.CallCustomMethod("Get D3D9HardwarePixelBuffer getSurface", (IntPtr)pData))
                    {
                        Log.Fatal("Get D3D9HardwarePixelBuffer getSurface failed.");
                    }
                }
                d3dImage.Lock();
                d3dImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, data.outPointer);
                d3dImage.Unlock();
            }

            return(true);
        }
示例#5
0
        protected override bool Setup()
        {
            ReadConfigs();
            CreateTasks();

            mMapExporter = new GorgonMapExporter()
            {
                atlasHeight = 4096, atlasWidth = 4096
            };
            mImageExporter = new PngImageExporter();

            var setup = base.Setup();
            var ptr   = TextureManager.Singleton.CreateManual("RttTex",
                                                              ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                                                              TextureType.TEX_TYPE_2D,
                                                              148,
                                                              148,
                                                              0,
                                                              PixelFormat.PF_R8G8B8A8,
                                                              (int)TextureUsage.TU_RENDERTARGET
                                                              );

            mRTT  = ptr.GetBuffer().GetRenderTarget();
            mRTVP = mRTT.AddViewport(mCamera);
            mRTVP.BackgroundColour = new ColourValue(0, 0, 0, 0);
            mRTVP.SetClearEveryFrame(true);
            mRTVP.OverlaysEnabled = false;

            //Calculate diagonal distance value
            //mPythDistance = (mDistance / Mogre.Math.Sqrt(2));

            var altitude = new Degree(mCameraAngle);
            var angles   = new float[] {
                180f,  // South
                135f,  // Southeast
                90f,   // East
                45f,   // Northeast
                0f,    // North
                -45f,  // Northwest
                -90f,  // West
                -135f, // Southwest
            };

            mCameraDirections = new List <string> {
                "s",
                "se",
                "e",
                "ne",
                "n",
                "nw",
                "w",
                "sw"
            };
            mCameraPositions = new List <Vector3>();
            for (var i = 0; i < 8; i++)
            {
                float   azimuth = angles[i];
                string  dirname = mCameraDirections[i];
                Vector3 pos     = getPosOnSphere(mDistance, new Degree(-azimuth), -altitude);
                mCameraPositions.Add(pos);
                Console.WriteLine("Determined camera pos: {0,2} is {1,5:F2},{2,5:F2},{3,5:F2}", dirname, pos.x, pos.y, pos.z);
            }

            /*
             * mCameraPositions = new List<Vector3> {
             *  new Vector3(0, mDistance, mDistance),                   // Front / South
             *  new Vector3(-mPythDistance, mDistance, mPythDistance),  // Front-right / southwest
             *  new Vector3(-mDistance, mDistance, 0),                  // Right / west
             *  new Vector3(-mPythDistance, mDistance, -mPythDistance), // Back-right / northwest
             *  new Vector3(0, mDistance, -mDistance),                  // Back / north
             *  new Vector3(mPythDistance, mDistance, -mPythDistance),  // Back-left / northeast
             *  new Vector3(mDistance, mDistance, 0),                   // Left / east
             *  new Vector3(mPythDistance, mDistance, mPythDistance),   // Front-left / southeast
             * };
             */



            //CompositorManager.Singleton.AddCompositor(vp, "EdgeDetectCompositor", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "EdgeDetectCompositor", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "EdgeDetectCompositor", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "EdgeDetectCompositor", true);

            /*CompositorManager.Singleton.AddCompositor(vp, "Pixelate", 0);
             * CompositorManager.Singleton.AddCompositor(mRTVP, "Pixelate", 0);
             * CompositorManager.Singleton.SetCompositorEnabled(vp, "Pixelate", true);
             * CompositorManager.Singleton.SetCompositorEnabled(mRTVP, "Pixelate", true);*/

            //CompositorManager.Singleton.AddCompositor(vp, "Normal", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "Normal", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "Normal", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "Normal", true);

            //CompositorManager.Singleton.AddCompositor(vp, "SMAA", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "SMAA", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "SMAA", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "SMAA", true);

            //CompositorManager.Singleton.AddCompositor(vp, "FXAA", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "FXAA", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "FXAA", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "FXAA", true);

            //Set up task scheduler
            imageTrimScheduler   = new LimitedConcurrencyLevelTaskScheduler(3);
            imageTrimTaskFactory = new TaskFactory(imageTrimScheduler);
            imagePackScheduler   = new LimitedConcurrencyLevelTaskScheduler(1);
            imagePackTaskFactory = new TaskFactory(imagePackScheduler);
            return(setup);
        }
        bool CreateRenderTarget()
        {
            DestroyRenderTarget();

            if( RendererWorld.Instance == null )
                return false;

            Vec2I textureSize = GetDemandTextureSize();
            if( textureSize.X < 1 || textureSize.Y < 1 )
                return false;

            string textureName = TextureManager.Instance.GetUniqueName( "WPFRenderTexture" );

            int hardwareFSAA = 0;
            if( !RendererWorld.InitializationOptions.AllowSceneMRTRendering )
            {
                if( !int.TryParse( RendererWorld.InitializationOptions.FullSceneAntialiasing, out hardwareFSAA ) )
                    hardwareFSAA = 0;
            }

            texture = TextureManager.Instance.Create( textureName, Texture.Type.Type2D, textureSize,
                1, 0, Engine.Renderer.PixelFormat.R8G8B8, Texture.Usage.RenderTarget, false, hardwareFSAA );

            if( texture == null )
                return false;

            currentTextureSize = textureSize;

            renderTexture = texture.GetBuffer().GetRenderTarget();
            renderTexture.AutoUpdate = false;
            renderTexture.AllowAdditionalMRTs = true;

            camera = SceneManager.Instance.CreateCamera(
                SceneManager.Instance.GetUniqueCameraName( "UserControl" ) );
            camera.Purpose = Camera.Purposes.MainCamera;

            //update camera settings
            camera.NearClipDistance = cameraNearFarClipDistance.Minimum;
            camera.FarClipDistance = cameraNearFarClipDistance.Maximum;
            camera.AspectRatio = (float)texture.Size.X / (float)texture.Size.Y;
            camera.FixedUp = cameraFixedUp;
            camera.Position = cameraPosition;
            camera.Direction = cameraDirection;
            camera.Fov = cameraFov;
            camera.ProjectionType = cameraProjectionType;
            camera.OrthoWindowHeight = cameraOrthoWindowHeight;

            viewport = renderTexture.AddViewport( camera );

            //Initialize HDR compositor for HDR render technique
            if( EngineApp.RenderTechnique == "HDR" )
            {
                viewport.AddCompositor( "HDR", 0 );
                viewport.SetCompositorEnabled( "HDR", true );
            }

            //Initialize Fast Approximate Antialiasing (FXAA)
            {
                bool useMRT = RendererWorld.InitializationOptions.AllowSceneMRTRendering;
                string fsaa = RendererWorld.InitializationOptions.FullSceneAntialiasing;
                if( ( useMRT && ( fsaa == "" || fsaa == "RecommendedSetting" ) && IsActivateFXAAByDefault() ) ||
                    fsaa == "FXAA" )
                {
                    if( RenderSystem.Instance.HasShaderModel3() )
                        InitializeFXAACompositor();
                }
            }

            //add listener
            renderTargetListener = new ViewRenderTargetListener( this );
            renderTexture.AddListener( renderTargetListener );

            if( guiRenderer == null )
                guiRenderer = new GuiRenderer( viewport );
            else
                guiRenderer.ChangeViewport( viewport );

            if( controlManager == null )
                controlManager = new ScreenControlManager( guiRenderer );

            //initialize D3DImage output
            if( d3dImageIsSupported && allowUsingD3DImage )
            {
                // create a D3DImage to host the scene and monitor it for changes in front buffer availability
                if( d3dImage == null )
                {
                    d3dImage = new D3DImage();
                    d3dImage.IsFrontBufferAvailableChanged += D3DImage_IsFrontBufferAvailableChanged;
                    CompositionTarget.Rendering += D3DImage_OnRendering;
                }

                // set output to background image
                Background = new ImageBrush( d3dImage );

                // set the back buffer using the new scene pointer
                HardwarePixelBuffer buffer = texture.GetBuffer( 0, 0 );
                GetD3D9HardwarePixelBufferData data = new GetD3D9HardwarePixelBufferData();
                data.hardwareBuffer = buffer._GetRealObject();
                data.outPointer = IntPtr.Zero;
                unsafe
                {
                    GetD3D9HardwarePixelBufferData* pData = &data;
                    if( !RenderSystem.Instance.CallCustomMethod( "Get D3D9HardwarePixelBuffer getSurface", (IntPtr)pData ) )
                        Log.Fatal( "Get D3D9HardwarePixelBuffer getSurface failed." );
                }
                d3dImage.Lock();
                d3dImage.SetBackBuffer( D3DResourceType.IDirect3DSurface9, data.outPointer );
                d3dImage.Unlock();
            }

            return true;
        }
示例#7
0
        protected override bool Setup()
        {
            ReadConfigs();
            CreateTasks();

            mMapExporter = new GorgonMapExporter() { atlasHeight = 4096, atlasWidth = 4096 };
            mImageExporter = new PngImageExporter();

            var setup = base.Setup();
            var ptr = TextureManager.Singleton.CreateManual("RttTex",
                                                            ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                                                            TextureType.TEX_TYPE_2D,
                                                            148,
                                                            148,
                                                            0,
                                                            PixelFormat.PF_R8G8B8A8,
                                                            (int)TextureUsage.TU_RENDERTARGET
                );
            mRTT = ptr.GetBuffer().GetRenderTarget();
            mRTVP = mRTT.AddViewport(mCamera);
            mRTVP.BackgroundColour = new ColourValue(0, 0, 0, 0);
            mRTVP.SetClearEveryFrame(true);
            mRTVP.OverlaysEnabled = false;

            //Calculate diagonal distance value
            //mPythDistance = (mDistance / Mogre.Math.Sqrt(2));

            var altitude = new Degree(mCameraAngle);
            var angles = new float[]{
                180f, // South
                135f, // Southeast
                 90f, // East
                 45f, // Northeast
                  0f, // North
                -45f, // Northwest
                -90f, // West
               -135f, // Southwest
            };
            mCameraDirections = new List<string> {
                "s",
                "se",
                "e",
                "ne",
                "n",
                "nw",
                "w",
                "sw"
            };
            mCameraPositions = new List<Vector3>();
            for (var i = 0; i < 8; i++)
            {
                float azimuth = angles[i];
                string dirname = mCameraDirections[i];
                Vector3 pos = getPosOnSphere(mDistance, new Degree(-azimuth), -altitude);
                mCameraPositions.Add(pos);
                Console.WriteLine("Determined camera pos: {0,2} is {1,5:F2},{2,5:F2},{3,5:F2}", dirname, pos.x, pos.y, pos.z);
            }
            /*
            mCameraPositions = new List<Vector3> {
                new Vector3(0, mDistance, mDistance),                   // Front / South
                new Vector3(-mPythDistance, mDistance, mPythDistance),  // Front-right / southwest
                new Vector3(-mDistance, mDistance, 0),                  // Right / west
                new Vector3(-mPythDistance, mDistance, -mPythDistance), // Back-right / northwest
                new Vector3(0, mDistance, -mDistance),                  // Back / north
                new Vector3(mPythDistance, mDistance, -mPythDistance),  // Back-left / northeast
                new Vector3(mDistance, mDistance, 0),                   // Left / east
                new Vector3(mPythDistance, mDistance, mPythDistance),   // Front-left / southeast
            };
            */

            //CompositorManager.Singleton.AddCompositor(vp, "EdgeDetectCompositor", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "EdgeDetectCompositor", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "EdgeDetectCompositor", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "EdgeDetectCompositor", true);

            /*CompositorManager.Singleton.AddCompositor(vp, "Pixelate", 0);
            CompositorManager.Singleton.AddCompositor(mRTVP, "Pixelate", 0);
            CompositorManager.Singleton.SetCompositorEnabled(vp, "Pixelate", true);
            CompositorManager.Singleton.SetCompositorEnabled(mRTVP, "Pixelate", true);*/

            //CompositorManager.Singleton.AddCompositor(vp, "Normal", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "Normal", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "Normal", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "Normal", true);

            //CompositorManager.Singleton.AddCompositor(vp, "SMAA", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "SMAA", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "SMAA", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "SMAA", true);

            //CompositorManager.Singleton.AddCompositor(vp, "FXAA", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "FXAA", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "FXAA", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "FXAA", true);

            //Set up task scheduler
            imageTrimScheduler = new LimitedConcurrencyLevelTaskScheduler(3);
            imageTrimTaskFactory = new TaskFactory(imageTrimScheduler);
            imagePackScheduler = new LimitedConcurrencyLevelTaskScheduler(1);
            imagePackTaskFactory = new TaskFactory(imagePackScheduler);
            return setup;
        }
示例#8
0
        void CreateReflectionTexture()
        {
            DestroyReflectionTexture();

            Vec2i textureSize = GetRequiredReflectionTextureSize();

            //create render texture

            string textureName = TextureManager.Instance.GetUniqueName( "WaterPlaneReflection" );

            bool hdr = RendererWorld.Instance.DefaultViewport.GetCompositorInstance( "HDR" ) != null;

            reflectionTexture = TextureManager.Instance.Create( textureName, Texture.Type.Type2D,
                textureSize, 1, 0, hdr ? PixelFormat.Float16RGB : PixelFormat.R8G8B8,
                Texture.Usage.RenderTarget );

            reflectionRenderTexture = reflectionTexture.GetBuffer().GetRenderTarget();

            //create camera
            reflectionCamera = SceneManager.Instance.CreateCamera();
            reflectionCamera.AllowFrustumTestMode = true;

            //add viewport
            reflectionViewport = reflectionRenderTexture.AddViewport( reflectionCamera );
            reflectionViewport.ShadowsEnabled = false;
            reflectionViewport.MaterialScheme = MaterialSchemes.Low.ToString();

            //add listener
            renderTargetListener = new ReflectionRenderTargetListener( this );
            reflectionRenderTexture.AddListener( renderTargetListener );

            reflectionRenderTexture.AutoUpdate = Visible;
        }
        protected override void CreateScene()
        {
            mLog = LogManager.Singleton.createLog("RSQTest.log", false, true);
            mLog.LogMessage(string.Format("RSQTest log {0}", System.DateTime.Now));

            create4LineDebugOverLay();
            Show4LineDebugOverLay();

            //setup RenderTargetListenerDirector
            mRTListener = new RenderTargetListenerDirector();
            mRTListener.SubscribeEvents();
            mRTListener.evtPreRenderTargetUpdate  += new RenderTargetListenerDirector.RTLD_Delegate_RenderTargetUpdate(event_PreRenderTargetUpdate);
            mRTListener.evtPostRenderTargetUpdate += new RenderTargetListenerDirector.RTLD_Delegate_RenderTargetUpdate(event_PostRenderTargetUpdate);

            mSceneManager.SetAmbientLight(Converter.GetColor(0.2f, 0.2f, 0.2f));

            mSceneManager.SetSkyBox(true, "Examples/MorningSkyBox");

            // Create a light
            Light l = mSceneManager.CreateLight("MainLight");

            l.SetLightType(OgreDotNet.Light.LightTypes.Directional);
            Math3D.Vector3 dir = new Vector3(0.5f, -1.0f, 0.0f);
            dir.Normalize();
            l.SetDirection(dir);
            l.SetDiffuseColour(1.0f, 1.0f, 0.8f);
            l.SetSpecularColour(1.0f, 1.0f, 1.0f);

            // Create a prefab plane
            mPlane        = new MovablePlane("ReflectPlane");
            mPlane.D      = 0;
            mPlane.Normal = OgreVector3.FromVector3(Math3D.Vector3.UnitY);
            MeshManager.GetSingleton().CreatePlane("ReflectionPlane", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                                                   mPlane, 2000, 2000, 1, 1, true, 1, 1, 1, Vector3.UnitZ);
            mPlaneEnt = mSceneManager.CreateEntity("Plane", "ReflectionPlane");

            // Create an entity from a model (will be loaded automatically)
            Entity knotEnt = mSceneManager.CreateEntity("Knot", "knot.mesh");

            // Create an entity from a model (will be loaded automatically)
            Entity ogreHead = mSceneManager.CreateEntity("Head", "ogrehead.mesh");

            knotEnt.SetMaterialName("Examples/TextureEffect2");

            // Attach the rtt entity to the root of the scene
            SceneNode rootNode = mSceneManager.GetRootSceneNode();

            mPlaneNode = rootNode.CreateChildSceneNode();

            // Attach both the plane entity, and the plane definition
            mPlaneNode.AttachObject(mPlaneEnt);

            //multi Inheritence problem, use the static Get*From function to convert
            MovableObject mo = MovableObject.GetMovableObjectFrom(mPlane);

            mPlaneNode.AttachObject(mo);

            mPlaneNode.Translate(0.0f, -10.0f, 0.0f);

            // Tilt it a little to make it interesting
            //mPlaneNode.Roll( new Radian( new Degree( 5.0f)) );
            mPlaneNode.Roll(5.0f);

            rootNode.CreateChildSceneNode("Head").AttachObject(ogreHead);


            RenderTexture rttTex = mRoot.GetRenderSystem().CreateRenderTexture("RttTex", 512, 512,
                                                                               TextureType.TEX_TYPE_2D, PixelFormat.PF_R8G8B8);

            {            //new scope for some reason
                mReflectCam = mSceneManager.CreateCamera("ReflectCam");
                mReflectCam.SetNearClipDistance(mCamera.GetNearClipDistance());
                mReflectCam.SetFarClipDistance(mCamera.GetFarClipDistance());
                mReflectCam.SetAspectRatio(
                    (float)mRenderWindow.GetViewport(0).ActualWidth /
                    (float)mRenderWindow.GetViewport(0).ActualHeight);

                Viewport v = rttTex.AddViewport(mReflectCam);
                v.ClearEveryFrame = true;
                v.BackgroundColor = System.Drawing.Color.Black;                 //Converter.ToColor( ColourValue.Black );

                ResourcePtr resPtr = MaterialManager.Instance.Create("RttMat",
                                                                     ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME);

                MaterialPtr mat = new MaterialPtr(ResourcePtr.getCPtr(resPtr).Handle, false);

                TextureUnitState t = mat.Get().GetTechnique(0).getPass(0).createTextureUnitState("RustedMetal.jpg");
                t = mat.Get().GetTechnique(0).getPass(0).createTextureUnitState("RttTex");
                // Blend with base texture
                t.setColourOperationEx(LayerBlendOperationEx.LBX_BLEND_MANUAL, LayerBlendSource.LBS_TEXTURE,
                                       LayerBlendSource.LBS_CURRENT, Color.White,
                                       Color.White, 0.25f);
                t.SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_CLAMP);
                t.setProjectiveTexturing(true, mReflectCam);
                rttTex.AddListener(mRTListener);

                // set up linked reflection
                mReflectCam.EnableReflection(mPlane);
                // Also clip
                mReflectCam.EnableCustomNearClipPlane(mPlane);
            }

            // Give the plane a texture
            mPlaneEnt.SetMaterialName("RttMat");


            // Add a whole bunch of extra transparent entities
            Entity cloneEnt;

            for (int n = 0; n < 10; ++n)
            {
                // Create a new node under the root
                SceneNode node = mSceneManager.CreateSceneNode();
                // Random translate
                Vector3 nodePos;
                nodePos.x = OgreMath.SymmetricRandom() * 750.0f;
                nodePos.y = OgreMath.SymmetricRandom() * 100.0f + 25.0f;
                nodePos.z = OgreMath.SymmetricRandom() * 750.0f;
                node.SetPosition(nodePos);
                rootNode.AddChild(node);
                // Clone knot
                string cloneName = string.Format("Knot{0}", n);
                cloneEnt = knotEnt.Clone(cloneName);
                // Attach to new node
                node.AttachObject(cloneEnt);
            }


            mCamera.SetPosition(new Vector3(-50.0f, 100.0f, 500.0f));
            mCamera.LookAt = new Vector3(0, 0, 0);
        }
示例#10
0
        protected override void CreateScene()
        {
            // Check gpu caps
            if (!GpuProgramManager.Instance.IsSyntaxSupported("ps_2_0") &&
                !GpuProgramManager.Instance.IsSyntaxSupported("ps_1_4") &&
                !GpuProgramManager.Instance.IsSyntaxSupported("arbfp1"))
            {
                throw new Exception("Your hardware does not support advanced pixel shaders, so you cannot run this demo.  Time to go to Best Buy ;)");
            }

            Animation.DefaultInterpolationMode = InterpolationMode.Linear;

            theCam          = camera;
            theCam.Position = new Vector3(-100, 20, 700);

            // set the ambient scene light
            scene.AmbientLight = new ColorEx(0.5f, 0.5f, 0.5f);

            Light light = scene.CreateLight("MainLight");

            light.Type      = LightType.Directional;
            light.Direction = -Vector3.UnitY;

            Material mat = MaterialManager.Instance.GetByName("Examples/FresnelReflectionRefraction");

            // Refraction texture
            RenderTexture rttTex = Root.Instance.RenderSystem.CreateRenderTexture("Refraction", 512, 512);

            {
                Viewport vp = rttTex.AddViewport(camera, 0, 0, 1.0f, 1.0f, 0);
                vp.OverlaysEnabled = false;
                mat.GetTechnique(0).GetPass(0).GetTextureUnitState(2).SetTextureName("Refraction");
                rttTex.BeforeUpdate += new RenderTargetUpdateEventHandler(Refraction_BeforeUpdate);
                rttTex.AfterUpdate  += new RenderTargetUpdateEventHandler(Refraction_AfterUpdate);
            }

            // Reflection texture
            rttTex = Root.Instance.RenderSystem.CreateRenderTexture("Reflection", 512, 512);
            {
                Viewport vp = rttTex.AddViewport(camera, 0, 0, 1.0f, 1.0f, 0);
                vp.OverlaysEnabled = false;
                mat.GetTechnique(0).GetPass(0).GetTextureUnitState(1).SetTextureName("Reflection");
                rttTex.BeforeUpdate += new RenderTargetUpdateEventHandler(Reflection_BeforeUpdate);
                rttTex.AfterUpdate  += new RenderTargetUpdateEventHandler(Reflection_AfterUpdate);
            }

            reflectionPlane.Normal = Vector3.UnitY;
            reflectionPlane.D      = 0;
            MeshManager.Instance.CreatePlane(
                "ReflectionPlane", reflectionPlane, 1500, 1500, 10, 10, true, 1, 5, 5, Vector3.UnitZ);

            planeEnt = scene.CreateEntity("Plane", "ReflectionPlane");
            planeEnt.MaterialName = "Examples/FresnelReflectionRefraction";
            scene.RootSceneNode.CreateChildSceneNode().AttachObject(planeEnt);

            scene.SetSkyBox(true, "Examples/CloudyNoonSkyBox", 2000);

            SceneNode myRootNode = scene.RootSceneNode.CreateChildSceneNode();

            Entity ent;

            // Above water entities - NB all meshes are static
            ent = scene.CreateEntity("head1", "head1.mesh");
            myRootNode.AttachObject(ent);
            aboveWaterEnts.Add(ent);
            ent = scene.CreateEntity("Pillar1", "Pillar1.mesh");
            myRootNode.AttachObject(ent);
            aboveWaterEnts.Add(ent);
            ent = scene.CreateEntity("Pillar2", "Pillar2.mesh");
            myRootNode.AttachObject(ent);
            aboveWaterEnts.Add(ent);
            ent = scene.CreateEntity("Pillar3", "Pillar3.mesh");
            myRootNode.AttachObject(ent);
            aboveWaterEnts.Add(ent);
            ent = scene.CreateEntity("Pillar4", "Pillar4.mesh");
            myRootNode.AttachObject(ent);
            aboveWaterEnts.Add(ent);
            ent = scene.CreateEntity("UpperSurround", "UpperSurround.mesh");
            myRootNode.AttachObject(ent);
            aboveWaterEnts.Add(ent);

            // Now the below water ents
            ent = scene.CreateEntity("LowerSurround", "LowerSurround.mesh");
            myRootNode.AttachObject(ent);
            belowWaterEnts.Add(ent);
            ent = scene.CreateEntity("PoolFloor", "PoolFloor.mesh");
            myRootNode.AttachObject(ent);
            belowWaterEnts.Add(ent);

            for (int fishNo = 0; fishNo < NUM_FISH; fishNo++)
            {
                ent = scene.CreateEntity(string.Format("fish{0}", fishNo), "fish.mesh");
                fishNodes[fishNo]                = myRootNode.CreateChildSceneNode();
                fishAnimations[fishNo]           = ent.GetAnimationState("swim");
                fishAnimations[fishNo].IsEnabled = true;
                fishNodes[fishNo].AttachObject(ent);
                belowWaterEnts.Add(ent);

                // Generate a random selection of points for the fish to swim to
                fishSplines[fishNo].AutoCalculate = false;

                Vector3 lastPos = Vector3.Zero;

                for (int waypoint = 0; waypoint < NUM_FISH_WAYPOINTS; waypoint++)
                {
                    Vector3 pos = new Vector3(
                        MathUtil.SymmetricRandom() * 700, -10, MathUtil.SymmetricRandom() * 700);

                    if (waypoint > 0)
                    {
                        // check this waypoint isn't too far, we don't want turbo-fish ;)
                        // since the waypoints are achieved every 5 seconds, half the length
                        // of the pond is ok
                        while ((lastPos - pos).Length > 750)
                        {
                            pos = new Vector3(
                                MathUtil.SymmetricRandom() * 700, -10, MathUtil.SymmetricRandom() * 700);
                        }
                    }

                    fishSplines[fishNo].AddPoint(pos);
                    lastPos = pos;
                }

                // close the spline
                fishSplines[fishNo].AddPoint(fishSplines[fishNo].GetPoint(0));
                // recalc
                fishSplines[fishNo].RecalculateTangents();
            }
        }
示例#11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="force"></param>
        protected void RenderTextures(bool force)
        {
            Texture       renderTexture  = null;
            RenderTexture renderTarget   = null;
            Camera        renderCamera   = null;
            Viewport      renderViewport = null;
            //Set up RTT texture
            int textureSize = ImpostorPage.ImpostorResolution;

            if (renderTexture == null)
            {
                renderTexture = (Texture)TextureManager.Singleton.CreateManual(GetUniqueID("ImpostorTexture"), "Impostors",
                                                                               TextureType.TwoD, textureSize * ImpostorYawAngles, textureSize * ImpostorPitchAngles, 0,
                                                                               MogreLibMedia.PixelFormat.A8B8G8R8, TextureUsage.RenderTarget, mLoader);
            }

            renderTexture.MipmapCount = 0x7FFFFFFF;

            //Set up render target
            renderTarget = renderTexture.GetBuffer().GetRenderTarget();
            renderTarget.IsAutoUpdated = false;

            //Set up camera
            renderCamera                = mSceneMgr.CreateCamera(GetUniqueID("ImpostorCam"));
            renderCamera.LodBias        = 1000.0f;
            renderViewport              = renderTarget.AddViewport(renderCamera);
            renderViewport.ShowOverlays = false;
#warning why is set == protected?
            // renderViewport.ClearEveryFrame = true;
            renderViewport.ShowShadows     = false;
            renderViewport.BackgroundColor = ImpostorPage.ImpostorBackgroundColor;

            //Set up scene node
            SceneNode node = mSceneMgr.GetSceneNode("ImpostorPage.RenderNode");

            SceneNode oldSceneNode = mEntity.ParentSceneNode;
            if (oldSceneNode != null)
            {
                oldSceneNode.DetachObject(mEntity);
            }

            node.AttachObject(mEntity);
            node.Position = -mEntityCenter;

            //Set up camera FOV
            float objectDist = mEntityRadius * 100;
            float nearDist   = objectDist - (mEntityRadius + 1);
            float farDist    = objectDist + (mEntityRadius + 1);

            renderCamera.AspectRatio = 1.0f;
            renderCamera.FieldOfView = (float)MogreLibMath.Utility.ATan(mEntityDiameter / objectDist);
            renderCamera.Near        = nearDist;
            renderCamera.Far         = farDist;

            //Disable mipmapping (without this, masked textures look bad)
            MaterialManager mm           = MaterialManager.Instance;
            FilterOptions   oldMinFilter = mm.GetDefaultTextureFiltering(FilterType.Min);
            FilterOptions   oldMagFilter = mm.GetDefaultTextureFiltering(FilterType.Mag);
            FilterOptions   oldMipFilter = mm.GetDefaultTextureFiltering(FilterType.Mip);
            mm.SetDefaultTextureFiltering(FilterOptions.Point, FilterOptions.Linear, FilterOptions.None);

            //Disable fog
            FogMode oldFogMode    = mSceneMgr.FogMode;
            ColorEx oldFogColor   = mSceneMgr.FogColor;
            float   oldFogDensity = mSceneMgr.FogDensity;
            float   oldFogStart   = mSceneMgr.FogStart;
            float   oldFogEnd     = mSceneMgr.FogEnd;
            mSceneMgr.FogMode = FogMode.None;

            // Get current status of the queue mode
            SpecialCaseRenderQueueMode oldSpecialCaseRenderQueueMode = mSceneMgr.SpecialCaseRenderQueueList.RenderQueueMode;

            //Only render the entity
            mSceneMgr.SpecialCaseRenderQueueList.RenderQueueMode = SpecialCaseRenderQueueMode.Include;
            mSceneMgr.SpecialCaseRenderQueueList.AddRenderQueue(RenderQueueGroupID.Six + 1);

            RenderQueueGroupID oldRenderGroup = mEntity.RenderQueueGroup;
            mEntity.RenderQueueGroup = RenderQueueGroupID.Six + 1;
            bool oldVisible = mEntity.IsVisible;
            mEntity.IsVisible = true;
#warning implement float oldMaxDistance = entity->getRenderingDistance();
#warning implement entity->setRenderingDistance(0);

            bool needsRegen = true;
            //Calculate the filename used to uniquely identity this render
            string strKey = mEntityKey;
            char[] key    = new char[32];
            int    i      = 0;
            foreach (char c in mEntityKey)
            {
                key[i] ^= c;
                i       = (i + 1) % key.Length;
            }
            for (i = 0; i < key.Length; i++)
            {
                key[i] = (char)((key[i] % 26) + 'A');
            }

            ResourceGroupManager.Instance.AddResourceLocation(".", "Folder", "BinFolder");
            string keyStr = string.Empty;
            foreach (char c in key)
            {
                keyStr += c.ToString();
            }
            string fileName = "Impostor." + keyStr + "." + textureSize + ".png";
            //Attempt to load the pre-render file if allowed
            needsRegen = force;
            if (!needsRegen)
            {
                try
                {
                    mTexture = (Texture)TextureManager.Singleton.Load(fileName, "BinFolder", TextureType.TwoD, 0x7FFFFFFF);
                }
                catch
                {
                    needsRegen = true;
                }
            }

            if (needsRegen)
            {
                //If this has not been pre-rendered, do so now
                float xDivFactor = 1.0f / ImpostorYawAngles;
                float yDivFactor = 1.0f / ImpostorPitchAngles;
                for (int o = 0; o < ImpostorPitchAngles; o++)                                //4 pitch angle renders
                {
                    Radian pitch = (Radian) new Degree((Real)((90.0f * o) * yDivFactor));    //0, 22.5, 45, 67.5
                    for (i = 0; i < ImpostorYawAngles; i++)                                  //8 yaw angle renders
                    {
                        Radian yaw = (Radian) new Degree((Real)((360.0f * i) * xDivFactor)); //0, 45, 90, 135, 180, 225, 270, 315

                        //Position camera
                        renderCamera.Position    = new Vector3(0, 0, 0);
                        renderCamera.Orientation = Quaternion.Identity;
                        renderCamera.Pitch((float)-pitch);
                        renderCamera.Yaw((float)yaw);
                        renderCamera.MoveRelative(new Vector3(0, 0, objectDist));

                        //Render the impostor
                        renderViewport.SetDimensions((float)(i * xDivFactor), (float)(o * yDivFactor), xDivFactor, yDivFactor);
                        renderTarget.Update();
                    }
                }

                //Save RTT to file
                renderTarget.WriteContentsToFile(fileName);

                //Load the render into the appropriate texture view
                mTexture = (Texture)TextureManager.Singleton.Load(fileName, "BinFolder", TextureType.TwoD, 0x7FFFFFFF);
            }

            mEntity.IsVisible        = oldVisible;
            mEntity.RenderQueueGroup = oldRenderGroup;
#warning entity->setRenderingDistance(oldMaxDistance);
            mSceneMgr.SpecialCaseRenderQueueList.RemoveRenderQueue(RenderQueueGroupID.Six + 1);
            // Restore original state
            mSceneMgr.SpecialCaseRenderQueueList.RenderQueueMode = oldSpecialCaseRenderQueueMode;

            //Re-enable mipmapping
            mm.SetDefaultTextureFiltering(oldMinFilter, oldMagFilter, oldMipFilter);

            //Re-enable fog
            mSceneMgr.SetFog(oldFogMode, oldFogColor, oldFogDensity, oldFogStart, oldFogEnd);

            //Delete camera
            renderTarget.RemoveViewport(0);
            renderCamera.SceneManager.DestroyCamera(renderCamera);

            //Delete scene node
            node.DetachAllObjects();
            if (oldSceneNode != null)
            {
                oldSceneNode.AttachObject(mEntity);
            }


            //Delete RTT texture
            Debug.Assert(renderTexture != null);
            string texName2 = renderTexture.Name;

            renderTexture = null;
            if (TextureManager.Singleton != null)
            {
                TextureManager.Singleton.Remove(texName2);
            }
        }
            ///////////////

            private bool CreateRenderTexture()
            {
                Vec2I size = new Vec2I(512, 256);

                string textureName = TextureManager.Instance.GetUniqueName("RenderToTextureExample");
                texture = TextureManager.Instance.Create(textureName, Texture.Type.Type2D, size, 1, 0,
                    PixelFormat.R8G8B8, Texture.Usage.RenderTarget);
                if (texture == null)
                    return false;

                renderTexture = texture.GetBuffer().GetRenderTarget();
                //you can update render texture manually by means renderTexture.Update() method. For this task set AutoUpdate = false;
                renderTexture.AutoUpdate = true;

                //create camera
                string cameraName = SceneManager.Instance.GetUniqueCameraName("RenderToTextureExample");
                camera = SceneManager.Instance.CreateCamera(cameraName);
                camera.Purpose = Camera.Purposes.Special;
                camera.AllowMapCompositorManager = false;

                //add viewport
                viewport = renderTexture.AddViewport(camera);
                viewport.BackgroundColor = new ColorValue(0, 0, 0, 1);
                viewport.ShadowsEnabled = false;
                viewport.MaterialScheme = "";

                //add listener
                renderTargetListener = new SceneRenderTargetListener(this);
                renderTexture.AddListener(renderTargetListener);

                return true;
            }
示例#13
0
        protected override void CreateScene()
        {
            // set ambient light
            scene.AmbientLight = new ColorEx(0.2f, 0.2f, 0.2f);

            scene.SetSkyBox(true, "Skybox/Morning", 5000);

            // create a default point light
            Light light = scene.CreateLight("MainLight");

            light.Type = LightType.Directional;
            Vector3 dir = new Vector3(0.5f, -1, 0);

            dir.Normalize();
            light.Direction = dir;
            light.Diffuse   = new ColorEx(1.0f, 1.0f, 0.8f);
            light.Specular  = ColorEx.White;

            // create a plane
            plane        = new MovablePlane("ReflectPlane");
            plane.D      = 0;
            plane.Normal = Vector3.UnitY;

            // create another plane to create the mesh.  Ogre's MovablePlane uses multiple inheritance, bah!
            Plane tmpPlane = new Plane();

            tmpPlane.D      = 0;
            tmpPlane.Normal = Vector3.UnitY;

            MeshManager.Instance.CreatePlane("ReflectionPlane", tmpPlane, 2000, 2000, 1, 1, true, 1, 1, 1, Vector3.UnitZ);
            planeEntity = scene.CreateEntity("Plane", "ReflectionPlane");

            // create an entity from a model
            Entity knot = scene.CreateEntity("Knot", "knot.mesh");

            knot.MaterialName = "TextureFX/Knot";

            // create an entity from a model
            Entity head = scene.CreateEntity("Head", "ogrehead.mesh");

            // attach the render to texture entity to the root of the scene
            SceneNode rootNode = scene.RootSceneNode;

            planeNode = rootNode.CreateChildSceneNode();

            planeNode.AttachObject(planeEntity);
            planeNode.AttachObject(plane);
            planeNode.Translate(new Vector3(0, -10, 0));

            // tilt it a little to make it interesting
            planeNode.Roll(5);

            rootNode.CreateChildSceneNode("Head").AttachObject(head);

            // create a render texture
            RenderTexture rttTex = Root.Instance.RenderSystem.CreateRenderTexture("RttTex", 512, 512);

            reflectCam             = scene.CreateCamera("ReflectCam");
            reflectCam.Near        = camera.Near;
            reflectCam.Far         = camera.Far;
            reflectCam.AspectRatio = (float)window.GetViewport(0).ActualWidth / (float)window.GetViewport(0).ActualHeight;

            Viewport viewport = rttTex.AddViewport(reflectCam);

            viewport.ClearEveryFrame = true;
            viewport.OverlaysEnabled = false;
            viewport.BackgroundColor = ColorEx.Black;

            Material         mat = scene.CreateMaterial("RttMat");
            TextureUnitState t   = mat.GetTechnique(0).GetPass(0).CreateTextureUnitState("RustedMetal.jpg");

            t = mat.GetTechnique(0).GetPass(0).CreateTextureUnitState("RttTex");

            // blend with base texture
            t.SetColorOperationEx(LayerBlendOperationEx.BlendManual, LayerBlendSource.Texture, LayerBlendSource.Current,
                                  ColorEx.White, ColorEx.White, 0.25f);

            t.SetProjectiveTexturing(true, reflectCam);

            // register events for viewport before/after update
            rttTex.AfterUpdate  += new RenderTargetUpdateEventHandler(rttTex_AfterUpdate);
            rttTex.BeforeUpdate += new RenderTargetUpdateEventHandler(rttTex_BeforeUpdate);

            // set up linked reflection
            reflectCam.EnableReflection(plane);

            // also clip
            reflectCam.EnableCustomNearClipPlane(plane);

            planeEntity.MaterialName = "RttMat";

            Entity clone = null;

            for (int i = 0; i < 10; i++)
            {
                // create a new node under the root
                SceneNode node = scene.CreateSceneNode();

                // calculate a random position
                Vector3 nodePosition = new Vector3();
                nodePosition.x = MathUtil.SymmetricRandom() * 750.0f;
                nodePosition.y = MathUtil.SymmetricRandom() * 100.0f + 25;
                nodePosition.z = MathUtil.SymmetricRandom() * 750.0f;

                // set the new position
                node.Position = nodePosition;

                // attach this node to the root node
                rootNode.AddChild(node);

                // clone the knot
                string cloneName = string.Format("Knot{0}", i);
                clone = knot.Clone(cloneName);

                // add the cloned knot to the scene
                node.AttachObject(clone);
            }

            camera.Position = new Vector3(-50, 100, 500);
            camera.LookAt(new Vector3(0, 0, 0));
        }