public override void Update() { PreUpdate(); Device d3dDevice = D3DDevice.Instance.Device; // Actualizo la direccion if (Input.keyDown(Microsoft.DirectX.DirectInput.Key.A)) { dir_an += 1f * ElapsedTime; } if (Input.keyDown(Microsoft.DirectX.DirectInput.Key.D)) { dir_an -= 1f * ElapsedTime; } // calculo la velocidad TGCVector2 vel = new TGCVector2((float)Math.Sin(dir_an), (float)Math.Cos(dir_an)); // actualizo la posicion pos += vel * kvel * ElapsedTime; // actualizo los parametros de la camara float dH = 2.0f; // altura del personaje float H = terrain.CalcularAltura(pos.X, pos.Y); TGCVector2 pos_s = pos + vel * 2; TGCVector3 lookFrom = new TGCVector3(pos.X, H + dH, pos.Y); TGCVector3 lookAt = new TGCVector3(pos_s.X, H + 1.5f, pos_s.Y); d3dDevice.Transform.View = TGCMatrix.LookAtLH(lookFrom, lookAt, TGCVector3.Up); effect.SetValue("fvEyePosition", TGCVector3.Vector3ToFloat3Array(lookFrom)); }
private TGCMatrix LookAtFromCubeMapFace(CubeMapFace face, TGCVector3 position) { switch (face) { case CubeMapFace.PositiveX: return(TGCMatrix.LookAtLH(position, position + new TGCVector3(1f, 0f, 0f), TGCVector3.Up)); case CubeMapFace.PositiveZ: return(TGCMatrix.LookAtLH(position, position + new TGCVector3(0f, 0f, 1f), TGCVector3.Up)); case CubeMapFace.PositiveY: return(TGCMatrix.LookAtLH(position, position + TGCVector3.Up, new TGCVector3(0f, 0f, -1f))); case CubeMapFace.NegativeX: return(TGCMatrix.LookAtLH(position, position + new TGCVector3(-1f, 0f, 0f), TGCVector3.Up)); case CubeMapFace.NegativeZ: return(TGCMatrix.LookAtLH(position, position + new TGCVector3(0f, 0f, -1f), TGCVector3.Up)); case CubeMapFace.NegativeY: return(TGCMatrix.LookAtLH(position, position + -TGCVector3.Up, new TGCVector3(0f, 0f, 1f))); default: throw new Exception("Invalid cubemap face"); } }
public void Update(float elapsedTime, TgcD3dInput input) { //Forward if (input.keyDown(Key.W)) { moveForward(MovementSpeed * elapsedTime); } //Backward if (input.keyDown(Key.S)) { moveForward(-MovementSpeed * elapsedTime); } //Strafe right if (input.keyDown(Key.D)) { moveSide(MovementSpeed * elapsedTime); } //Strafe left if (input.keyDown(Key.A)) { moveSide(-MovementSpeed * elapsedTime); } //Jump if (input.keyDown(Key.Space)) { moveUp(JumpSpeed * elapsedTime); } //Crouch if (input.keyDown(Key.LeftControl)) { moveUp(-JumpSpeed * elapsedTime); } if (input.keyPressed(Key.L)) { LockCam = !LockCam; } //Solo rotar si se esta aprentando el boton izq del mouse if (lockCam || input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT)) { rotate(-input.XposRelative * RotationSpeed, -input.YposRelative * RotationSpeed); } if (lockCam) { Cursor.Position = mouseCenter; } viewMatrix = TGCMatrix.LookAtLH(eye, target, up); updateViewMatrix(D3DDevice.Instance.Device); }
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 void RenderShadowMap() { var effect = TgcShaders.Instance.TgcMeshPointLightShader; // Calculo la matriz de view de la luz effect.SetValue("g_vLightPos", new Vector4(g_LightPos.X, g_LightPos.Y, g_LightPos.Z, 1)); effect.SetValue("g_vLightDir", new Vector4(g_LightDir.X, g_LightDir.Y, g_LightDir.Z, 1)); g_LightView = TGCMatrix.LookAtLH(g_LightPos, g_LightPos + g_LightDir, new TGCVector3(0, 0, 1)); // inicializacion standard: effect.SetValue("g_mProjLight", g_mShadowProj.ToMatrix()); effect.SetValue("g_mViewLightProj", (g_LightView * g_mShadowProj).ToMatrix()); // Primero genero el shadow map, para ello dibujo desde el pto de vista de luz // a una textura, con el VS y PS que generan un mapa de profundidades. var pOldRT = D3DDevice.Instance.Device.GetRenderTarget(0); var pShadowSurf = g_pShadowMap.GetSurfaceLevel(0); D3DDevice.Instance.Device.SetRenderTarget(0, pShadowSurf); var pOldDS = D3DDevice.Instance.Device.DepthStencilSurface; D3DDevice.Instance.Device.DepthStencilSurface = g_pDSShadow; D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); D3DDevice.Instance.Device.BeginScene(); // Hago el render de la escena pp dicha effect.SetValue("g_txShadow", g_pShadowMap); navePrincipal.ActionOnNave(m => m.Technique = "RenderShadow"); navePrincipal.Render(sol.Position, Camara.Position); if (spawnaearEnemigos) { enemigos.FindAll(enemigo => enemigo.EstaViva() && enemigo.EnemigoEstaAdelante()).ForEach(e => e.Scene.Meshes.ForEach(m => m.Technique = "RenderShadow")); enemigos.FindAll(enemigo => enemigo.EstaViva() && enemigo.EnemigoEstaAdelante()).ForEach(e => e.Render(sol.Position, Camara.Position)); } escenarios.ForEach(es => es.Scene.Meshes.ForEach(m => m.Technique = "RenderShadow")); escenarios.ForEach(es => es.torres.ForEach(t => t.Scene.Meshes.ForEach(m => m.Technique = "RenderShadow"))); escenarios.ForEach(es => es.Render(sol.Position, Camara.Position, ElapsedTime)); // Termino D3DDevice.Instance.Device.EndScene(); if (save) { TextureLoader.Save("shadowmap.jpg", ImageFileFormat.Jpg, g_pShadowMap); save = false; } // restuaro el render target y el stencil D3DDevice.Instance.Device.DepthStencilSurface = pOldDS; D3DDevice.Instance.Device.SetRenderTarget(0, pOldRT); }
private void RenderShaders()// x ahora solo shadowmap { // Calculo la matriz de view de la luz if (VariablesGlobales.DameLuz) { lightPos = VariablesGlobales.camara.GetPositionAtDistance(-10);//VariablesGlobales.xwing.GetPosition(); lightDir = VariablesGlobales.xwing.GetCoordenadaEsferica().GetXYZCoord(); shader.SetValue("g_vLightPos", new Vector4(lightPos.X, lightPos.Y, lightPos.Z, 1)); shader.SetValue("g_vLightDir", new Vector4(lightDir.X, lightDir.Y, lightDir.Z, 1)); lightView = TGCMatrix.LookAtLH(lightPos, lightPos + lightDir, new TGCVector3(0, 0, 1)); } else { lightPos.Y = VariablesGlobales.xwing.GetPosition().Y + 50; lightPos.Z = VariablesGlobales.xwing.GetPosition().Z; shader.SetValue("g_vLightPos", new Vector4(lightPos.X, lightPos.Y, lightPos.Z, 1)); lightDir = VariablesGlobales.xwing.GetPosition() - lightPos; lightDir.Normalize(); shader.SetValue("g_vLightDir", new Vector4(lightDir.X, lightDir.Y, lightDir.Z, 1)); lightView = TGCMatrix.LookAtLH(lightPos, lightPos + lightDir, new TGCVector3(0, 0, 1)); } //@@@@xq está el up vector en la z?? //@@@@@@@@Probar solo renderizar en el shadow al xwing, y dsps poner al piso como render scene // inicializacion standard: shader.SetValue("g_mProjLight", shadowProj.ToMatrix()); shader.SetValue("g_mViewLightProj", (lightView * shadowProj).ToMatrix()); // Primero genero el shadow map, para ello dibujo desde el pto de vista de luz // a una textura, con el VS y PS que generan un mapa de profundidades. var pShadowSurf = shadow_map.GetSurfaceLevel(0); D3DDevice.Instance.Device.SetRenderTarget(0, pShadowSurf); D3DDevice.Instance.Device.DepthStencilSurface = shadow_depth; D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); // Hago el render de la escena pp dicha shader.SetValue("g_txShadow", shadow_map);//deja la textura seteada pa q se use dsps en el render normal D3DDevice.Instance.Device.BeginScene(); //necesito un metodo q todos puedan pasar su mesh y q el postprocess les ponga la technique shaderManager.SetTechnique("RenderShadow", ShaderManager.MESH_TYPE.SHADOW); shaderManager.RenderMesh(ShaderManager.MESH_TYPE.SHADOW); // Termino D3DDevice.Instance.Device.EndScene(); //TextureLoader.Save(variablesGlobales.shadersDir+"shadowmap.bmp", ImageFileFormat.Bmp, shadow_map); }
public void RenderShadowMap() { //Doy posicion a la luz // Calculo la matriz de view de la luz effect.SetValue("g_vLightPos", new Vector4(g_LightPos.X, g_LightPos.Y, g_LightPos.Z, 1)); effect.SetValue("g_vLightDir", new Vector4(g_LightDir.X, g_LightDir.Y, g_LightDir.Z, 1)); g_LightView = TGCMatrix.LookAtLH(g_LightPos, g_LightPos + g_LightDir, new TGCVector3(0, 0, 1)); // inicializacion standard: effect.SetValue("g_mProjLight", g_mShadowProj.ToMatrix()); effect.SetValue("g_mViewLightProj", (g_LightView * g_mShadowProj).ToMatrix()); // Primero genero el shadow map, para ello dibujo desde el pto de vista de luz // a una textura, con el VS y PS que generan un mapa de profundidades. var pOldRT = D3DDevice.Instance.Device.GetRenderTarget(0); var pShadowSurf = g_pShadowMap.GetSurfaceLevel(0); D3DDevice.Instance.Device.SetRenderTarget(0, pShadowSurf); var pOldDS = D3DDevice.Instance.Device.DepthStencilSurface; D3DDevice.Instance.Device.DepthStencilSurface = g_pDSShadow; D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.White, 1.0f, 0); D3DDevice.Instance.Device.BeginScene(); // Hago el render de la escena pp dicha // solo los objetos que proyectan sombras: //Renderizar terreno terrain.executeRender(effect); // dibujo el bosque foreach (var instance in bosque) { instance.UpdateMeshTransform(); instance.Render(); } // el tanque // Seteo la tecnica: estoy generando la sombra o estoy dibujando la escena mesh.Technique = "RenderShadow"; mesh.Render(); // Termino D3DDevice.Instance.Device.EndScene(); //TextureLoader.Save("shadowmap.bmp", ImageFileFormat.Bmp, g_pShadowMap); // restuaro el render target y el stencil D3DDevice.Instance.Device.DepthStencilSurface = pOldDS; D3DDevice.Instance.Device.SetRenderTarget(0, pOldRT); effect.SetValue("g_txShadow", g_pShadowMap); }
/// <summary> /// Asigna target con offsets. /// </summary> public void setTargetOffset(TGCVector3 target, float offsetY, float offsetZ) { Eye = new TGCVector3(target.X, target.Y + offsetY, target.Z + offsetZ); Target = target; m_viewMatrix = TGCMatrix.LookAtLH(Eye, Target, m_targetYAxis); m_orientation = TGCQuaternion.RotationMatrix(m_viewMatrix); var offset = Target - Eye; m_offsetDistance = offset.Length(); m_headingDegrees = 0.0f; m_pitchDegrees = 0.0f; }
public void RenderShadowMap() { // Calculo la matriz de view de la luz shadowEffect.SetValue("g_vLightPos", new Vector4(g_LightPos.X, g_LightPos.Y, g_LightPos.Z, 1)); shadowEffect.SetValue("g_vLightDir", new Vector4(g_LightDir.X, g_LightDir.Y, g_LightDir.Z, 1)); skeletalShadowEffect.SetValue("g_vLightPos", new Vector4(g_LightPos.X, g_LightPos.Y, g_LightPos.Z, 1)); skeletalShadowEffect.SetValue("g_vLightDir", new Vector4(g_LightDir.X, g_LightDir.Y, g_LightDir.Z, 1)); g_LightView = TGCMatrix.LookAtLH(g_LightPos, g_LightPos + g_LightDir, new TGCVector3(0, 0, 1)); // inicializacion standard: shadowEffect.SetValue("g_mProjLight", g_mShadowProj.ToMatrix()); shadowEffect.SetValue("g_mViewLightProj", (g_LightView * g_mShadowProj).ToMatrix()); skeletalShadowEffect.SetValue("g_mProjLight", g_mShadowProj.ToMatrix()); skeletalShadowEffect.SetValue("g_mViewLightProj", (g_LightView * g_mShadowProj).ToMatrix()); // Primero genero el shadow map, para ello dibujo desde el pto de vista de luz // a una textura, con el VS y PS que generan un mapa de profundidades. var pOldRT = D3DDevice.Instance.Device.GetRenderTarget(0); var pShadowSurf = g_pShadowMap.GetSurfaceLevel(0); D3DDevice.Instance.Device.SetRenderTarget(0, pShadowSurf); var pOldDS = D3DDevice.Instance.Device.DepthStencilSurface; D3DDevice.Instance.Device.DepthStencilSurface = shadowDepthStencil; D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); D3DDevice.Instance.Device.BeginScene(); // Hago el render de la escena pp dicha shadowEffect.SetValue("g_txShadow", g_pShadowMap); skeletalShadowEffect.SetValue("g_txShadow", g_pShadowMap); // RENDER doingShadowRender = true; RenderScene(); // Termino D3DDevice.Instance.Device.EndScene(); //TextureLoader.Save("shadowmap.bmp", ImageFileFormat.Bmp, g_pShadowMap); // restuaro el render target y el stencil D3DDevice.Instance.Device.DepthStencilSurface = pOldDS; D3DDevice.Instance.Device.SetRenderTarget(0, pOldRT); }
public void RenderShadowMap() { // Calculo la matriz de view de la luz effect.SetValue("g_vLightPos", new TGCVector4(g_LightPos.X, g_LightPos.Y, g_LightPos.Z, 1)); effect.SetValue("g_vLightDir", new TGCVector4(g_LightDir.X, g_LightDir.Y, g_LightDir.Z, 1)); g_LightView = TGCMatrix.LookAtLH(g_LightPos, g_LightPos + g_LightDir, new TGCVector3(0, 0, 1)); arrow.PStart = g_LightPos; arrow.PEnd = g_LightPos + g_LightDir * 20f; arrow.updateValues(); // inicializacion standard: effect.SetValue("g_mProjLight", g_mShadowProj.ToMatrix()); effect.SetValue("g_mViewLightProj", (g_LightView * g_mShadowProj).ToMatrix()); //frustumShadow.updateVolume(TGCMatrix.FromMatrix(D3DDevice.Instance.Device.Transform.View), // TGCMatrix.FromMatrix(D3DDevice.Instance.Device.Transform.Projection)); // Primero genero el shadow map, para ello dibujo desde el pto de vista de luz // a una textura, con el VS y PS que generan un mapa de profundidades. var pOldRT = D3DDevice.Instance.Device.GetRenderTarget(0); var pShadowSurf = g_pShadowMap.GetSurfaceLevel(0); D3DDevice.Instance.Device.SetRenderTarget(0, pShadowSurf); var pOldDS = D3DDevice.Instance.Device.DepthStencilSurface; D3DDevice.Instance.Device.DepthStencilSurface = g_pDSShadow; D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Gray, 1.0f, 0); //D3DDevice.Instance.Device.BeginScene(); // Hago el render de la escena pp dicha effect.SetValue("g_txShadow", g_pShadowMap); //RenderScene(true,g_LightView, g_mShadowProj); RenderScene2(true); //Termino //D3DDevice.Instance.Device.EndScene(); TextureLoader.Save("shadowmap.bmp", ImageFileFormat.Bmp, g_pShadowMap); // restuaro el render target y el stencil D3DDevice.Instance.Device.DepthStencilSurface = pOldDS; D3DDevice.Instance.Device.SetRenderTarget(0, pOldRT); }
public unsafe override void Render() { Device device = GuiController.Instance.D3dDevice; time += ElapsedTime; TgcD3dInput d3dInput = GuiController.Instance.D3dInput; //Obtener variacion XY del mouse if (d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT)) { float mouseX = d3dInput.XposRelative; float mouseY = d3dInput.YposRelative; float an = mouseX * 0.1f; float x = (float)(LookFrom.X * Math.Cos(an) + LookFrom.Z * Math.Sin(an)); float z = (float)(LookFrom.Z * Math.Cos(an) - LookFrom.X * Math.Sin(an)); LookFrom.X = x; LookFrom.Z = z; LookFrom.Y += mouseY * 150f; } //Determinar distancia de la camara o zoom segun el Mouse Wheel if (d3dInput.WheelPos != 0) { TGCVector3 vdir = LookFrom - LookAt; vdir.Normalize(); LookFrom = LookFrom - vdir * (d3dInput.WheelPos * 500); } device.Transform.View = TGCMatrix.LookAtLH(LookFrom, LookAt, new TGCVector3(0, 1, 0)); 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; device.SetRenderState(RenderStates.AlphaBlendEnable, false); // rt1= velocidad Surface pOldRT = device.GetRenderTarget(0); Surface pSurf = g_pVelocidadOut.GetSurfaceLevel(0); device.SetRenderTarget(0, pSurf); Surface pOldDS = device.DepthStencilSurface; device.DepthStencilSurface = g_pDepthStencil; // rt2 = posicion Surface pSurf2 = g_pPosOut.GetSurfaceLevel(0); device.SetRenderTarget(1, pSurf2); device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); device.BeginScene(); effect.SetValue("elapsedTime", ElapsedTime); effect.Technique = "ComputeVel"; effect.SetValue("g_pVelocidad", g_pVelocidad); effect.SetValue("g_pPos", g_pPos); device.VertexFormat = CustomVertex.PositionTextured.Format; device.SetStreamSource(0, g_pVBV3D, 0); effect.Begin(FX.None); effect.BeginPass(1); device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); effect.EndPass(); effect.End(); device.EndScene(); // leo los datos de la textura de velocidades // ---------------------------------------------------------------------- Surface pDestSurf = g_pTempVel.GetSurfaceLevel(0); device.GetRenderTargetData(pSurf, pDestSurf); Surface pDestSurf2 = g_pTempPos.GetSurfaceLevel(0); device.GetRenderTargetData(pSurf2, pDestSurf2); float *pDataVel = (float *)pDestSurf.LockRectangle(LockFlags.None).InternalData.ToPointer(); float *pDataPos = (float *)pDestSurf2.LockRectangle(LockFlags.None).InternalData.ToPointer(); for (int i = 0; i < MAX_DS; i++) { for (int j = 0; j < MAX_DS; j++) { vel_x[i, j] = *pDataVel++; vel_z[i, j] = *pDataVel++; pDataVel++; // no usado pDataVel++; // no usado pos_x[i, j] = *pDataPos++; pos_z[i, j] = *pDataPos++; pos_y[i, j] = *pDataPos++; pDataPos++; // no usado } } pDestSurf.UnlockRectangle(); pDestSurf2.UnlockRectangle(); pSurf.Dispose(); pSurf2.Dispose(); device.SetRenderTarget(0, pOldRT); device.SetRenderTarget(1, null); device.DepthStencilSurface = pOldDS; // swap de texturas Texture aux = g_pVelocidad; g_pVelocidad = g_pVelocidadOut; g_pVelocidadOut = aux; aux = g_pPos; g_pPos = g_pPosOut; g_pPosOut = aux; // dibujo pp dicho ---------------------------------------------- device.Transform.Projection = ant_Proj; device.Transform.World = ant_World; device.Transform.View = ant_View; device.BeginScene(); device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); //Renderizar terreno if ((bool)Modifiers["dibujar_terreno"]) { terrain.Render(); } // dibujo las particulas como point sprites mesh.Effect = effect; mesh.Technique = "DefaultTechnique"; effect.SetValue("texDiffuseMap", g_pBaseTexture); CustomVertex.PositionColored[,] vertices = new CustomVertex.PositionColored[MAX_DS, MAX_DS]; for (int i = 0; i < MAX_DS; i++) { for (int j = 0; j < MAX_DS; j++) { float x0 = pos_x[i, j]; float z0 = pos_z[i, j]; float H = pos_y[i, j]; vertices[i, j] = new CustomVertex.PositionColored(x0, H + esfera_radio, z0, Color.Blue.ToArgb()); } } g_pVB.SetData(vertices, 0, LockFlags.None); device.VertexFormat = CustomVertex.PositionColored.Format; device.SetStreamSource(0, g_pVB, 0); device.SetTexture(0, null); device.SetRenderState(RenderStates.PointSize, 32); device.SetRenderState(RenderStates.PointScaleEnable, true); device.SetRenderState(RenderStates.PointSpriteEnable, true); device.DrawPrimitives(PrimitiveType.PointList, 0, MAX_DS * MAX_DS); device.EndScene(); }
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 }
//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 }
/// <summary> /// Actualiza los valores de la camara /// </summary> public void updateCamera(float elapsedTime) { if (!Enable) { return; } //Obtener variacion XY del mouse var mouseX = 0f; var mouseY = 0f; if (Input.keyDown(Key.LeftAlt) && Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_MIDDLE)) { mouseX = Input.XposRelative; mouseY = Input.YposRelative; diffX += mouseX * elapsedTime * RotationSpeed; diffY += mouseY * elapsedTime * RotationSpeed; } else { diffX += mouseX; diffY += mouseY; } //Calcular rotacion a aplicar var rotX = -diffY / FastMath.PI + BaseRotX; var rotY = diffX / FastMath.PI + BaseRotY; //Truncar valores de rotacion fuera de rango if (rotX > FastMath.PI * 2 || rotX < -FastMath.PI * 2) { diffY = 0; rotX = 0; } //Invertir Y de UpVector segun el angulo de rotacion if (rotX < -FastMath.PI / 2 && rotX > -FastMath.PI * 3 / 2) { upVector.Y = -1; } else if (rotX > FastMath.PI / 2 && rotX < FastMath.PI * 3 / 2) { upVector.Y = -1; } else { upVector.Y = 1; } //Determinar distancia de la camara o zoom segun el Mouse Wheel if (Input.WheelPos != 0) { diffZ += ZoomFactor * Input.WheelPos * -1; } var distance = -CameraDistance * diffZ; //Limitar el zoom a 0 if (distance > 0) { distance = 0; } //Realizar Transformacion: primero alejarse en Z, despues rotar en X e Y y despues ir al centro de la cmara var m = TGCMatrix.Translation(0, 0, -distance) * TGCMatrix.RotationX(rotX) * TGCMatrix.RotationY(rotY) * TGCMatrix.Translation(CameraCenter); //Extraer la posicion final de la matriz de transformacion nextPos.X = m.M41; nextPos.Y = m.M42; nextPos.Z = m.M43; //Hacer efecto de Pan View if (!Input.keyDown(Key.LeftAlt) && Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_MIDDLE)) { var dx = -Input.XposRelative; var dy = Input.YposRelative; var panSpeedZoom = PanSpeed * FastMath.Abs(distance); var d = CameraCenter - nextPos; d.Normalize(); var n = TGCVector3.Cross(d, upVector); n.Normalize(); var up = TGCVector3.Cross(n, d); var desf = TGCVector3.Scale(up, dy * panSpeedZoom) - TGCVector3.Scale(n, dx * panSpeedZoom); nextPos = nextPos + desf; CameraCenter = CameraCenter + desf; } //Obtener ViewTGCMatrix haciendo un LookAt desde la posicion final anterior al centro de la camara viewTGCMatrix = TGCMatrix.LookAtLH(nextPos, CameraCenter, upVector); }
/// <summary> /// Devuelve la matriz View en base a los valores de la camara. Es invocado en cada update de render. /// </summary> public virtual TGCMatrix GetViewMatrix() { return(TGCMatrix.LookAtLH(Position, LookAt, UpVector)); }
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); }
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(); }
public void render() { //pense en poner la luz adentro de la calabera y hacer que se vean los bordes, //se veia medio feo pero por ahi se puede hacer mejor //var lightPos = g.mostro.cPos // + TGCVector3.Up * 400f // + g.mostro.colDir * 0.21f // + TGCVector3.Cross(g.mostro.colDir, TGCVector3.Up) * .1f; var lightPos = g.mostro.cPos + g.mostro.height * TGCVector3.Up; var lightObj = new TGCVector3(g.mostro.lightObj.X, g.mostro.flyHeight, g.mostro.lightObj.Y); var lightView = TGCMatrix.LookAtLH(lightPos, lightObj, new TGCVector3(0, 0, 1)); var viewLightProj = (lightView * proj).ToMatrix(); shader.SetValue("mViewLightProj", viewLightProj); g.map.shader.SetValue("mViewLightProj", viewLightProj); g.map.shader.SetValue("lightPos", TGCVector3.Vector3ToFloat3Array(lightPos)); var lightDir = lightObj - lightPos; lightDir.Normalize(); g.map.shader.SetValue("lightDir", TGCVector3.Vector3ToFloat3Array(lightDir)); var screenRT = D3DDevice.Instance.Device.GetRenderTarget(0); D3DDevice.Instance.Device.SetRenderTarget(0, tex.GetSurfaceLevel(0)); var screenDS = D3DDevice.Instance.Device.DepthStencilSurface; D3DDevice.Instance.Device.DepthStencilSurface = depths; D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.CornflowerBlue, 1.0f, 0); D3DDevice.Instance.Device.BeginScene(); //g.mostro.renderForShadow(); g.terrain.renderForShadow(viewLightProj); g.chunks.renderForShadow(); //uso el mesh del esqueleto para el jugador porque no tengo otro //podria ser deep lore var mostroPos = g.mostro.pos; g.mostro.pos = g.camera.eyePosition - 500f * TGCVector3.Up; g.mostro.render(); g.mostro.pos = mostroPos; D3DDevice.Instance.Device.EndScene(); //D3DDevice.Instance.Device.Present(); //TextureLoader.Save("shadowmap.bmp", ImageFileFormat.Bmp, g_pShadowMap); D3DDevice.Instance.Device.DepthStencilSurface = screenDS; D3DDevice.Instance.Device.SetRenderTarget(0, screenRT); g.map.shader.SetValue("inView", g.mostro.timeInView > 0); }