示例#1
0
        private void initSky()
        {
            //aumentar render distance
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(D3DDevice.Instance.FieldOfView, D3DDevice.Instance.AspectRatio,
                                                                                        D3DDevice.Instance.ZNearPlaneDistance, D3DDevice.Instance.ZFarPlaneDistance * 1000f).ToMatrix();


            sky        = new TgcSkyBox();
            sky.Center = TGCVector3.Empty;
            sky.Size   = new TGCVector3(800000, 800000, 800000);

            //sky.Color = Color.OrangeRed;

            var texturesPath = g.game.MediaDir + "SkyBox\\";


            sky.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "lun4_up.jpg");
            sky.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "lun4_dn.jpg");
            sky.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "lun4_lf2.jpg");
            sky.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "lun4_rt2.jpg");
            sky.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "lun4_bk2.jpg");
            sky.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "lun4_ft2.jpg");

            sky.SkyEpsilon = 25f;

            sky.Init();
        }
示例#2
0
        public void InstanciarSombras()
        {
            //Cargar Shader personalizado
            effect = TGCShaders.Instance.LoadEffect(MyShaderDir + "Sombras.fx");

            // le asigno el efecto a las mallas

            // Creo el shadowmap.
            // Format.R32F
            // Format.X8R8G8B8
            g_pShadowMap = new Texture(D3DDevice.Instance.Device, SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, Usage.RenderTarget, Format.R32F, Pool.Default);

            arrow           = new TgcArrow();
            arrow.Thickness = 1f;
            arrow.HeadSize  = new TGCVector2(2f, 2f);
            arrow.BodyColor = Color.Blue;
            // tengo que crear un stencilbuffer para el shadowmap manualmente
            // para asegurarme que tenga la el mismo tamano que el shadowmap, y que no tenga
            // multisample, etc etc.
            g_pDSShadow = D3DDevice.Instance.Device.CreateDepthStencilSurface(SHADOWMAP_SIZE, SHADOWMAP_SIZE, DepthFormat.D24S8, MultiSampleType.None, 0, true);
            // por ultimo necesito una matriz de proyeccion para el shadowmap, ya
            // que voy a dibujar desde el pto de vista de la luz.
            // El angulo tiene que ser mayor a 45 para que la sombra no falle en los extremos del cono de luz
            // de hecho, un valor mayor a 90 todavia es mejor, porque hasta con 90 grados es muy dificil
            // lograr que los objetos del borde generen sombras
            var aspectRatio = D3DDevice.Instance.AspectRatio;

            g_mShadowProj = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(80), aspectRatio, 550, 3000);
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, near_plane, far_plane).ToMatrix();

            //lightLookFromModifier = camara.getPosition();
            //lightLookAtModifier = camara.getLookAt();
        }
示例#3
0
        public override void Init()
        {
            skyBox        = new TgcSkyBox();
            skyBox.Center = TGCVector3.Empty;
            skyBox.Size   = new TGCVector3(10000, 10000, 10000);

            //especifico donde estan las texturas cargadas
            var rutaTextura = MediaDir + "Superficie\\";

            //coloco cada textura en cada cara del cubo del skyBox
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, rutaTextura + "bluecloud_up.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, rutaTextura + "bluecloud_dn.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, rutaTextura + "bluecloud_lf.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, rutaTextura + "bluecloud_rt.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, rutaTextura + "bluecloud_bk.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, rutaTextura + "bluecloud_ft.jpg");


            skyBox.SkyEpsilon = 25f;

            skyBox.Init();

            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(D3DDevice.Instance.FieldOfView, D3DDevice.Instance.AspectRatio,
                                                                                        D3DDevice.Instance.ZNearPlaneDistance, D3DDevice.Instance.ZFarPlaneDistance * 2f).ToMatrix();
        }
示例#4
0
        private void SetCamera()
        {
            // Cambio el farPlane
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(D3DDevice.Instance.FieldOfView, D3DDevice.Instance.AspectRatio,
                                                                                        D3DDevice.Instance.ZNearPlaneDistance, D3DDevice.Instance.ZFarPlaneDistance * 10f).ToMatrix();

            Camera = new FPSCamera(this, Player, Player.RelativeEyePosition);
        }
        private void renderCubemap(TGCVector3 worldPos)
        {
            // ojo: es fundamental que el fov sea de 90 grados.
            // asi que re-genero la matriz de proyeccion
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f), 1f, 1f, 10000f).ToMatrix();

            // En vez de renderizar todas las caras en todos los frames (Como en el codigo comentado de arriba), renderizo una cara por cada frame
            var nFace = (CubeMapFace)(frameNumber % 6);
            var pFace = g_pCubeMap.GetCubeMapSurface(nFace, 0);

            D3DDevice.Instance.Device.SetRenderTarget(0, pFace);
            TGCVector3 Dir, VUP;

            switch (nFace)
            {
            default:
            case CubeMapFace.PositiveX:
                Dir = new TGCVector3(1, 0, 0);
                VUP = TGCVector3.Up;
                break;

            case CubeMapFace.NegativeX:
                Dir = new TGCVector3(-1, 0, 0);
                VUP = TGCVector3.Up;
                break;

            case CubeMapFace.PositiveY:
                Dir = TGCVector3.Up;
                VUP = new TGCVector3(0, 0, -1);
                break;

            case CubeMapFace.NegativeY:
                Dir = TGCVector3.Down;
                VUP = new TGCVector3(0, 0, 1);
                break;

            case CubeMapFace.PositiveZ:
                Dir = new TGCVector3(0, 0, 1);
                VUP = TGCVector3.Up;
                break;

            case CubeMapFace.NegativeZ:
                Dir = new TGCVector3(0, 0, -1);
                VUP = TGCVector3.Up;
                break;
            }

            //como queremos usar la camara rotacional pero siguendo a un objetivo comentamos el seteo del view.
            D3DDevice.Instance.Device.Transform.View = TGCMatrix.LookAtLH(worldPos, Dir, VUP);

            D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            D3DDevice.Instance.Device.BeginScene();

            //Renderizar
            renderScene(true);

            D3DDevice.Instance.Device.EndScene();
        }
        public CameraFPS(TgcD3dInput input)
        {
            Input = input;
            var d3Instance = D3DDevice.Instance;

            d3Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(d3Instance.FieldOfView, d3Instance.AspectRatio,
                                                                                d3Instance.ZNearPlaneDistance, d3Instance.ZFarPlaneDistance * 3f).ToMatrix();
            Position.Y = -1;
        }
        public void Update(float elapsedTime)
        {
            //Se cambia el valor por defecto del farplane para evitar cliping de farplane. [Copiado del ejemplo]
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(D3DDevice.Instance.FieldOfView, D3DDevice.Instance.AspectRatio,
                                                                                        D3DDevice.Instance.ZNearPlaneDistance, D3DDevice.Instance.ZFarPlaneDistance * 2f).ToMatrix();


            skyBox.Center = camara.Position;
        }
示例#8
0
        /// <summary>
        ///     Valores default del Direct3d Device
        /// </summary>
        public void DefaultValues()
        {
            //Frustum values
            Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(FieldOfView, AspectRatio, ZNearPlaneDistance,
                                                                     ZFarPlaneDistance).ToMatrix();

            //Render state
            Device.RenderState.SpecularEnable       = false;
            Device.RenderState.FillMode             = FillMode.Solid;
            Device.RenderState.CullMode             = Cull.None;
            Device.RenderState.ShadeMode            = ShadeMode.Gouraud;
            Device.RenderState.MultiSampleAntiAlias = true;
            Device.RenderState.SlopeScaleDepthBias  = -0.1f;
            Device.RenderState.DepthBias            = 0f;
            Device.RenderState.ColorVertex          = true;
            Device.RenderState.Lighting             = false;
            Device.RenderState.ZBufferEnable        = true;
            Device.RenderState.FogEnable            = false;

            //Alpha Blending
            Device.RenderState.AlphaBlendEnable = false;
            Device.RenderState.AlphaTestEnable  = false;
            Device.RenderState.ReferenceAlpha   = 50; //verificar un valor optimo.
            Device.RenderState.AlphaFunction    = Compare.Greater;
            Device.RenderState.BlendOperation   = BlendOperation.Add;
            Device.RenderState.SourceBlend      = Blend.SourceAlpha;
            Device.RenderState.DestinationBlend = Blend.InvSourceAlpha;

            //Texture Filtering
            Device.SetSamplerState(0, SamplerStageStates.MinFilter, (int)TextureFilter.Linear);
            Device.SetSamplerState(0, SamplerStageStates.MagFilter, (int)TextureFilter.Linear);
            Device.SetSamplerState(0, SamplerStageStates.MipFilter, (int)TextureFilter.Linear);

            Device.SetSamplerState(1, SamplerStageStates.MinFilter, (int)TextureFilter.Linear);
            Device.SetSamplerState(1, SamplerStageStates.MagFilter, (int)TextureFilter.Linear);
            Device.SetSamplerState(1, SamplerStageStates.MipFilter, (int)TextureFilter.Linear);

            //Clear lights
            foreach (Light light in Device.Lights)
            {
                light.Enabled = false;
            }

            //Limpiar todas las texturas
            TexturesManager.Instance.clearAll();

            //Reset Material
            Device.Material = DEFAULT_MATERIAL;

            //Limpiar IndexBuffer
            Device.Indices = null;

            EnableParticles();
        }
示例#9
0
        public override void Render()
        {
            var deviceInstance = D3DDevice.Instance;
            var device         = deviceInstance.Device;

            if (firstTime)
            {
                var oldRenderTarget = device.GetRenderTarget(0);
                var oldDepth        = device.DepthStencilSurface;

                RenderCubeMap(device);

                device.DepthStencilSurface = oldDepth;

                RenderIrradianceMap(device);

                RenderPrefilterMap(device);

                RenderBDRFLut(device);

                if (save)
                {
                    save = false;
                }

                device.Transform.View       = Camera.GetViewMatrix();
                device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), deviceInstance.AspectRatio, 1f, 2000f).ToMatrix();

                device.SetRenderTarget(0, oldRenderTarget);
                device.DepthStencilSurface = oldDepth;

                firstTime = false;
            }
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);

            device.BeginScene();

            RenderBaseScene();

            effect.SetValue("irradianceMap", irradianceMap);
            effect.SetValue("prefilterMap", prefilterMap);
            effect.SetValue("brdfLut", bdrfLUT);

            pbrMeshes.ForEach(mesh => mesh.Apply());

            pbrTexturedMeshes.ForEach(mesh => mesh.Apply());

            lightBoxes.ForEach(lightBox => lightBox.Render());

            RenderAxis();
            RenderFPS();
            device.EndScene();
            device.Present();
        }
示例#10
0
        private void RenderCubeMap(Device device)
        {
            device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f), 1f, 1f, 2000f).ToMatrix();

            RenderToCubeMapFace(CubeMapFace.PositiveX, reflectionProbePosition);
            RenderToCubeMapFace(CubeMapFace.PositiveY, reflectionProbePosition);
            RenderToCubeMapFace(CubeMapFace.PositiveZ, reflectionProbePosition);
            RenderToCubeMapFace(CubeMapFace.NegativeX, reflectionProbePosition);
            RenderToCubeMapFace(CubeMapFace.NegativeY, reflectionProbePosition);
            RenderToCubeMapFace(CubeMapFace.NegativeZ, reflectionProbePosition);
        }
示例#11
0
        public override void Update()
        {
            PreUpdate();
            escapeDelay += ElapsedTime;

            if (!InPrincipalMenu && Input.keyDown(Key.Escape) && escapeDelay > 0.5f)   // uso el delay porque no me funciona el keyUp o keyPressed
            {
                escapeDelay = 0;
                FocusInGame = !FocusInGame;
                ManageFocus();
            }

            if (FocusInGame || InPrincipalMenu)    // Si no se está en modo gameplay, desactivar el update de todo
            {
                principalMenu.Update(ElapsedTime);

                UpdateInstantiatedObjects();
                spawnManager.Update();

                UpdateBoundingBoxRendering();

                // Actualizo el frustum para que solo tome hasta la fog distance asi no manda a renderizar items del quadtree que estén por detras
                var projectionMatrixFog = TGCMatrix.PerspectiveFovLH(D3DDevice.Instance.FieldOfView, D3DDevice.Instance.AspectRatio, D3DDevice.Instance.ZNearPlaneDistance, FastMath.Abs(fog.EndDistance));
                Frustum.updateVolume(TGCMatrix.FromMatrix(D3DDevice.Instance.Device.Transform.View), projectionMatrixFog);
                ScenesQuadTree.UpdateVisibleObjects(Frustum);


                // Todos los objetos (estaticos y no estaticos)
                foreach (GameObject o in SceneObjects)
                {
                    o.Update();
                }

                // HeightMaps
                foreach (HeightMapTextured hm in heightMaps)
                {
                    hm.Update();
                }

                PlayAmbienceSound();

                // Muevo el centro del skybox para que sea inalcanzable
                skyBox.Center = new TGCVector3(Camera.Position.X, 0, Camera.Position.Z);
            }

            UpdateHUD();
            UpdateParticleEmitter();

            time += ElapsedTime;


            PostUpdate();
        }
示例#12
0
        public override void Update()
        {
            //Se cambia el valor por defecto del farplane para evitar cliping de farplane.
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(D3DDevice.Instance.FieldOfView, D3DDevice.Instance.AspectRatio,
                                                                                        D3DDevice.Instance.ZNearPlaneDistance, D3DDevice.Instance.ZFarPlaneDistance * 2f).ToMatrix();

            //Se actualiza la posicion del skybox.
            if (moveWithCameraModifier.Value)
            {
                skyBox.Center = Camera.Position;
            }
        }
示例#13
0
        private void RenderIrradianceMap(Device device)
        {
            device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f), 1f, 0.01f, 5f).ToMatrix();

            unitCube.Technique = "Irradiance";
            effect.SetValue("cubeMap", cubeMap);
            RenderToIrradianceCubeMapFace(CubeMapFace.PositiveX);
            RenderToIrradianceCubeMapFace(CubeMapFace.PositiveY);
            RenderToIrradianceCubeMapFace(CubeMapFace.PositiveZ);
            RenderToIrradianceCubeMapFace(CubeMapFace.NegativeX);
            RenderToIrradianceCubeMapFace(CubeMapFace.NegativeY);
            RenderToIrradianceCubeMapFace(CubeMapFace.NegativeZ);
        }
        // Renderiza todo incluido el postprocess en el Texture pasado
        public Texture RenderCompleto(Texture renderTarget2D)
        {
            var d3dDevice = D3DDevice.Instance.Device;

            //Cargamos el Render Targer al cual se va a dibujar la escena 3D. Antes nos guardamos el surface original
            //En vez de dibujar a la pantalla, dibujamos a un buffer auxiliar, nuestro Render Target.
            var pSurf = renderTarget2D.GetSurfaceLevel(0);

            d3dDevice.SetRenderTarget(0, pSurf);
            d3dDevice.DepthStencilSurface = depthStencil;
            var rectangle = renderTarget2D.Device.ScissorRectangle;

            // Restauro el estado de las transformaciones
            d3dDevice.Transform.View       = Camera.GetViewMatrix().ToMatrix();
            d3dDevice.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(PantallaDividida ? 65 : 45), (float)rectangle.Width / rectangle.Height, 1f, 10000f).ToMatrix();

            // dibujo pp dicho
            d3dDevice.BeginScene();
            d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            renderScene();
            d3dDevice.EndScene();

            //Liberar memoria de surface de Render Target
            pSurf.Dispose();

            //Si quisieramos ver que se dibujo, podemos guardar el resultado a una textura en un archivo para debugear su resultado (ojo, es lento)
            //TextureLoader.Save(this.ShadersDir + "render_target.bmp", ImageFileFormat.Bmp, renderTarget2D);

            // Renderizamos lo que va a tener bloom

            //Cargamos el Render Targer al cual se va a dibujar la escena 3D. Antes nos guardamos el surface original
            //En vez de dibujar a la pantalla, dibujamos a un buffer auxiliar, nuestro Render Target.
            pSurf = renderTargetBloom.GetSurfaceLevel(0);
            d3dDevice.SetRenderTarget(0, pSurf);
            d3dDevice.DepthStencilSurface = depthStencil;

            // dibujo pp dicho
            d3dDevice.BeginScene();
            d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            renderLuminoso();
            d3dDevice.EndScene();

            //Liberar memoria de surface de Render Target
            pSurf.Dispose();

            return(renderTarget2D);
        }
示例#15
0
        private void RenderPrefilterMap(Device device)
        {
            device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f), 1f, 0.01f, 5f).ToMatrix();

            unitCube.Technique = "Prefilter";
            effect.SetValue("cubeMap", cubeMap);
            int mipLevels = 5;

            for (int lod = 0; lod < mipLevels; lod++)
            {
                float roughness = (float)lod / (float)(mipLevels - 1);
                effect.SetValue("passRoughness", roughness);
                RenderToPrefilterMapFace(CubeMapFace.PositiveX, lod);
                RenderToPrefilterMapFace(CubeMapFace.PositiveY, lod);
                RenderToPrefilterMapFace(CubeMapFace.PositiveZ, lod);
                RenderToPrefilterMapFace(CubeMapFace.NegativeX, lod);
                RenderToPrefilterMapFace(CubeMapFace.NegativeY, lod);
                RenderToPrefilterMapFace(CubeMapFace.NegativeZ, lod);
            }
        }
示例#16
0
        public void UpdateAspectRatioAndProjection(int width, int height)
        {
            AspectRatio = (float)width / height;
            Width       = width;
            Height      = height;
            //hay que actualizar tambien la matriz de proyeccion, sino sigue viendo mal.
            Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(FieldOfView, AspectRatio, ZNearPlaneDistance, ZFarPlaneDistance).ToMatrix();
            //FALTA TODO ESTO DE ABAJO....
            //DefaultValues();
            //Device.Reset(d3dpp);

            /*Viewport v = new Viewport();
             * v.MaxZ = Device.Viewport.MaxZ;
             * v.MinZ = Device.Viewport.MinZ;
             * v.X = Device.Viewport.X;
             * v.Y = Device.Viewport.Y;
             * v.Width = Width;
             * v.Height = Height;
             * Device.Viewport = v;*/
        }
示例#17
0
        private void IniciarShaders(ref Effect shader)
        {
            shader = Effect.FromFile(d3dDevice, VariablesGlobales.shadersDir + "Shader.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors);
            if (shader == null)
            {
                throw new Exception("Error al cargar shader. Errores: " + compilationErrors);
            }

            VariablesGlobales.shader = shader;

            int shadowmap_size = (int)FastMath.Max(D3DDevice.Instance.Width, D3DDevice.Instance.Height) / 2;

            //--------------------------------------------------------------------------------------
            // SHADOWMAP
            // Format.R32F
            // Format.X8R8G8B8
            shadow_map = new Texture(d3dDevice, shadowmap_size, shadowmap_size, 1, Usage.RenderTarget, Format.R32F, Pool.Default);

            // tengo que crear un stencilbuffer para el shadowmap manualmente
            // para asegurarme que tenga la el mismo tamano que el shadowmap, y que no tenga
            // multisample, etc etc.
            shadow_depth = d3dDevice.CreateDepthStencilSurface(shadowmap_size, shadowmap_size, DepthFormat.D24S8, MultiSampleType.None, 0, true);
            // por ultimo necesito una matriz de proyeccion para el shadowmap, ya
            // que voy a dibujar desde el pto de vista de la luz.
            // El angulo tiene que ser mayor a 45 para que la sombra no falle en los extremos del cono de luz
            // de hecho, un valor mayor a 90 todavia es mejor, porque hasta con 90 grados es muy dificil
            // lograr que los objetos del borde generen sombras
            shadowProj = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(80), D3DDevice.Instance.AspectRatio,
                                                    5, 5000);

            /*
             * d3dDevice.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f),
             *                               D3DDevice.Instance.AspectRatio, D3DDevice.Instance.ZNearPlaneDistance,
             *                               D3DDevice.Instance.ZFarPlaneDistance).ToMatrix();//near_plane, far_plane).ToMatrix();
             * //@@@@@CUIDADO TOY CAMBIANDO TODO EL VIEW ACA
             */
            lightPos = new TGCVector3(0, 100, 50);
            lightDir = new TGCVector3(0, -1, 1);
            lightDir.Normalize();
            //--------------------------------------------------------------------------------------
        }
示例#18
0
        public Escenario()
        {
            var d3dDevice = D3DDevice.Instance.Device;

            sharpenVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured),
                                            4, d3dDevice, Usage.Dynamic | Usage.WriteOnly,
                                            CustomVertex.PositionTextured.Format, Pool.Default);
            //FullScreen Quad
            CustomVertex.PositionTextured[] vertices =
            {
                new CustomVertex.PositionTextured(-1,  1, 1, 0, 0),
                new CustomVertex.PositionTextured(1,   1, 1, 1, 0),
                new CustomVertex.PositionTextured(-1, -1, 1, 0, 1),
                new CustomVertex.PositionTextured(1,  -1, 1, 1, 1)
            };
            sharpenVBV3D.SetData(vertices, 0, LockFlags.None);
            // inicializo el render target
            Text = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                               , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                               Format.X8R8G8B8, Pool.Default);
            sharpenDepthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth,
                                                                      d3dDevice.PresentationParameters.BackBufferHeight,
                                                                      DepthFormat.D24S8, MultiSampleType.None, 0, true);// Creo el shadowmap.
            // Format.R32F
            // Format.X8R8G8B8
            g_pShadowMap = new Texture(D3DDevice.Instance.Device, SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, Usage.RenderTarget, Format.R32F, Pool.Default);

            // tengo que crear un stencilbuffer para el shadowmap manualmente
            // para asegurarme que tenga la el mismo tamano que el shadowmap, y que no tenga
            // multisample, etc etc.
            shadowDepthStencil = D3DDevice.Instance.Device.CreateDepthStencilSurface(SHADOWMAP_SIZE, SHADOWMAP_SIZE, DepthFormat.D24S8, MultiSampleType.None, 0, true);
            // por ultimo necesito una matriz de proyeccion para el shadowmap, ya
            // que voy a dibujar desde el pto de vista de la luz.
            // El angulo tiene que ser mayor a 45 para que la sombra no falle en los extremos del cono de luz
            // de hecho, un valor mayor a 90 todavia es mejor, porque hasta con 90 grados es muy dificil
            // lograr que los objetos del borde generen sombras
            var aspectRatio = D3DDevice.Instance.AspectRatio;

            g_mShadowProj = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(80), aspectRatio, 50, 5000);
        }
示例#19
0
        public Shadow()
        {
            g.shadow = this;

            shader = TGCShaders.Instance.LoadEffect(TGCShaders.Instance.CommonShadersPath + "shadow.fx");

            tex    = new Texture(D3DDevice.Instance.Device, SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, Usage.RenderTarget, Format.R32F, Pool.Default);
            depths = D3DDevice.Instance.Device.CreateDepthStencilSurface(SHADOWMAP_SIZE, SHADOWMAP_SIZE, DepthFormat.D24S8, MultiSampleType.None, 0, true);

            g.map.shader.SetValue("shadowTexture", tex);

            var aspectRatio = D3DDevice.Instance.AspectRatio;
            var nearPlane   = 50;
            var farPlane    = 5000000;

            proj = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(80), aspectRatio, nearPlane, farPlane);


            //var nearPlane2 = 50;
            //var farPlane2 = 5000000;
            //D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, nearPlane2, farPlane2).ToMatrix();
            //ni idea de que hace esta linea pero me hizo perder una hora cuando cambie el orden de inicializacion
            //y cambio la matriz esta, que solo afectaba a las velas en mano y la barra de estamina
        }
        public void Init()
        {
            this.CreateSmoke();
            this.CreateSpark();
            //--------------------------------------------------------------------------------------
            // Creo el shadowmap.
            // Format.R32F
            // Format.X8R8G8B8
            g_pShadowMap = new Texture(D3DDevice.Instance.Device, SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, Usage.RenderTarget, Format.R32F, Pool.Default);

            // tengo que crear un stencilbuffer para el shadowmap manualmente
            // para asegurarme que tenga la el mismo tamano que el shadowmap, y que no tenga
            // multisample, etc etc.
            g_pDSShadow = D3DDevice.Instance.Device.CreateDepthStencilSurface(SHADOWMAP_SIZE, SHADOWMAP_SIZE, DepthFormat.D24S8, MultiSampleType.None, 0, true);
            // por ultimo necesito una matriz de proyeccion para el shadowmap, ya
            // que voy a dibujar desde el pto de vista de la luz.
            // El angulo tiene que ser mayor a 45 para que la sombra no falle en los extremos del cono de luz
            // de hecho, un valor mayor a 90 todavia es mejor, porque hasta con 90 grados es muy dificil
            // lograr que los objetos del borde generen sombras
            var aspectRatio = D3DDevice.Instance.AspectRatio;

            g_mShadowProj = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(80), aspectRatio, 50, 5000);
            // D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, 2f, 1500f).ToMatrix();
        }
示例#21
0
        public unsafe override void Init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            GuiController.Instance.CustomRenderEnabled = true;

            MyMediaDir  = MediaDir + "WorkshopShaders\\";
            MyShaderDir = ShadersDir + "WorkshopShaders\\";

            time  = 0f;
            vel_x = new float[MAX_DS, MAX_DS];
            vel_z = new float[MAX_DS, MAX_DS];
            pos_x = new float[MAX_DS, MAX_DS];
            pos_y = new float[MAX_DS, MAX_DS];
            pos_z = new float[MAX_DS, MAX_DS];

            //Crear loader
            TgcSceneLoader loader = new TgcSceneLoader();

            // ------------------------------------------------------------
            //Path de Heightmap default del terreno y Path de Textura default del terreno
            TGCVector3 PosTerrain = new TGCVector3(0, 0, 0);

            currentHeightmap = MyMediaDir + "Heighmaps\\" + "Heightmap2.jpg";
            currentScaleXZ   = 100f;
            currentScaleY    = 6f;
            currentTexture   = MyMediaDir + "Heighmaps\\" + "Heightmap2.JPG";       //+ "grid.JPG";
            terrain          = new TgcSimpleTerrain();
            terrain.loadHeightmap(currentHeightmap, currentScaleXZ, currentScaleY, PosTerrain);
            terrain.loadTexture(currentTexture);
            // tomo el ancho de la textura, ojo tiene que ser cuadrada
            float terrain_width = (float)terrain.HeightmapData.GetLength(0);

            // mesh principal
            scene = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Sphere\\Sphere-TgcScene.xml");
            Bitmap b = (Bitmap)Bitmap.FromFile(MyMediaDir + "Heighmaps\\grid.jpg");

            g_pBaseTexture = Texture.FromBitmap(d3dDevice, b, Usage.None, Pool.Managed);
            b.Dispose();
            mesh                     = scene.Meshes[0];
            mesh.Scale               = new TGCVector3(0.5f, 0.5f, 0.5f);
            mesh.Position            = new TGCVector3(0f, 0f, 0f);
            mesh.AutoTransformEnable = false;
            TGCVector3 size = mesh.BoundingBox.calculateSize();

            esfera_radio = Math.Abs(size.Y) / 2;

            //Cargar Shader
            string compilationErrors;

            effect = Effect.FromFile(d3dDevice, MyShaderDir + "GPUCompute.fx", null, null, ShaderFlags.None, null, out compilationErrors);
            if (effect == null)
            {
                throw new Exception("Error al cargar shader. Errores: " + compilationErrors);
            }
            //Configurar Technique
            effect.Technique = "DefaultTechnique";
            effect.SetValue("map_size", terrain_width);
            effect.SetValue("map_desf", 0.5f / terrain_width);

            arrow            = new TgcArrow();
            arrow.Thickness  = 1f;
            arrow.HeadSize   = new TGCVector2(2f, 2f);
            arrow.BodyColor  = Color.Blue;
            arrowN           = new TgcArrow();
            arrowN.Thickness = 1f;
            arrowN.HeadSize  = new TGCVector2(2f, 2f);
            arrowN.BodyColor = Color.Red;
            arrowT           = new TgcArrow();
            arrowT.Thickness = 1f;
            arrowT.HeadSize  = new TGCVector2(2f, 2f);
            arrowT.BodyColor = Color.Green;

            GuiController.Instance.RotCamera.CameraCenter   = new TGCVector3(0, 0, 0);
            GuiController.Instance.RotCamera.CameraDistance = 3200;
            GuiController.Instance.RotCamera.RotationSpeed  = 2f;

            LookAt   = new TGCVector3(0, 0, 0);
            LookFrom = new TGCVector3(3200, 3000, 3200);

            float aspectRatio = (float)GuiController.Instance.Panel3d.Width / GuiController.Instance.Panel3d.Height;

            GuiController.Instance.CurrentCamera.updateCamera();
            d3dDevice.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, 5f, 40000f);

            // Creo el mapa de velocidad
            g_pVelocidad    = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default);
            g_pVelocidadOut = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default);
            // Mapa de Posicion
            g_pPos    = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default);
            g_pPosOut = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default);

            // stencil compatible sin multisampling
            g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(MAX_DS, MAX_DS, DepthFormat.D24S8, MultiSampleType.None, 0, true);

            // temporaria para recuperar los valores
            g_pTempVel = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, 0, Format.A32B32G32R32F, Pool.SystemMemory);
            g_pTempPos = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, 0, Format.A32B32G32R32F, Pool.SystemMemory);

            effect.SetValue("g_pVelocidad", g_pVelocidad);
            effect.SetValue("g_pPos", g_pPos);
            // Textura del heigmap
            g_pHeightmap = TextureLoader.FromFile(d3dDevice, currentHeightmap);
            effect.SetValue("height_map", g_pHeightmap);

            // Resolucion de pantalla
            effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth);
            effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight);
            effect.SetValue("currentScaleXZ", currentScaleXZ);
            effect.SetValue("currentScaleY", currentScaleY);

            //Se crean 2 triangulos con las dimensiones de la pantalla con sus posiciones ya transformadas
            // x = -1 es el extremo izquiedo de la pantalla, x=1 es el extremo derecho
            // Lo mismo para la Y con arriba y abajo
            // la Z en 1 simpre
            CustomVertex.PositionTextured[] vertices = new CustomVertex.PositionTextured[]
            {
                new CustomVertex.PositionTextured(-1, 1, 1, 0, 0),
                new CustomVertex.PositionTextured(1, 1, 1, 1, 0),
                new CustomVertex.PositionTextured(-1, -1, 1, 0, 1),
                new CustomVertex.PositionTextured(1, -1, 1, 1, 1)
            };
            //vertex buffer de los triangulos
            g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default);
            g_pVBV3D.SetData(vertices, 0, LockFlags.None);

            g_pVB = new VertexBuffer(typeof(CustomVertex.PositionColored), MAX_DS * MAX_DS, d3dDevice, Usage.Dynamic | Usage.None, CustomVertex.PositionColored.Format, Pool.Default);

            // inicializo el mapa de velocidades
            Device    device    = GuiController.Instance.D3dDevice;
            TGCMatrix ant_Proj  = device.Transform.Projection;
            TGCMatrix ant_World = device.Transform.World;
            TGCMatrix ant_View  = device.Transform.View;

            device.Transform.Projection = TGCMatrix.Identity;
            device.Transform.World      = TGCMatrix.Identity;
            device.Transform.View       = TGCMatrix.Identity;

            // rt1 = velocidad
            Surface pOldRT = device.GetRenderTarget(0);
            Surface pSurf  = g_pVelocidad.GetSurfaceLevel(0);

            device.SetRenderTarget(0, pSurf);
            Surface pOldDS = device.DepthStencilSurface;

            device.DepthStencilSurface = g_pDepthStencil;

            // rt2 = posicion
            Surface pSurf2 = g_pPos.GetSurfaceLevel(0);

            device.SetRenderTarget(1, pSurf2);

            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            device.BeginScene();
            effect.Technique    = "ComputeVel";
            device.VertexFormat = CustomVertex.PositionTextured.Format;
            device.SetStreamSource(0, g_pVBV3D, 0);
            effect.Begin(FX.None);
            effect.BeginPass(0);
            device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
            effect.EndPass();
            effect.End();
            device.EndScene();

            effect.SetValue("Kp", esfera_radio * (float)Math.PI / 2);

            // restauro los RT
            device.SetRenderTarget(0, pOldRT);
            device.SetRenderTarget(1, null);
            device.DepthStencilSurface = pOldDS;
            // restauro las Transf.
            device.Transform.Projection = ant_Proj;
            device.Transform.World      = ant_World;
            device.Transform.View       = ant_View;

            Modifiers.addBoolean("dibujar_terreno", "Dibujar Terreno", true);
        }
示例#22
0
        /// <summary>
        ///     Se llama una sola vez, al principio cuando se ejecuta el ejemplo.
        ///     Escribir aquí todo el código de inicialización: cargar modelos, texturas, estructuras de optimización, todo
        ///     procesamiento que podemos pre calcular para nuestro juego.
        ///     Borrar el codigo ejemplo no utilizado.
        /// </summary>
        public override void Init()
        {
            estrellasS.ForEach(e => e.AutoTransform = true);
            CustomVertex.PositionTextured[] screenQuadVertices =
            {
                new CustomVertex.PositionTextured(-1,  1, 1, 0, 0),
                new CustomVertex.PositionTextured(1,   1, 1, 1, 0),
                new CustomVertex.PositionTextured(-1, -1, 1, 0, 1),
                new CustomVertex.PositionTextured(1,  -1, 1, 1, 1)
            };
            //vertex buffer de los triangulos
            screenQuadVB = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, D3DDevice.Instance.Device, Usage.Dynamic | Usage.WriteOnly,
                                            CustomVertex.PositionTextured.Format, Pool.Default);
            screenQuadVB.SetData(screenQuadVertices, 0, LockFlags.None);

            //Creamos un DepthStencil que debe ser compatible con nuestra definicion de renderTarget2D.
            depthStencil = D3DDevice.Instance.Device.CreateDepthStencilSurface(D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth,
                                                                               D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true);

            depthStencilOld = D3DDevice.Instance.Device.DepthStencilSurface;


            escena = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth,
                                 D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default);

            propulsores = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth,
                                      D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default);

            propulsoresBlurAux = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth,
                                             D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default);

            propulsoresBlurAux2 = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth,
                                              D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default);

            //Device de DirectX para crear primitivas.
            var d3dDevice = D3DDevice.Instance.Device;

            D3DDevice.Instance.Device.Transform.Projection =
                Matrix.PerspectiveFovLH(D3DDevice.Instance.FieldOfView,
                                        D3DDevice.Instance.AspectRatio,
                                        D3DDevice.Instance.ZNearPlaneDistance,
                                        D3DDevice.Instance.ZFarPlaneDistance * 1.8f);

            this.postProcessMerge = TgcShaders.loadEffect(this.ShadersDir + "PostProcess.fx");
            this.blurEffect       = TgcShaders.loadEffect(this.ShadersDir + "GaussianBlur.fx");

            blurEffect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth);
            blurEffect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight);

            this.escenarios = new List <Escenario>();
            this.enemigos   = new List <NaveEnemiga>();

            //Crear SkyBox
            skyBox        = new TgcSkyBox();
            skyBox.Center = new TGCVector3(0, 0, -2300f);
            skyBox.Size   = new TGCVector3(10000, 10000, 18000);
            var texturesPath = MediaDir + "XWing\\Textures\\";

            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "space.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "space.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "space.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "space.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "space.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "space.jpg");

            skyBox.Init();

            this.navePrincipal                = new NaveEspacial(MediaDir, "xwing-TgcScene.xml", Color.DarkBlue, 10, 250, null, 250f);
            this.navePrincipal.ScaleFactor    = TGCMatrix.Scaling(0.5f, 0.5f, 0.5f);
            this.navePrincipal.RotationVector = new TGCVector3(0, FastMath.PI_HALF, 0);
            this.navePrincipal.MovementVector = new TGCVector3(1200f, -1100f, 4000f);


            for (int i = 0; i < 5; i++)
            {
                escenarios.Add(Escenario.GenerarEscenarioDefault(MediaDir, i));
            }

            for (int i = 0; i < enemigosAlMismoTiempo; i++)
            {
                enemigos.Add(new NaveEnemiga(MediaDir, "X-Wing-TgcScene.xml", dañoEnemigos, 500, navePrincipal));
                enemigos[i].MovementVector = new TGCVector3(0, 0, 500000000000f);
                enemigos[i].CreateOOB();
            }


            //escenarios.ForEach(es => es.generarTorre(MediaDir));
            currentScene = escenarios[0];

            this.navePrincipal.CreateOOB();
            //Suelen utilizarse objetos que manejan el comportamiento de la camara.
            //Lo que en realidad necesitamos gráficamente es una matriz de View.
            //El framework maneja una cámara estática, pero debe ser inicializada.
            //Posición de la camara.
            var cameraPosition = new TGCVector3(0, 0, 0);
            //Quiero que la camara mire hacia el origen (0,0,0).
            var lookAt = new TGCVector3(-50000, -1, 0);

            //Configuro donde esta la posicion de la camara y hacia donde mira.
            Camara.SetCamera(cameraPosition, lookAt);
            //Internamente el framework construye la matriz de view con estos dos vectores.
            //Luego en nuestro juego tendremos que crear una cámara que cambie la matriz de view con variables como movimientos o animaciones de escenas.

            Camara = new CamaraStarWars(this.navePrincipal.GetPosition(), 20, 100);

            sol = TGCBox.fromSize(new TGCVector3(0, 5000, 4000), new TGCVector3(50, 50, 50), Color.Yellow);
            sol.AutoTransform = true;
            menu = new Menu(MediaDir, Input);

            //Cargo sonidos
            pathSonidoMenu     = MediaDir + "Sound\\musica_menu.mp3";
            pathSonidoAmbiente = MediaDir + "Music\\StarWarsMusic.mp3";
            pathSonidoDisparo  = MediaDir + "Music\\laserSound.wav";

            if (menu.playSonidoMenu)
            {
                playerAmbiente.closeFile();
                playerAmbiente.FileName = pathSonidoMenu;
                playerAmbiente.play(true);
            }


            drawer = new Drawer2D();
            hud    = new Hud(MediaDir, Input);

            //ShadowMap

            // Creo el shadowmap.
            // Format.R32F
            // Format.X8R8G8B8
            g_pShadowMap = new Texture(D3DDevice.Instance.Device, SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, Usage.RenderTarget, Format.R32F, Pool.Default);

            // tengo que crear un stencilbuffer para el shadowmap manualmente
            // para asegurarme que tenga la el mismo tamano que el shadowmap, y que no tenga
            // multisample, etc etc.
            g_pDSShadow = D3DDevice.Instance.Device.CreateDepthStencilSurface(SHADOWMAP_SIZE, SHADOWMAP_SIZE, DepthFormat.D24S8, MultiSampleType.None, 0, true);
            // por ultimo necesito una matriz de proyeccion para el shadowmap, ya
            // que voy a dibujar desde el pto de vista de la luz.
            // El angulo tiene que ser mayor a 45 para que la sombra no falle en los extremos del cono de luz
            // de hecho, un valor mayor a 90 todavia es mejor, porque hasta con 90 grados es muy dificil
            // lograr que los objetos del borde generen sombras
            var aspectRatio = D3DDevice.Instance.AspectRatio;

            g_mShadowProj = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(50), aspectRatio, 50, 15000);
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, near_plane, far_plane).ToMatrix();
        }
示例#23
0
        public override void Render()
        {
            ClearTextures();
            D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            D3DDevice.Instance.Device.BeginScene();

            var aspectRatio = D3DDevice.Instance.AspectRatio;

            time += ElapsedTime;

            if (Input.keyPressed(Key.C))
            {
                timer_preview = 0;
                camara_rot    = !camara_rot;
            }

            if (Input.keyPressed(Key.F))
            {
                if (tipo_vista == 1)
                {
                    tipo_vista = 0;
                }
                else
                {
                    tipo_vista = 1;
                }
                ant_vista = tipo_vista;
            }

            if (Input.keyPressed(Key.D))
            {
                if (tipo_vista == 2)
                {
                    tipo_vista = ant_vista;
                }
                else
                {
                    tipo_vista = 2;
                }
            }

            if (Input.keyPressed(Key.Space))
            {
                if (vel_tanque <= 1)
                {
                    vel_tanque = 10;
                }
                else
                {
                    vel_tanque = 1;
                }
            }

            if (timer_preview > 0)
            {
                timer_preview -= ElapsedTime;
                if (timer_preview < 0)
                {
                    timer_preview = 0;
                }
            }

            // animar tanque
            an_tanque -= ElapsedTime * Geometry.DegreeToRadian(vel_tanque);
            var   alfa         = an_tanque;
            var   x0           = 2000f * (float)Math.Cos(alfa);
            var   z0           = 2000f * (float)Math.Sin(alfa);
            float offset_rueda = 10;
            var   H            = terrain.CalcularAltura(x0, z0) + alto_tanque / 2 - offset_rueda;

            if (H < nivel_mar)
            {
                H = nivel_mar;
            }
            mesh.Position = new TGCVector3(x0, H, z0);
            // direccion tangente sobre el piso:
            var dir_tanque = new TGCVector2(-(float)Math.Sin(alfa), (float)Math.Cos(alfa));

            dir_tanque.Normalize();
            // Posicion de la parte de adelante del tanque
            var pos2d = new TGCVector2(x0, z0);

            pos2d = pos2d + dir_tanque * (largo_tanque / 2);
            var H_frente = terrain.CalcularAltura(pos2d.X, pos2d.Y) + alto_tanque / 2 - offset_rueda;

            if (H_frente < nivel_mar - 15)
            {
                H_frente = nivel_mar - 15;
            }
            var pos_frente = new TGCVector3(pos2d.X, H_frente, pos2d.Y);
            var Vel        = pos_frente - mesh.Position;

            Vel.Normalize();
            mesh.Transform = CalcularMatriz(mesh.Position, mesh.Scale, Vel);

            // animo la canoa en circulos:
            alfa = -time *Geometry.DegreeToRadian(10.0f);

            x0              = 400f * (float)Math.Cos(alfa);
            z0              = 400f * (float)Math.Sin(alfa);
            canoa.Position  = new TGCVector3(x0, 150, z0);
            dir_canoa       = new TGCVector3(-(float)Math.Sin(alfa), 0, (float)Math.Cos(alfa));
            canoa.Transform = CalcularMatriz(canoa.Position, canoa.Scale, dir_canoa);

            alfa_sol += ElapsedTime * Geometry.DegreeToRadian(1.0f);
            if (alfa_sol > 2.5)
            {
                alfa_sol = 1.5f;
            }
            // animo la posicion del sol
            //g_LightPos = new TGCVector3(1500f * (float)Math.Cos(alfa_sol), 1500f * (float)Math.Sin(alfa_sol), 0f);
            g_LightPos = new TGCVector3(2000f * (float)Math.Cos(alfa_sol), 2000f * (float)Math.Sin(alfa_sol),
                                        0f);
            g_LightDir = -g_LightPos;
            g_LightDir.Normalize();

            if (timer_preview > 0)
            {
                var an = -time *Geometry.DegreeToRadian(10.0f);

                LookFrom.X = 1500f * (float)Math.Sin(an);
                LookFrom.Z = 1500f * (float)Math.Cos(an);
            }
            else
            {
                if (camara_rot)
                {
                    CamaraRot.CameraCenter = mesh.BoundingBox.calculateBoxCenter();
                    CamaraRot.UpdateCamera(ElapsedTime); //FIXME, puede que no haga falta esto.
                    Camara = CamaraRot;
                }
                else
                {
                    Camara = DefaultCamera;
                }
            }

            // --------------------------------------------------------------------
            D3DDevice.Instance.Device.EndScene();
            if (g_pCubeMapAgua == null)
            {
                // solo la primera vez crea el env map del agua
                CrearEnvMapAgua();
                // ya que esta creado, se lo asigno al effecto:
                effect.SetValue("g_txCubeMapAgua", g_pCubeMapAgua);
            }

            // Creo el env map del tanque:
            var g_pCubeMap = new CubeTexture(D3DDevice.Instance.Device, 256, 1, Usage.RenderTarget,
                                             Format.A16B16G16R16F, Pool.Default);
            var pOldRT = D3DDevice.Instance.Device.GetRenderTarget(0);

            // ojo: es fundamental que el fov sea de 90 grados.
            // asi que re-genero la matriz de proyeccion
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f), 1f, near_plane, far_plane).ToMatrix();

            // Genero las caras del enviroment map
            for (var nFace = CubeMapFace.PositiveX; nFace <= CubeMapFace.NegativeZ; ++nFace)
            {
                var pFace = g_pCubeMap.GetCubeMapSurface(nFace, 0);
                D3DDevice.Instance.Device.SetRenderTarget(0, pFace);
                TGCVector3 Dir, VUP;
                Color      color;
                switch (nFace)
                {
                default:
                case CubeMapFace.PositiveX:
                    // Left
                    Dir   = new TGCVector3(1, 0, 0);
                    VUP   = TGCVector3.Up;
                    color = Color.Black;
                    break;

                case CubeMapFace.NegativeX:
                    // Right
                    Dir   = new TGCVector3(-1, 0, 0);
                    VUP   = TGCVector3.Up;
                    color = Color.Red;
                    break;

                case CubeMapFace.PositiveY:
                    // Up
                    Dir   = TGCVector3.Up;
                    VUP   = new TGCVector3(0, 0, -1);
                    color = Color.Gray;
                    break;

                case CubeMapFace.NegativeY:
                    // Down
                    Dir   = TGCVector3.Down;
                    VUP   = new TGCVector3(0, 0, 1);
                    color = Color.Yellow;
                    break;

                case CubeMapFace.PositiveZ:
                    // Front
                    Dir   = new TGCVector3(0, 0, 1);
                    VUP   = TGCVector3.Up;
                    color = Color.Green;
                    break;

                case CubeMapFace.NegativeZ:
                    // Back
                    Dir   = new TGCVector3(0, 0, -1);
                    VUP   = TGCVector3.Up;
                    color = Color.Blue;
                    break;
                }

                //Obtener ViewMatrix haciendo un LookAt desde la posicion final anterior al centro de la camara
                var Pos = mesh.Position;
                D3DDevice.Instance.Device.Transform.View = TGCMatrix.LookAtLH(Pos, Pos + Dir, VUP).ToMatrix();

                D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, color, 1.0f, 0);
                D3DDevice.Instance.Device.BeginScene();

                //Renderizar
                renderScene(ElapsedTime, true);

                D3DDevice.Instance.Device.EndScene();
                //string fname = string.Format("face{0:D}.bmp", nFace);
                //SurfaceLoader.Save(fname, ImageFileFormat.Bmp, pFace);
            }
            // restuaro el render target
            D3DDevice.Instance.Device.SetRenderTarget(0, pOldRT);
            //TextureLoader.Save("test.bmp", ImageFileFormat.Bmp, g_pCubeMap);

            //Genero el shadow map
            RenderShadowMap();

            // Restauro el estado de las transformaciones
            if (timer_preview > 0)
            {
                D3DDevice.Instance.Device.Transform.View = TGCMatrix.LookAtLH(LookFrom, LookAt, TGCVector3.Up).ToMatrix();
            }
            else
            {
                D3DDevice.Instance.Device.Transform.View = Camara.GetViewMatrix().ToMatrix();
            }
            // FIXME! esto no se bien para que lo hace aca.

            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, near_plane, far_plane).ToMatrix();

            // Cargo las var. del shader:
            effect.SetValue("g_txCubeMap", g_pCubeMap);
            effect.SetValue("fvLightPosition", new Vector4(0, 400, 0, 0));
            effect.SetValue("fvEyePosition", TGCVector3.Vector3ToFloat3Array(timer_preview > 0 ? LookFrom : Camara.Position));
            effect.SetValue("time", time);

            // -----------------------------------------------------
            // dibujo la escena pp dicha:
            D3DDevice.Instance.Device.BeginScene();

            if (tipo_vista != 1)
            {
                // con shaders :
                if (tipo_vista == 2)
                {
                    // dibujo en una vista:
                    D3DDevice.Instance.Device.Viewport = View1;
                }
                else
                {
                    // dibujo en la pantalla completa
                    D3DDevice.Instance.Device.Viewport = ViewF;
                }

                D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                // 1ero sin el agua
                renderScene(ElapsedTime, false);

                // Ahora dibujo el agua
                D3DDevice.Instance.Device.RenderState.AlphaBlendEnable = true;
                effect.SetValue("aux_Tex", terrain.terrainTexture);
                // posicion de la canoa (divido por la escala)
                effect.SetValue("canoa_x", x0 / 10.0f);
                effect.SetValue("canoa_y", z0 / 10.0f);
                piso.Technique = "RenderAgua";
                piso.Render();
            }

            if (tipo_vista != 0)
            {
                // sin shaders
                if (tipo_vista == 2)
                {
                    // dibujo en una vista:
                    D3DDevice.Instance.Device.Viewport = View2;
                }
                else
                {
                    // dibujo en la pantalla completa
                    D3DDevice.Instance.Device.Viewport = ViewF;
                }

                D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                //Renderizar terreno
                terrain.render();
                //Renderizar SkyBox
                skyBox.Render();
                // dibujo el bosque
                foreach (var instance in bosque)
                {
                    instance.UpdateMeshTransform();
                    instance.Render();
                }
                // canoa
                canoa.Render();
                // tanque
                mesh.Render();
                // agua
                var ant_src   = D3DDevice.Instance.Device.RenderState.SourceBlend;
                var ant_dest  = D3DDevice.Instance.Device.RenderState.DestinationBlend;
                var ant_alpha = D3DDevice.Instance.Device.RenderState.AlphaBlendEnable;
                D3DDevice.Instance.Device.RenderState.AlphaBlendEnable = true;
                D3DDevice.Instance.Device.RenderState.SourceBlend      = Blend.SourceColor;
                D3DDevice.Instance.Device.RenderState.DestinationBlend = Blend.InvSourceColor;
                piso.Render();
                D3DDevice.Instance.Device.RenderState.SourceBlend      = ant_src;
                D3DDevice.Instance.Device.RenderState.DestinationBlend = ant_dest;
                D3DDevice.Instance.Device.RenderState.AlphaBlendEnable = ant_alpha;
            }

            g_pCubeMap.Dispose();

            RenderFPS();
            RenderAxis();
            D3DDevice.Instance.Device.EndScene();
            D3DDevice.Instance.Device.Present();
        }
示例#24
0
        public override void Render()
        {
            PreRender();

            var aspectRatio = D3DDevice.Instance.AspectRatio;

            if (Input.keyPressed(Key.Space))
            {
                vel_tanque++;
                if (vel_tanque > 10)
                {
                    vel_tanque = 0;
                }
            }
            if (Input.keyPressed(Key.X))
            {
                volar = !volar;
            }

            if (Input.keyPressed(Key.S))
            {
                // swap mesh
                var mesh_aux = mesh;
                mesh  = meshX;
                meshX = mesh;
            }

            //Cargar variables de shader
            effect.SetValue("fvLightPosition", new Vector4(0, 400, 0, 0));
            effect.SetValue("fvEyePosition", TGCVector3.Vector3ToFloat3Array(Camara.Position));
            effect.SetValue("kx", reflexionModifier.Value);
            effect.SetValue("kc", refraccionModifier.Value);
            effect.SetValue("usar_fresnel", fresnelModifier.Value);

            time += ElapsedTime;
            // animar tanque
            var alfa = -time *Geometry.DegreeToRadian(vel_tanque);

            var   x0           = 2000f * (float)Math.Cos(alfa);
            var   z0           = 2000f * (float)Math.Sin(alfa);
            float offset_rueda = 13;
            var   H            = CalcularAltura(x0, z0) + alto_tanque / 2 - offset_rueda;

            if (volar)
            {
                H += 300;
            }
            mesh.Position = new TGCVector3(x0, H, z0);
            // direccion tangente sobre el piso:
            var dir_tanque = new TGCVector2(-(float)Math.Sin(alfa), (float)Math.Cos(alfa));

            dir_tanque.Normalize();
            // Posicion de la parte de adelante del tanque
            var pos2d = new TGCVector2(x0, z0);

            pos2d = pos2d + dir_tanque * (largo_tanque / 2);
            var H_frente = CalcularAltura(pos2d.X, pos2d.Y) + alto_tanque / 2 - offset_rueda;

            if (volar)
            {
                H_frente += 300;
            }
            var pos_frente = new TGCVector3(pos2d.X, H_frente, pos2d.Y);
            var Vel        = pos_frente - mesh.Position;

            Vel.Normalize();

            mesh.Transform = CalcularMatriz(mesh.Position, mesh.Scale, Vel);

            var beta = -time *Geometry.DegreeToRadian(120.0f);

            avion.Position  = new TGCVector3(x0 + 300f * (float)Math.Cos(beta), 400 + H, z0 + 300f * (float)Math.Sin(alfa));
            dir_avion       = new TGCVector3(-(float)Math.Sin(beta), 0, (float)Math.Cos(beta));
            avion.Transform = CalcularMatriz(avion.Position, avion.Scale, dir_avion);

            // --------------------------------------------------------------------
            D3DDevice.Instance.Device.EndScene();
            var g_pCubeMap = new CubeTexture(D3DDevice.Instance.Device, 256, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);
            var pOldRT     = D3DDevice.Instance.Device.GetRenderTarget(0);

            // ojo: es fundamental que el fov sea de 90 grados.
            // asi que re-genero la matriz de proyeccion
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f), 1f, 1f, 10000f).ToMatrix();

            // Genero las caras del enviroment map
            for (var nFace = CubeMapFace.PositiveX; nFace <= CubeMapFace.NegativeZ; ++nFace)
            {
                var pFace = g_pCubeMap.GetCubeMapSurface(nFace, 0);
                D3DDevice.Instance.Device.SetRenderTarget(0, pFace);
                TGCVector3 Dir, VUP;
                Color      color;
                switch (nFace)
                {
                default:
                case CubeMapFace.PositiveX:
                    // Left
                    Dir   = new TGCVector3(1, 0, 0);
                    VUP   = TGCVector3.Up;
                    color = Color.Black;
                    break;

                case CubeMapFace.NegativeX:
                    // Right
                    Dir   = new TGCVector3(-1, 0, 0);
                    VUP   = TGCVector3.Up;
                    color = Color.Red;
                    break;

                case CubeMapFace.PositiveY:
                    // Up
                    Dir   = TGCVector3.Up;
                    VUP   = new TGCVector3(0, 0, -1);
                    color = Color.Gray;
                    break;

                case CubeMapFace.NegativeY:
                    // Down
                    Dir   = TGCVector3.Down;
                    VUP   = new TGCVector3(0, 0, 1);
                    color = Color.Yellow;
                    break;

                case CubeMapFace.PositiveZ:
                    // Front
                    Dir   = new TGCVector3(0, 0, 1);
                    VUP   = TGCVector3.Up;
                    color = Color.Green;
                    break;

                case CubeMapFace.NegativeZ:
                    // Back
                    Dir   = new TGCVector3(0, 0, -1);
                    VUP   = TGCVector3.Up;
                    color = Color.Blue;
                    break;
                }

                //como queremos usar la camara rotacional pero siguendo a un objetivo comentamos el seteo del view.
                //Obtener ViewMatrix haciendo un LookAt desde la posicion final anterior al centro de la camara
                //var Pos = mesh.Position;
                //D3DDevice.Instance.Device.Transform.View = TGCMatrix.LookAtLH(Pos, Pos + Dir, VUP);
                CamaraRot.CameraCenter = mesh.Position;

                D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, color, 1.0f, 0);
                D3DDevice.Instance.Device.BeginScene();

                //Renderizar
                renderScene(ElapsedTime, true);

                D3DDevice.Instance.Device.EndScene();
                //string fname = string.Format("face{0:D}.bmp", nFace);
                //SurfaceLoader.Save(fname, ImageFileFormat.Bmp, pFace);
            }
            // restuaro el render target
            D3DDevice.Instance.Device.SetRenderTarget(0, pOldRT);
            //TextureLoader.Save("test.bmp", ImageFileFormat.Bmp, g_pCubeMap);

            // Restauro el estado de las transformaciones
            D3DDevice.Instance.Device.Transform.View       = Camara.GetViewMatrix().ToMatrix();
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, 1f, 10000f).ToMatrix();

            // dibujo pp dicho
            D3DDevice.Instance.Device.BeginScene();
            D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            effect.SetValue("g_txCubeMap", g_pCubeMap);
            renderScene(ElapsedTime, false);
            g_pCubeMap.Dispose();

            D3DDevice.Instance.Device.EndScene();
            D3DDevice.Instance.Device.Present();
        }
示例#25
0
        public override void Init()
        {
            MyMediaDir  = MediaDir + "WorkshopShaders\\";
            MyShaderDir = ShadersDir + "WorkshopShaders\\";

            //Crear loader
            var loader = new TgcSceneLoader();

            // ------------------------------------------------------------
            //Cargar la escena
            scene = loader.loadSceneFromFile(MyMediaDir + "shadowTest\\ShadowTest-TgcScene.xml");

            scene2 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\AvionCaza\\AvionCaza-TgcScene.xml");
            avion  = scene2.Meshes[0];

            avion.Scale     = new TGCVector3(0.1f, 0.1f, 0.1f);
            avion.Position  = new TGCVector3(100f, 100f, 0f);
            avion.Transform = TGCMatrix.Scaling(avion.Scale) * TGCMatrix.Translation(avion.Position);
            dir_avion       = new TGCVector3(0, 0, 1);

            //Cargar Shader personalizado
            effect = TGCShaders.Instance.LoadEffect(MyShaderDir + "ShadowMap.fx");

            // le asigno el efecto a las mallas
            foreach (var T in scene.Meshes)
            {
                T.Scale  = TGCVector3.One;
                T.Effect = effect;
            }
            avion.Effect = effect;

            //--------------------------------------------------------------------------------------
            // Creo el shadowmap.
            // Format.R32F
            // Format.X8R8G8B8
            g_pShadowMap = new Texture(D3DDevice.Instance.Device, SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, Usage.RenderTarget, Format.R32F, Pool.Default);

            // tengo que crear un stencilbuffer para el shadowmap manualmente
            // para asegurarme que tenga la el mismo tamano que el shadowmap, y que no tenga
            // multisample, etc etc.
            g_pDSShadow = D3DDevice.Instance.Device.CreateDepthStencilSurface(SHADOWMAP_SIZE, SHADOWMAP_SIZE, DepthFormat.D24S8, MultiSampleType.None, 0, true);
            // por ultimo necesito una matriz de proyeccion para el shadowmap, ya
            // que voy a dibujar desde el pto de vista de la luz.
            // El angulo tiene que ser mayor a 45 para que la sombra no falle en los extremos del cono de luz
            // de hecho, un valor mayor a 90 todavia es mejor, porque hasta con 90 grados es muy dificil
            // lograr que los objetos del borde generen sombras
            var aspectRatio = D3DDevice.Instance.AspectRatio;

            g_mShadowProj = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(80), aspectRatio, 50, 5000);
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, near_plane, far_plane).ToMatrix();

            arrow           = new TgcArrow();
            arrow.Thickness = 1f;
            arrow.HeadSize  = new TGCVector2(2f, 2f);
            arrow.BodyColor = Color.Blue;

            float K = 300;

            lightLookFromModifier = AddVertex3f("LightLookFrom", new TGCVector3(-K, -K, -K), new TGCVector3(K, K, K), new TGCVector3(80, 120, 0));
            lightLookAtModifier   = AddVertex3f("LightLookAt", new TGCVector3(-K, -K, -K), new TGCVector3(K, K, K), TGCVector3.Empty);

            var rotCamera = new TgcRotationalCamera(scene.Meshes[0].BoundingBox.calculateBoxCenter(), scene.Meshes[0].BoundingBox.calculateBoxRadius() * 2, Input);

            rotCamera.CameraCenter   = rotCamera.CameraCenter + new TGCVector3(0, 50f, 0);
            rotCamera.CameraDistance = 300;
            rotCamera.RotationSpeed  = 50f;
            Camera = rotCamera;
        }
示例#26
0
        public void CrearEnvMapAgua()
        {
            // creo el enviroment map para el agua
            g_pCubeMapAgua = new CubeTexture(D3DDevice.Instance.Device, 256, 1, Usage.RenderTarget,
                                             Format.A16B16G16R16F, Pool.Default);
            var pOldRT = D3DDevice.Instance.Device.GetRenderTarget(0);

            // ojo: es fundamental que el fov sea de 90 grados.
            // asi que re-genero la matriz de proyeccion
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f), 1f, near_plane, far_plane).ToMatrix();
            // Genero las caras del enviroment map
            for (var nFace = CubeMapFace.PositiveX; nFace <= CubeMapFace.NegativeZ; ++nFace)
            {
                var pFace = g_pCubeMapAgua.GetCubeMapSurface(nFace, 0);
                D3DDevice.Instance.Device.SetRenderTarget(0, pFace);
                TGCVector3 Dir, VUP;
                Color      color;
                switch (nFace)
                {
                default:
                case CubeMapFace.PositiveX:
                    // Left
                    Dir   = new TGCVector3(1, 0, 0);
                    VUP   = TGCVector3.Up;
                    color = Color.Black;
                    break;

                case CubeMapFace.NegativeX:
                    // Right
                    Dir   = new TGCVector3(-1, 0, 0);
                    VUP   = TGCVector3.Up;
                    color = Color.Red;
                    break;

                case CubeMapFace.PositiveY:
                    // Up
                    Dir   = TGCVector3.Up;
                    VUP   = new TGCVector3(0, 0, -1);
                    color = Color.Gray;
                    break;

                case CubeMapFace.NegativeY:
                    // Down
                    Dir   = TGCVector3.Down;
                    VUP   = new TGCVector3(0, 0, 1);
                    color = Color.Yellow;
                    break;

                case CubeMapFace.PositiveZ:
                    // Front
                    Dir   = new TGCVector3(0, 0, 1);
                    VUP   = TGCVector3.Up;
                    color = Color.Green;
                    break;

                case CubeMapFace.NegativeZ:
                    // Back
                    Dir   = new TGCVector3(0, 0, -1);
                    VUP   = TGCVector3.Up;
                    color = Color.Blue;
                    break;
                }

                var Pos = piso.Position;
                if (nFace == CubeMapFace.NegativeY)
                {
                    Pos.Y += 2000;
                }

                D3DDevice.Instance.Device.Transform.View = TGCMatrix.LookAtLH(Pos, Pos + Dir, VUP).ToMatrix();
                D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, color, 1.0f, 0);
                D3DDevice.Instance.Device.BeginScene();
                //Renderizar: solo algunas cosas:
                if (nFace == CubeMapFace.NegativeY)
                {
                    //Renderizar terreno
                    terrain.render();
                }
                else
                {
                    //Renderizar SkyBox
                    skyBox.Render();
                    // dibujo el bosque
                    foreach (var instance in bosque)
                    {
                        instance.UpdateMeshTransform();
                        instance.Render();
                    }
                }
                var fname = string.Format("face{0:D}.bmp", nFace);
                //SurfaceLoader.Save(fname, ImageFileFormat.Bmp, pFace);

                D3DDevice.Instance.Device.EndScene();
            }
            // restuaro el render target
            D3DDevice.Instance.Device.SetRenderTarget(0, pOldRT);
        }
示例#27
0
        //public void Update(float[] eyePosition)
        //{
        //    effect.SetValue("fvEyePosition", eyePosition);
        //}

        public void Init(GameModel model, Device device)
        {
            this.d3dDevice = device;
            this.gameModel = model;

            #region configurarEfecto

            string compilationErrors;
            effect = Effect.FromFile(d3dDevice, GameModel.shadersDir + "PostProcess.fx",
                                     null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors);
            Console.WriteLine(compilationErrors);
            effect.Technique = "DefaultTechnique";
            #endregion

            depthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth,
                                                               d3dDevice.PresentationParameters.BackBufferHeight,
                                                               DepthFormat.D24S8, MultiSampleType.None, 0, true);

            #region inicializarRenderTargets
            renderTarget = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                                       , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                                       Format.X8R8G8B8, Pool.Default);

            renderTarget4 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth / 4
                                        , d3dDevice.PresentationParameters.BackBufferHeight / 4, 1, Usage.RenderTarget,
                                        Format.X8R8G8B8, Pool.Default);

            renderTargetGlow = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth / 4
                                           , d3dDevice.PresentationParameters.BackBufferHeight / 4, 1, Usage.RenderTarget,
                                           Format.X8R8G8B8, Pool.Default);
            #endregion

            #region setEffectValues
            effect.SetValue("g_RenderTarget", renderTarget);
            // Resolucion de pantalla
            effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth);
            effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight);
            #endregion

            #region inicializarVertexBuffer
            //Creamos un FullScreen Quad
            CustomVertex.PositionTextured[] vertices =
            {
                new CustomVertex.PositionTextured(-1,  1, 1, 0, 0),
                new CustomVertex.PositionTextured(1,   1, 1, 1, 0),
                new CustomVertex.PositionTextured(-1, -1, 1, 0, 1),
                new CustomVertex.PositionTextured(1,  -1, 1, 1, 1)
            };
            //vertex buffer de los triangulos
            vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionTextured),
                                            4, d3dDevice, Usage.Dynamic | Usage.WriteOnly,
                                            CustomVertex.PositionTextured.Format, Pool.Default);
            vertexBuffer.SetData(vertices, 0, LockFlags.None);
            #endregion

            #region shadowMap
            shadowTex   = new Texture(D3DDevice.Instance.Device, SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, Usage.RenderTarget, Format.R32F, Pool.Default);
            stencilBuff = D3DDevice.Instance.Device.CreateDepthStencilSurface(SHADOWMAP_SIZE, SHADOWMAP_SIZE, DepthFormat.D24S8, MultiSampleType.None, 0, true);

            var aspectRatio = D3DDevice.Instance.AspectRatio;
            projMatrix = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(80), aspectRatio, 50, 5000);
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, near_plane, far_plane).ToMatrix();
            #endregion

            #region light
            lightPos = new TGCVector3(760, 520, 60);
            lightDir = TGCVector3.Empty - lightPos;
            lightDir.Normalize();
            lightView = TGCMatrix.LookAtLH(lightPos, lightPos + lightDir, new TGCVector3(0, 0, 1));
            #endregion
        }
        public override void Update()
        {
            // 1) Crear una matriz de transformacion (de 4x4 para 3D) con la identidad
            var m = TGCMatrix.Identity;

            // 2) Crear una matriz de transformacion para traslacion
            var translate = TGCMatrix.Translation(new TGCVector3(100, -5, 0));

            // 3) Crear una matriz de escalado para traslacion
            var scale = TGCMatrix.Scaling(new TGCVector3(2, 4, 2));

            // 4) Crear una matriz de rotacion para traslacion
            var angleY   = FastMath.PI_HALF;                                       //En radianes
            var angleX   = FastMath.ToRad(60);                                     //De grados a radianes
            var angleZ   = FastMath.PI / 14;
            var rotation = TGCMatrix.RotationYawPitchRoll(angleY, angleX, angleZ); //Ojo con el orden de los angulos

            // 5) Combinar varias matrices en una sola. El orden depende del movimiento que se quiera lograr
            var movimientoFinal = scale * rotation * translate;

            // 6) Transformar un punto en base al movimiento de una matriz de transformacion
            var p = new TGCVector3(10, 5, 10);
            var transformedVec4 = TGCVector3.Transform(p, movimientoFinal);
            //Devuelve un TGCVector4 poque estan las coordenadas homogeneas
            var transformedVec3 = new TGCVector3(transformedVec4.X, transformedVec4.Y, transformedVec4.Z);

            //Ignoramos la componente W

            // 7) Setear la matriz de World de DirectX
            D3DDevice.Instance.Device.Transform.World = movimientoFinal.ToMatrix();

            // 8) Crear una matriz de View mirando hacia un determinado punto y aplicarla a DirectX
            var posicionCamara = new TGCVector3(20, 10, 0);
            var haciaDondeMiro = TGCVector3.Empty;
            var upVector       = TGCVector3.Up; //Indica donde es arriba y donde abajo
            var viewMatrix     = TGCMatrix.LookAtLH(posicionCamara, haciaDondeMiro, upVector);

            D3DDevice.Instance.Device.Transform.View = viewMatrix.ToMatrix();

            // 9) Crear una matriz de proyeccion y aplicarla en DirectX
            var fieldOfViewY       = FastMath.ToRad(45.0f);
            var aspectRatio        = D3DDevice.Instance.AspectRatio;
            var zNearPlaneDistance = 1f;
            var zFarPlaneDistance  = 10000f;
            var projection         = TGCMatrix.PerspectiveFovLH(fieldOfViewY, aspectRatio, zNearPlaneDistance, zFarPlaneDistance);

            D3DDevice.Instance.Device.Transform.Projection = projection.ToMatrix();

            // 10) Proyectar manualmente un punto 3D a la pantalla (lo que normalmente se hace dentro del vertex shader)
            var q             = new TGCVector3(100, -15, 2);
            var worldViewProj = D3DDevice.Instance.Device.Transform.World * D3DDevice.Instance.Device.Transform.View *
                                D3DDevice.Instance.Device.Transform.Projection;
            //Obtener la matriz final
            var projectedPoint = TGCVector3.Transform(q, TGCMatrix.FromMatrix(worldViewProj)); //Proyectar

            //Dividir por w
            projectedPoint.X /= projectedPoint.W;
            projectedPoint.Y /= projectedPoint.W;
            projectedPoint.Z /= projectedPoint.W; //La z solo es necesaria si queremos hacer Depth-testing
            //Pasarlo a screen-space
            var screenPoint = new Point(
                (int)(0.5f + (p.X + 1) * 0.5f * D3DDevice.Instance.Device.Viewport.Width),
                (int)(0.5f + (1 - p.Y) * 0.5f * D3DDevice.Instance.Device.Viewport.Height));

            // 11) Con vertir de un punto 2D a uno 3D, al revez de lo que se hizo antes (normalmente para hacer picking con el mouse)
            var screenPoint2 = new Point(15, 100); //punto 2D de la pantalla
            var vAux         = TGCVector3.Empty;

            vAux.X = (2.0f * screenPoint2.X / D3DDevice.Instance.Device.Viewport.Width - 1) /
                     D3DDevice.Instance.Device.Transform.Projection.M11;
            vAux.Y = -(2.0f * screenPoint2.Y / D3DDevice.Instance.Device.Viewport.Height - 1) /
                     D3DDevice.Instance.Device.Transform.Projection.M22;
            vAux.Z = 1.0f;
            var inverseView = TGCMatrix.Invert(TGCMatrix.FromMatrix(D3DDevice.Instance.Device.Transform.View)); //Invertir ViewMatrix
            var origin      = new TGCVector3(inverseView.M41, inverseView.M42, inverseView.M43);
            var direction   = new TGCVector3(
                vAux.X * inverseView.M11 + vAux.Y * inverseView.M21 + vAux.Z * inverseView.M31,
                vAux.X * inverseView.M12 + vAux.Y * inverseView.M22 + vAux.Z * inverseView.M32,
                vAux.X * inverseView.M13 + vAux.Y * inverseView.M23 + vAux.Z * inverseView.M33);
            //Con origin y direction formamos una recta que hay que buscar interseccion contra todos los objetos del escenario y quedarnos con la mas cercana a la camara
        }
示例#29
0
        public override void Init()
        {
            //Crear loader
            var loader = new TgcSceneLoader();

            // ------------------------------------------------------------
            // Creo el Heightmap para el terreno:
            terrain = new MySimpleTerrain();
            terrain.loadHeightmap(MediaDir + "Heighmaps\\Heightmap3.jpg", 100f, 1f,
                                  TGCVector3.Empty);
            terrain.loadTexture(MediaDir + "Heighmaps\\TerrainTexture3.jpg");

            // ------------------------------------------------------------
            // Crear SkyBox:
            skyBox        = new TgcSkyBox();
            skyBox.Center = TGCVector3.Empty;
            skyBox.Size   = new TGCVector3(8000, 8000, 8000);
            var texturesPath = MediaDir + "Texturas\\Quake\\SkyBox1\\";

            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "phobos_up.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "phobos_dn.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "phobos_lf.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "phobos_rt.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "phobos_bk.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "phobos_ft.jpg");
            skyBox.SkyEpsilon = 50f;
            skyBox.Init();

            // ------------------------------------------------------------
            //Cargar los mesh:
            scene =
                loader.loadSceneFromFile(MediaDir +
                                         "MeshCreator\\Meshes\\Vehiculos\\TanqueFuturistaRuedas\\TanqueFuturistaRuedas-TgcScene.xml");
            mesh = scene.Meshes[0];

            scene2 =
                loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera\\Palmera-TgcScene.xml");
            palmera = scene2.Meshes[0];

            scene3 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\Canoa\\Canoa-TgcScene.xml");
            canoa  = scene3.Meshes[0];

            scene4 = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Piso\\Agua-TgcScene.xml");
            piso   = scene4.Meshes[0];

            mesh.Scale    = new TGCVector3(0.5f, 0.5f, 0.5f);
            mesh.Position = new TGCVector3(0f, 0f, 0f);
            var size = mesh.BoundingBox.calculateSize();

            largo_tanque   = Math.Abs(size.Z);
            alto_tanque    = Math.Abs(size.Y) * mesh.Scale.Y;
            vel_tanque     = 10;
            an_tanque      = 0;
            canoa.Scale    = new TGCVector3(1f, 1f, 1f);
            canoa.Position = new TGCVector3(3000f, 550f, 0f);
            dir_canoa      = new TGCVector3(0, 0, 1);
            nivel_mar      = 135f;
            piso.Scale     = new TGCVector3(25f, 1f, 25f);
            piso.Position  = new TGCVector3(0f, nivel_mar, 0f);

            size = palmera.BoundingBox.calculateSize();
            var alto_palmera = Math.Abs(size.Y);

            cant_palmeras = 0;
            int i;

            bosque = new List <TgcMesh>();
            float[] r = { 1850f, 2100f, 2300f, 1800f };
            for (i = 0; i < 4; i++)
            {
                for (var j = 0; j < 15; j++)
                {
                    var instance = palmera.createMeshInstance(palmera.Name + i);
                    instance.Scale = new TGCVector3(0.5f, 1.5f, 0.5f);
                    var x = r[i] * (float)Math.Cos(Geometry.DegreeToRadian(100 + 10.0f * j));
                    var z = r[i] * (float)Math.Sin(Geometry.DegreeToRadian(100 + 10.0f * j));
                    instance.Position = new TGCVector3(x, terrain.CalcularAltura(x, z)
                                                       /*+ alto_palmera / 2 * instance.Scale.Y*/, z);
                    bosque.Add(instance);
                    ++cant_palmeras;
                }
            }

            // segunda parte: la isla del medio
            // estas no entran en el env. map (porque se supone que el env. map esta lejos
            // del pto de vista del observador y estas palmeras estan en el medio del lago)
            float[] r2 = { 200f, 350f, 400f, 477f };
            for (i = 0; i < 4; i++)
            {
                for (var j = 0; j < 5; j++)
                {
                    var instance = palmera.createMeshInstance(palmera.Name + i);
                    instance.Scale = new TGCVector3(0.5f, 1f + j / 5f * 0.33f, 0.5f);
                    var x = r2[i] * (float)Math.Cos(Geometry.DegreeToRadian(25.0f * j));
                    var z = r2[i] * (float)Math.Sin(Geometry.DegreeToRadian(25.0f * j));
                    instance.Position = new TGCVector3(x, terrain.CalcularAltura(x, z)
                                                       /*+ alto_palmera / 2 * instance.Scale.Y*/, z);
                    bosque.Add(instance);
                }
            }

            // Arreglo las normales del tanque

            /*int[] adj = new int[mesh.D3dMesh.NumberFaces * 3];
             * mesh.D3dMesh.GenerateAdjacency(0, adj);
             * mesh.D3dMesh.ComputeNormals(adj);
             */

            g_pCubeMapAgua = null;

            //Cargar Shader personalizado
            effect =
                TGCShaders.Instance.LoadEffect(ShadersDir + "WorkshopShaders\\Demo.fx");

            // le asigno el efecto a las mallas
            mesh.Effect       = effect;
            mesh.Technique    = "RenderScene";
            piso.Effect       = effect;
            piso.Technique    = "RenderScene";
            palmera.Effect    = effect;
            palmera.Technique = "RenderScene";
            canoa.Effect      = effect;
            canoa.Technique   = "RenderScene";

            //--------------------------------------------------------------------------------------
            // Creo el shadowmap.
            // Format.R32F
            // Format.X8R8G8B8
            g_pShadowMap = new Texture(D3DDevice.Instance.Device, SHADOWMAP_SIZE, SHADOWMAP_SIZE,
                                       1, Usage.RenderTarget, Format.R32F,
                                       Pool.Default);

            // tengo que crear un stencilbuffer para el shadowmap manualmente
            // para asegurarme que tenga la el mismo tamano que el shadowmap, y que no tenga
            // multisample, etc etc.
            g_pDSShadow = D3DDevice.Instance.Device.CreateDepthStencilSurface(SHADOWMAP_SIZE,
                                                                              SHADOWMAP_SIZE,
                                                                              DepthFormat.D24S8,
                                                                              MultiSampleType.None,
                                                                              0,
                                                                              true);
            // por ultimo necesito una matriz de proyeccion para el shadowmap, ya
            // que voy a dibujar desde el pto de vista de la luz.
            // El angulo tiene que ser mayor a 45 para que la sombra no falle en los extremos del cono de luz
            // de hecho, un valor mayor a 90 todavia es mejor, porque hasta con 90 grados es muy dificil
            // lograr que los objetos del borde generen sombras
            var aspectRatio = D3DDevice.Instance.AspectRatio;

            g_mShadowProj = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(130.0f), aspectRatio, near_plane, far_plane);
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, near_plane, far_plane).ToMatrix();

            alfa_sol = 1.7f;
            //alfa_sol = 0;

            //--------------------------------------------------------------------------------------
            //Centrar camara rotacional respecto a este mesh
            camara_rot = false;
            CamaraRot  = new TgcRotationalCamera(mesh.BoundingBox.calculateBoxCenter(),
                                                 mesh.BoundingBox.calculateBoxRadius() * 2, Input);
            CamaraRot.CameraDistance = 300;
            CamaraRot.RotationSpeed  = 1.5f;
            DefaultCamera            = new TgcRotationalCamera(new TGCVector3(0, 200, 0), 5000, 0.1f, 1f, Input);
            Camara = DefaultCamera;

            LookFrom = new TGCVector3(0, 400, 2000);
            LookAt   = new TGCVector3(0, 200, 0);

            // inicio unos segundos de preview
            timer_preview = 50;

            arrow           = new TgcArrow();
            arrow.Thickness = 1f;
            arrow.HeadSize  = new TGCVector2(2f, 2f);
            arrow.BodyColor = Color.Blue;

            ant_vista    = tipo_vista = 0;
            View1        = new Viewport();
            View1.X      = 0;
            View1.Y      = 0;
            View1.Width  = D3DDevice.Instance.Width;
            View1.Height = D3DDevice.Instance.Height / 2;
            View1.MinZ   = 0;
            View1.MaxZ   = 1;
            View2        = new Viewport();
            View2.X      = 0;
            View2.Y      = View1.Height;
            View2.Width  = D3DDevice.Instance.Width;
            View2.Height = D3DDevice.Instance.Height / 2;
            View2.MinZ   = 0;
            View2.MaxZ   = 1;

            ViewF = D3DDevice.Instance.Device.Viewport;
        }
        public void Render(AutoManejable AutoFisico1, AutoManejable AutoFisico2, PoliciasIA GrupoPolicias, Core.Camara.TgcCamera Camara, bool juegoDoble)
        {
            //  Shader Enviroment Map --------------------------------
            //D3DDevice.Instance.Device.EndScene();
            var g_pCubeMap = new CubeTexture(D3DDevice.Instance.Device, 256, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);
            var pOldRT2    = D3DDevice.Instance.Device.GetRenderTarget(0);

            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f), 1f, 1f, 10000f).ToMatrix();

            // Genero las caras del enviroment map
            for (var nFace = CubeMapFace.PositiveX; nFace <= CubeMapFace.NegativeZ; ++nFace)
            {
                var pFace = g_pCubeMap.GetCubeMapSurface(nFace, 0);
                D3DDevice.Instance.Device.SetRenderTarget(0, pFace);
                TGCVector3 Dir, VUP;
                Color      color;
                switch (nFace)
                {
                default:
                case CubeMapFace.PositiveX:
                    // Left
                    Dir   = new TGCVector3(1, 0, 0);
                    VUP   = TGCVector3.Up;
                    color = Color.Black;
                    break;

                case CubeMapFace.NegativeX:
                    // Right
                    Dir   = new TGCVector3(-1, 0, 0);
                    VUP   = TGCVector3.Up;
                    color = Color.Red;
                    break;

                case CubeMapFace.PositiveY:
                    // Up
                    Dir   = TGCVector3.Up;
                    VUP   = new TGCVector3(0, 0, -1);
                    color = Color.Gray;
                    break;

                case CubeMapFace.NegativeY:
                    // Down
                    Dir   = TGCVector3.Down;
                    VUP   = new TGCVector3(0, 0, 1);
                    color = Color.Yellow;
                    break;

                case CubeMapFace.PositiveZ:
                    // Front
                    Dir   = new TGCVector3(0, 0, 1);
                    VUP   = TGCVector3.Up;
                    color = Color.Green;
                    break;

                case CubeMapFace.NegativeZ:
                    // Back
                    Dir   = new TGCVector3(0, 0, -1);
                    VUP   = TGCVector3.Up;
                    color = Color.Blue;
                    break;
                }

                D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, color, 1.0f, 0);
                //Renderizar

                foreach (var mesh in AutoFisico1.Mayas)
                {
                    mesh.Effect    = EnvMap;
                    mesh.Technique = "RenderScene";
                    mesh.Render();
                }
                if (juegoDoble)
                {
                    foreach (var mesh in AutoFisico2.Mayas)
                    {
                        mesh.Effect    = EnvMap;
                        mesh.Technique = "RenderScene";
                        mesh.Render();
                    }
                }
            }

            D3DDevice.Instance.Device.SetRenderTarget(0, pOldRT2);
            D3DDevice.Instance.Device.Transform.View       = Camara.GetViewMatrix().ToMatrix();
            D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), D3DDevice.Instance.AspectRatio, 1f, 10000f).ToMatrix();

            //D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            EnvMap.SetValue("g_txCubeMap", g_pCubeMap);

            foreach (var mesh in AutoFisico1.Mayas)
            {
                mesh.Effect    = EnvMap;
                mesh.Technique = "RenderScene";
                mesh.Render();
            }
            foreach (var rueda in AutoFisico1.Ruedas)
            {
                rueda.Effect    = EnvMap;
                rueda.Technique = "RenderScene";
                rueda.Render();
            }
            foreach (var mesh in GrupoPolicias.Todos[0].Mayas)
            {
                mesh.Effect    = EnvMap;
                mesh.Technique = "RenderScene";
                mesh.Render();
            }
            if (juegoDoble)
            {
                foreach (var mesh in AutoFisico2.Mayas)
                {
                    mesh.Effect    = EnvMap;
                    mesh.Technique = "RenderScene";
                    mesh.Render();
                }
                foreach (var rueda in AutoFisico2.Ruedas)
                {
                    rueda.Effect    = EnvMap;
                    rueda.Technique = "RenderScene";
                    rueda.Render();
                }
            }
            g_pCubeMap.Dispose();
            //-------------------------------------------------------------
        }