public Effect( Renderer renderer, string filename ) { //if (!File.Exists(filename)) // throw new FileNotFoundException(filename); if ( renderer == null ) throw new ArgumentNullException( "renderer", "Can't create an Effect without a valid renderer." ); string compilationErrors = ""; try { effect = Direct3D.Effect.FromFile( renderer.Device, filename, null, null, null, ShaderFlags.None, null, out compilationErrors ); } catch { Log.Write( "Unable to create effect " + filename + ". The compilation errors were: \n\n" + compilationErrors ); } renderer.AddGraphicsObject( this ); }
public static void Cargar() { Device d3dDevice = GuiController.Instance.D3dDevice; // Cargo el shader que tiene los efectos de postprocesado Shader = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "RenderGroup\\shaders\\postProcess.fx"); // Creo el quad que va a ocupar toda la pantalla CustomVertex.PositionTextured[] screenQuadVertices = 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) }; ScreenQuad = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, GuiController.Instance.D3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); ScreenQuad.SetData(screenQuadVertices, 0, LockFlags.None); // Creamos un render targer sobre el cual se va a dibujar la pantalla RenderTargetPostprocesado = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); #region VALORES DE INTERPOLACION intVaivenOscurecer = new InterpoladorVaiven(); intVaivenOscurecer.Min = 1; intVaivenOscurecer.Max = 15; intVaivenOscurecer.Speed = 40f; intVaivenOscurecer.reset(); #endregion }
public void Dispose() { if ( effect != null ) effect.Dispose(); effect = null; }
public override void Init() { MyMediaDir = MediaDir; //Crear loader var loader = new TgcSceneLoader(); // ------------------------------------------------------------ // Creo el Heightmap para el terreno: var PosTerrain = TGCVector3.Empty; currentHeightmap = MyMediaDir + "Heighmaps\\Heightmap2.jpg"; currentScaleXZ = 100f; currentScaleY = 2f; currentTexture = MyMediaDir + "Heighmaps\\TerrainTexture3.jpg"; terrain = new TgcSimpleTerrain(); terrain.loadHeightmap(currentHeightmap, currentScaleXZ, currentScaleY, PosTerrain); terrain.loadTexture(currentTexture); // ------------------------------------------------------------ // 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]; sceneX = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Sphere\\Sphere-TgcScene.xml"); meshX = sceneX.Meshes[0]; meshX.AutoTransform = true; scene2 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera\\Palmera-TgcScene.xml"); palmera = scene2.Meshes[0]; palmera.AutoTransform = true; scene3 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\AvionCaza\\AvionCaza-TgcScene.xml"); avion = scene3.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; avion.Scale = new TGCVector3(1f, 1f, 1f); avion.Position = new TGCVector3(3000f, 550f, 0f); dir_avion = new TGCVector3(0, 0, 1); size = palmera.BoundingBox.calculateSize(); var alto_palmera = Math.Abs(size.Y); int i; bosque = new List <TgcMesh>(); float[] r = { 1900f, 2100f, 2300f, 1800f }; for (i = 0; i < 4; i++) { for (var j = 0; j < 15; j++) { var instance = palmera.createMeshInstance(palmera.Name + i); instance.AutoTransform = true; instance.Scale = new TGCVector3(0.5f, 1.5f, 0.5f); var x = r[i] * (float)Math.Cos(Geometry.DegreeToRadian(180 + 10.0f * j)); var z = r[i] * (float)Math.Sin(Geometry.DegreeToRadian(180 + 10.0f * j)); instance.Position = new TGCVector3(x, 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); */ // Arreglo las normales de la esfera { var adj = new int[meshX.D3dMesh.NumberFaces * 3]; meshX.D3dMesh.GenerateAdjacency(0, adj); meshX.D3dMesh.ComputeNormals(adj); } //Cargar Shader personalizado effect = TgcShaders.loadEffect(ShadersDir + "WorkshopShaders\\EnvMap.fx"); // le asigno el efecto a la malla mesh.Effect = effect; meshX.Effect = effect; vel_tanque = 10; //Centrar camara rotacional respecto a este mesh CamaraRot = new TgcRotationalCamera(mesh.BoundingBox.calculateBoxCenter(), mesh.BoundingBox.calculateBoxRadius() * 2, Input); CamaraRot.CameraDistance = 300; CamaraRot.RotationSpeed = 1.5f; Camara = CamaraRot; kx = kc = 0.5f; reflexionModifier = AddFloat("Reflexion", 0, 1, kx); refraccionModifier = AddFloat("Refraccion", 0, 1, kc); fresnelModifier = AddBoolean("Fresnel", "fresnel", true); }
public override void Init() { // Defino que se muestre la presentacion presentacion = true; opcionMenuSelecionado = 0; tiempoFogataEncendida = 0; partidoGanado = false; // Defino el Menu presentacion drawer2D = new Drawer2D(); menuPresentacion = new CustomSprite(); menuPresentacion.Bitmap = new CustomBitmap(this.MediaDir + "\\HUD\\presentacion.png", D3DDevice.Instance.Device); Size textureSize = menuPresentacion.Bitmap.Size; menuPresentacion.Position = new Vector2(0, 0); escaladoProporcionalX = (float)(D3DDevice.Instance.Width * 1f / menuPresentacion.Bitmap.Size.Width * 1f); escaladoProporcionalY = (float)(D3DDevice.Instance.Height * 1f / menuPresentacion.Bitmap.Size.Height * 1f); if (escaladoProporcionalX > escaladoProporcionalY) { menuPresentacion.Scaling = new Vector2(escaladoProporcionalX, escaladoProporcionalX); } else { menuPresentacion.Scaling = new Vector2(escaladoProporcionalY, escaladoProporcionalY); } buttonUnselected = new CustomSprite(); buttonUnselected.Bitmap = new CustomBitmap(MediaDir + "\\HUD\\btn-off.png", D3DDevice.Instance.Device); buttonUnselected.Scaling = new Vector2(0.2f, 0.2f); buttonSelected = new CustomSprite(); buttonSelected.Bitmap = new CustomBitmap(MediaDir + "\\HUD\\btn-on.png", D3DDevice.Instance.Device); buttonSelected.Scaling = new Vector2(0.2f, 0.2f); logoWilson = new CustomSprite(); logoWilson.Bitmap = new CustomBitmap(MediaDir + "\\HUD\\wilson.png", D3DDevice.Instance.Device); logoWilson.Scaling = new Vector2(0.5f, 0.5f); logoWilson.Position = new Vector2(0, 0); // Para determinar que momento del día es usoHorario = 0; tiempoAcumLluvia = 0; tiempoAcumHacha = 0; horaDelDia = 0; //0: dia, 1:tarde, 2:noche; terreno = new EscenarioGame.Escenario(this); terreno.Init(); personaje = new Personaje(this); personaje.Init(); hud = new HUD(this); hud.Init(); musica = new Musica(this.MediaDir); musica.selectionSound("Sonido\\ambiente1.mp3"); musica.startSound(); musica2 = new Musica(this.MediaDir); musica2.selectionSound("Sonido\\talar.mp3"); // Inicializacion de PostProcess con Render Target 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 Render Targer sobre el cual se va a dibujar la pantalla renderTarget2D = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth , D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); //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); //Cargar shader con efectos de Post-Procesado effect = TgcShaders.loadEffect(ShadersDir + "PostProcess.fx"); //Configurar Technique dentro del shader effect.Technique = "RainTechnique"; //Cargar textura que se va a dibujar arriba de la escena del Render Target lluviaTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, this.MediaDir + "Isla\\efecto_rain.png"); // Inicializo la camara InitCamera(); // SkyBox: Se cambia el valor por defecto del farplane para evitar cliping de farplane. D3DDevice.Instance.Device.Transform.Projection = Matrix.PerspectiveFovLH(D3DDevice.Instance.FieldOfView, D3DDevice.Instance.AspectRatio, D3DDevice.Instance.ZNearPlaneDistance, D3DDevice.Instance.ZFarPlaneDistance * 2560f); //cajaMenu = new TgcBox(); //cajaMenu.Position = new Vector3(0, 0, 0); //cajaMenu.Size = new Vector3(1000, 1000, 1000); //cajaMenu.AutoTransformEnable = true; //menuCaja = TgcTexture.createTexture(D3DDevice.Instance.Device, this.MediaDir + "\\HUD\\presentacion.jpg"); //cajaMenu.setTexture(menuCaja); //cajaMenu.updateValues(); }
public override void Init() { var d3dDevice = D3DDevice.Instance.Device; MyShaderDir = ShadersDir; wav_files = Directory.GetFiles(MediaDir + "sound"); //sound.Create(MediaDir + "sound\\smokeonthewater.wav"); //sound.Create(MediaDir + "sound\\rolemu_-_neogauge.wav"); // super dificl //sound.Create(MediaDir + "sound\\rolem_-_Neoishiki.wav"); // buenisimo (dificil) //sound.Create(MediaDir + "sound\\Azureflux_-_06_-_Kinetic_Sands.wav"); //sound.Create(MediaDir + "sound\\Azureflux_-_01_-_BOMB.wav"); //sound.Create(MediaDir + "sound\\Azureflux_-_02_-_Waves.wav"); // muy bueno, facil //sound.Create(MediaDir + "sound\\Monplaisir_-_03_-_Level_0.wav"); //sound.Create(MediaDir + "sound\\Monplaisir_-_04_-_Level_1.wav"); // monotono //sound.Create(MediaDir + "sound\\Monplaisir_-_05_-_Level_2.wav"); // monotono //sound.Create(MediaDir + "sound\\Monplaisir_-_06_-_Level_3.wav"); //sound.Create(MediaDir + "sound\\Monplaisir_-_07_-_Level_4.wav"); // bueno //sound.Create(MediaDir + "sound\\tecno1.wav"); // dificil //sound.Create(MediaDir + "sound\\ScoobyDooPaPa.wav"); // interesante //sound.Create(MediaDir + "sound\\highway intro.wav"); // se va de escala //sound.Create(MediaDir + "sound\\Shook_Me_All_Night.wav"); // bajo volumen //sound.Create(MediaDir + "sound\\ACDC.wav"); //Cargar Shader personalizado string compilationErrors; effect = Effect.FromFile(D3DDevice.Instance.Device, MyShaderDir + "shaders.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors); if (effect == null) { throw new Exception("Error al cargar shader. Errores: " + compilationErrors); } //Configurar Technique dentro del shader effect.Technique = "DefaultTechnique"; // para capturar el mouse var focusWindows = D3DDevice.Instance.Device.CreationParameters.FocusWindow; mouseCenter = focusWindows.PointToScreen(new Point(focusWindows.Width / 2, focusWindows.Height / 2)); mouseCaptured = false; //Cursor.Hide(); // stencil g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true); g_pDepthStencilOld = d3dDevice.DepthStencilSurface; // inicializo el render target g_pRenderTarget = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pRenderTarget2 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pRenderTarget3 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pRenderTarget4 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pRenderTarget5 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); // Resolucion de pantalla effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth); effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight); 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 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); time = 0; sprite = new Sprite(d3dDevice); // ajusto las letras para que se vean mas o menos igual en todas las resoluciones. float kx = (float)d3dDevice.PresentationParameters.BackBufferWidth / 1366.0f; float ky = (float)d3dDevice.PresentationParameters.BackBufferHeight / 768.0f; float k = Math.Min(kx, ky); // Fonts font = new Microsoft.DirectX.Direct3D.Font(d3dDevice, (int)(24 * k), 0, FontWeight.Light, 0, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "Lucida Console"); font.PreloadGlyphs('0', '9'); font.PreloadGlyphs('a', 'z'); font.PreloadGlyphs('A', 'Z'); s_font = new Microsoft.DirectX.Direct3D.Font(d3dDevice, (int)(18 * k), 0, FontWeight.Light, 0, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "Lucida Console"); s_font.PreloadGlyphs('0', '9'); s_font.PreloadGlyphs('a', 'z'); s_font.PreloadGlyphs('A', 'Z'); c64_font = new Microsoft.DirectX.Direct3D.Font(d3dDevice, (int)(40 * k), (int)(30 * k), FontWeight.Light, 0, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "System"); c64_font.PreloadGlyphs('0', '9'); c64_font.PreloadGlyphs('a', 'z'); c64_font.PreloadGlyphs('A', 'Z'); }
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; }
private void setEffects() { this.effect = TgcShaders.loadEffect(Game.Default.ShadersDirectory + "BasicShader.fx"); this.effect.SetValue("center", new[] { this.center.X, this.center.Y, this.center.Z, 1f }); }
public WallAccess(Direct3D.Device NewGameDevice, GameEngine.ShaderLevel NewCardShaderLevel, DirectX.Matrix NewViewMatrix, DirectX.Matrix NewProjectionMatrix) { GameDevice = NewGameDevice; CardShaderLevel = NewCardShaderLevel; ViewMatrix = NewViewMatrix; ProjectionMatrix = NewProjectionMatrix; // Load Shader Effects From Files WallEffect = Direct3D.Effect.FromFile(GameDevice, GameConfig.Files.WallFx, null, null, Direct3D.ShaderFlags.None, null); WallEffect.Technique = "WallLight_1_1"; PipeEffect = Direct3D.Effect.FromFile(GameDevice, GameConfig.Files.PipeFx, null, null, Direct3D.ShaderFlags.None, null); PipeEffect.Technique = "PipeLight_1_1"; // Load Mesh From File WallMesh = Direct3D.Mesh.FromFile(GameConfig.Files.WallMesh, Direct3D.MeshFlags.Managed, GameDevice, out WallMtrl); PipeMesh = Direct3D.Mesh.FromFile(GameConfig.Files.PipeMesh, Direct3D.MeshFlags.Managed, GameDevice, out PipeMtrl); // Load Wall Textures if ((WallMtrl != null) && (WallMtrl.Length > 0)) { WallMaterials = new Direct3D.Material[WallMtrl.Length]; WallTextures = new Direct3D.Texture[WallMtrl.Length]; for (int i = 0; i < WallMtrl.Length; i++) { WallMaterials[i] = WallMtrl[i].Material3D; if ((WallMtrl[i].TextureFilename != null) && (WallMtrl[i].TextureFilename != string.Empty)) { WallTextures[i] = Direct3D.TextureLoader.FromFile(GameDevice, @"..\..\Resources\" + WallMtrl[i].TextureFilename); } } } // Load Pipe Textures if ((PipeMtrl != null) && (PipeMtrl.Length > 0)) { PipeMaterials = new Direct3D.Material[PipeMtrl.Length]; PipeTextures = new Direct3D.Texture[PipeMtrl.Length]; for (int i = 0; i < PipeMtrl.Length; i++) { PipeMaterials[i] = PipeMtrl[i].Material3D; if ((PipeMtrl[i].TextureFilename != null) && (PipeMtrl[i].TextureFilename != string.Empty)) { PipeTextures[i] = Direct3D.TextureLoader.FromFile(GameDevice, @"..\..\Resources\" + PipeMtrl[i].TextureFilename); } } } // Set wall mesh location WallWorldMatrix = DirectX.Matrix.RotationYawPitchRoll(3.12f, 0.0f, 0.0f) * DirectX.Matrix.Translation(15, -75, -425); PipeWorldMatrix = DirectX.Matrix.RotationYawPitchRoll(3.20f, -0.1f, 0.0f) * DirectX.Matrix.Translation(-145, 15, -375); // Set Wall Shader Parameters DirectX.Matrix WorldViewProjMatrix = WallWorldMatrix * ViewMatrix * ProjectionMatrix; WallEffect.SetValue("WorldViewProj", WorldViewProjMatrix); WallEffect.SetValue("WorldMatrix", WallWorldMatrix); WallEffect.SetValue("DiffuseDirection", new DirectX.Vector4(1.0f, 1.0f, 1.0f, 0.0f)); // Set Pipe Shader Parameters WorldViewProjMatrix = PipeWorldMatrix * ViewMatrix * ProjectionMatrix; PipeEffect.SetValue("WorldViewProj", WorldViewProjMatrix); PipeEffect.SetValue("WorldMatrix", PipeWorldMatrix); PipeEffect.SetValue("DiffuseDirection", new DirectX.Vector4(1.0f, 1.0f, 1.0f, 0.0f)); }
///////////////////////////////////////////////////////////////////////// /// ////////////////////////////RENDER/////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// public void render(float deltaTime, TgcFrustum frustum) { if (activarTeleport) { currentShaderSkeletalMesh = efectoTeleport; } else { currentShaderSkeletalMesh = TgcShaders.Instance.TgcSkeletalMeshShader; } foreach (var mesh in objectsInFront) { if (!coleccionablesAgarrados.Contains(mesh)) { // var resultadoColisionFrustum = TgcCollisionUtils.classifyFrustumAABB(frustum, mesh.BoundingBox); // if (resultadoColisionFrustum != TgcCollisionUtils.FrustumResult.OUTSIDE) mesh.Render(); } } efectoOlas.SetValue("time", tiempoOlas); personajePrincipal.Effect = currentShaderSkeletalMesh; if (activarTeleport) { efectoTeleport.SetValue("time", tiempoTeleport); personajePrincipal.Technique = "RenderScene"; } if (desactivarTeleport) { personajePrincipal.Technique = TgcShaders.Instance.getTgcSkeletalMeshTechnique(personajePrincipal.RenderType); efectoTeleport.SetValue("time", 0); desactivarTeleport = false; } personajePrincipal.animateAndRender(deltaTime); HUD.Begin(SpriteFlags.AlphaBlend | SpriteFlags.SortDepthFrontToBack); posVidas = D3DDevice.Instance.Device.Viewport.Width - vida.Width; for (int i = 0; i < vidasRestantes; i++) { HUD.Transform = TGCMatrix.Translation(new TGCVector3(posVidas, 0, 0)); HUD.Draw(vida.D3dTexture, Rectangle.Empty, Vector3.Empty, Vector3.Empty, Color.OrangeRed); posVidas -= vida.Width; } scene.Meshes[295].BoundingBox.Render(); scene.Meshes[296].BoundingBox.Render(); scene.Meshes[305].BoundingBox.Render(); coleccionablesAdquiridos.cambiarTexto(cantidadColeccionablesAgarrados.ToString()); coleccionablesAdquiridos.Render(); coleccionablesAdquiridos.cambiarTamañoLetra(28); coleccionablesAdquiridos.cambiarColor(Color.BlueViolet); HUD.Draw2D(mumuki.D3dTexture, Rectangle.Empty, new SizeF(100, 100), new PointF(D3DDevice.Instance.Width - 100, D3DDevice.Instance.Height - 150), Color.White); HUD.End(); }
/// <summary> /// Creates the Effect object. /// </summary> public Effect() { _effect = null; Dispose(); }
private void loadShader() { var d3dDevice = Gui.I.D3dDevice; string compilationErrors; this.effect = Microsoft.DirectX.Direct3D.Effect.FromFile(d3dDevice, this.pathShader(), null, null, ShaderFlags.None, null, out compilationErrors); this.mesh.effect = effect; }
/// <summary> /// Inizializza l'effetto avanzato Water (da utilizzare all'esterno del GameLoop) /// </summary> /// <param name="baseTex"></param> /// <param name="backTex"></param> /// <param name="normal1Tex"></param> /// <param name="worldTex"></param> /// <param name="terraIncognitaTex"></param> /// <param name="normal2Tex"></param> /// <param name="normal3Tex"></param> public void WaterEffect(string baseTex, string backTex, string normal1Tex, string worldTex, string terraIncognitaTex, string normal2Tex, string normal3Tex) { try { EffectPool pool = new EffectPool(); Effect = Microsoft.DirectX.Direct3D.Effect.FromFile(LogiX_Engine.Device, "Water.fx", null, ShaderFlags.None, pool); EffectHandles = new EffectHandle[16]; EffectTechniques = new EffectHandle[1]; EffectTechniques[0] = Effect.GetTechnique("Water"); EffectHandles[0] = Effect.GetParameter(null, "matWorldViewProjection"); EffectHandles[1] = Effect.GetParameter(null, "LightPosition"); EffectHandles[2] = Effect.GetParameter(null, "CameraPosition"); EffectHandles[3] = Effect.GetParameter(null, "Time"); EffectHandles[4] = Effect.GetParameter(null, "vAlpha"); EffectHandles[5] = Effect.GetParameter(null, "Wave"); EffectHandles[6] = Effect.GetParameter(null, "waveSpeed"); EffectHandles[7] = Effect.GetParameter(null, "WaveLenght"); EffectHandles[8] = Effect.GetParameter(null, "TexturesDimension"); EffectHandles[9] = Effect.GetParameter(null, "BaseTex"); EffectHandles[10] = Effect.GetParameter(null, "BackTex"); EffectHandles[11] = Effect.GetParameter(null, "Normal1Tex"); EffectHandles[12] = Effect.GetParameter(null, "WorldTex"); EffectHandles[13] = Effect.GetParameter(null, "TerraIncognitaTex"); EffectHandles[14] = Effect.GetParameter(null, "Normal2Tex"); EffectHandles[15] = Effect.GetParameter(null, "Normal3Tex"); BaseTextures = new BaseTexture[7]; BaseTextures[0] = TextureLoader.FromFile(LogiX_Engine.Device, baseTex); BaseTextures[1] = TextureLoader.FromFile(LogiX_Engine.Device, backTex); BaseTextures[2] = TextureLoader.FromFile(LogiX_Engine.Device, normal1Tex); BaseTextures[3] = TextureLoader.FromFile(LogiX_Engine.Device, worldTex); BaseTextures[4] = TextureLoader.FromFile(LogiX_Engine.Device, terraIncognitaTex); BaseTextures[5] = TextureLoader.FromFile(LogiX_Engine.Device, normal2Tex); BaseTextures[6] = TextureLoader.FromFile(LogiX_Engine.Device, normal3Tex); correct = true; } catch { Error("OnCreateObject"); } }
/// <summary> /// Inizializza l'effetto avanzato Glass (da utilizzare all'esterno del GameLoop) /// </summary> /// <param name="cubeMap"></param> public void GlassEffect(CubeMap cubeMap) { try { EffectPool pool = new EffectPool(); Effect = Microsoft.DirectX.Direct3D.Effect.FromFile(LogiX_Engine.Device, "MEDIA//Glass.fx", null, ShaderFlags.None, pool); EffectHandles = new EffectHandle[10]; EffectTechniques = new EffectHandle[1]; EffectTechniques[0] = Effect.GetTechnique("Glass"); EffectHandles[0] = Effect.GetParameter(null, "matViewProjection"); EffectHandles[1] = Effect.GetParameter(null, "PointOfView"); EffectHandles[2] = Effect.GetParameter(null, "refractionScale"); EffectHandles[3] = Effect.GetParameter(null, "baseColor"); EffectHandles[4] = Effect.GetParameter(null, "ambient"); EffectHandles[5] = Effect.GetParameter(null, "indexOfRefractionRatio"); EffectHandles[6] = Effect.GetParameter(null, "reflectionScale"); EffectHandles[7] = Effect.GetParameter(null, "texCube"); EffectHandles[8] = Effect.GetParameter(null, "alpha"); EffectHandles[9] = Effect.GetParameter(null, "matWorld"); CubeTextures = new CubeTexture[1]; CubeTextures[0] = cubeMap.DXCubeTexture; correct = true; } catch { Error("OnCreateObject"); } }
/// <summary> /// Inizializza un effetto base tra quelli possibili (definiti da LogiX_Technologies.XEffects). Da utilizzare all'esterno del GameLoop /// </summary> /// <param name="baseTexturePath"></param> /// <param name="normalTexturePath"></param> /// <param name="cubeMap"></param> /// <param name="DefaultEffects"></param> public void DefaultEffect(string baseTexturePath, string normalTexturePath, CubeMap cubeMap, XEffects DefaultEffects) { switch (DefaultEffects) { case XEffects.PerPixelDirectionalLight: try { EffectPool pool = new EffectPool(); Effect = Microsoft.DirectX.Direct3D.Effect.FromFile(LogiX_Engine.Device, "PerPixelDirectionalLight.fx", null, ShaderFlags.None, pool); EffectHandles = new EffectHandle[8]; EffectTechniques = new EffectHandle[1]; EffectTechniques[0] = Effect.GetTechnique("t0"); EffectHandles[0] = Effect.GetParameter(null, "transform"); EffectHandles[1] = Effect.GetParameter(null, "world"); EffectHandles[2] = Effect.GetParameter(null, "LightDirection"); EffectHandles[3] = Effect.GetParameter(null, "ViewDirection"); EffectHandles[4] = Effect.GetParameter(null, "base_Tex"); EffectHandles[5] = Effect.GetParameter(null, "Specular"); EffectHandles[6] = Effect.GetParameter(null, "Diffuse"); EffectHandles[7] = Effect.GetParameter(null, "SpecularPower"); BaseTextures = new BaseTexture[1]; BaseTextures[0] = TextureLoader.FromFile(LogiX_Engine.Device, baseTexturePath); correct = true; } catch { Error("OnCreateObject"); } break; case XEffects.PerPixelPointLight: try { EffectPool pool = new EffectPool(); Effect = Microsoft.DirectX.Direct3D.Effect.FromFile(LogiX_Engine.Device, Application.StartupPath + "/PerPixelPointLight.fx", null, ShaderFlags.None, pool); EffectHandles = new EffectHandle[11]; EffectTechniques = new EffectHandle[1]; EffectTechniques[0] = Effect.GetTechnique("PerPixelLightning"); EffectHandles[0] = Effect.GetParameter(null, "World"); EffectHandles[1] = Effect.GetParameter(null, "View"); EffectHandles[2] = Effect.GetParameter(null, "Projection"); EffectHandles[3] = Effect.GetParameter(null, "LightPosition"); EffectHandles[4] = Effect.GetParameter(null, "ReflectionRatio"); EffectHandles[5] = Effect.GetParameter(null, "SpecularRatio"); EffectHandles[6] = Effect.GetParameter(null, "SpecularStyleLerp"); EffectHandles[7] = Effect.GetParameter(null, "SpecularPower"); EffectHandles[8] = Effect.GetParameter(null, "LightColor"); EffectHandles[9] = Effect.GetParameter(null, "MyTex_Tex"); EffectHandles[10] = Effect.GetParameter(null, "myCubemap_Tex"); BaseTextures = new BaseTexture[1]; CubeTextures = new CubeTexture[1]; BaseTextures[0] = TextureLoader.FromFile(LogiX_Engine.Device, baseTexturePath); CubeTextures[0] = cubeMap.DXCubeTexture; } catch { Error("OnCreateObject"); } break; case XEffects.BumpPerPixelPointLight: try { EffectPool pool = new EffectPool(); Effect = Microsoft.DirectX.Direct3D.Effect.FromFile(LogiX_Engine.Device, Application.StartupPath + "PerPixelPointLight.fx", null, ShaderFlags.None, pool); EffectHandles = new EffectHandle[12]; EffectTechniques = new EffectHandle[1]; EffectTechniques[0] = Effect.GetTechnique("PerPixelLightning"); EffectHandles[0] = Effect.GetParameter(null, "World"); EffectHandles[1] = Effect.GetParameter(null, "View"); EffectHandles[2] = Effect.GetParameter(null, "Projection"); EffectHandles[3] = Effect.GetParameter(null, "LightPosition"); EffectHandles[4] = Effect.GetParameter(null, "ReflectionRatio"); EffectHandles[5] = Effect.GetParameter(null, "SpecularRatio"); EffectHandles[6] = Effect.GetParameter(null, "SpecularStyleLerp"); EffectHandles[7] = Effect.GetParameter(null, "SpecularPower"); EffectHandles[8] = Effect.GetParameter(null, "LightColor"); EffectHandles[9] = Effect.GetParameter(null, "MyTex_Tex"); EffectHandles[10] = Effect.GetParameter(null, "MyNTex_Tex"); EffectHandles[11] = Effect.GetParameter(null, "myCubemap_Tex"); BaseTextures = new BaseTexture[2]; CubeTextures = new CubeTexture[1]; BaseTextures[0] = TextureLoader.FromFile(LogiX_Engine.Device, baseTexturePath); BaseTextures[1] = TextureLoader.FromFile(LogiX_Engine.Device, normalTexturePath); CubeTextures[0] = cubeMap.DXCubeTexture; correct = true; } catch { Error("OnCreateObject"); } break; case XEffects.Reflect: try { EffectPool pool = new EffectPool(); Effect = Microsoft.DirectX.Direct3D.Effect.FromFile(LogiX_Engine.Device, "Reflect.fx", null, ShaderFlags.None, pool); EffectHandles = new EffectHandle[7]; EffectTechniques = new EffectHandle[1]; EffectTechniques[0] = Effect.GetTechnique("Textured_Bump"); EffectHandles[0] = Effect.GetParameter(null, "fvEyePosition"); EffectHandles[1] = Effect.GetParameter(null, "matView"); EffectHandles[2] = Effect.GetParameter(null, "matViewProjection"); EffectHandles[3] = Effect.GetParameter(null, "ReflectionRatio"); EffectHandles[4] = Effect.GetParameter(null, "bump_Tex"); EffectHandles[5] = Effect.GetParameter(null, "cube_Tex"); EffectHandles[6] = Effect.GetParameter(null, "Bump"); BaseTextures = new BaseTexture[1]; CubeTextures = new CubeTexture[1]; BaseTextures[0] = TextureLoader.FromFile(LogiX_Engine.Device, normalTexturePath); CubeTextures[0] = cubeMap.DXCubeTexture; correct = true; } catch { Error("OnCreateObject"); } break; } }
public override void Init() { MyShaderDir = ShadersDir + "WorkshopShaders\\"; //Crear loader var loader = new TgcSceneLoader(); //Cargar mesh scene = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Teapot\\Teapot-TgcScene.xml"); mesh = scene.Meshes[0]; mesh.Scale = new Vector3(1f, 1f, 1f); mesh.Position = new Vector3(-100f, -5f, 0f); // Arreglo las normales var adj = new int[mesh.D3dMesh.NumberFaces * 3]; mesh.D3dMesh.GenerateAdjacency(0, adj); mesh.D3dMesh.ComputeNormals(adj); //Cargar Shader personalizado effect = TgcShaders.loadEffect(MyShaderDir + "ToonShading.fx"); // le asigno el efecto a la malla mesh.Effect = effect; mesh.Technique = "DefaultTechnique"; // Creo las instancias de malla instances = new List <TgcMesh>(); for (var i = -5; i < 5; i++) { for (var j = -5; j < 5; j++) { var instance = mesh.createMeshInstance(mesh.Name + i); instance.move(i * 50, (i + j) * 5, j * 50); instances.Add(instance); } } Modifiers.addVertex3f("LightPosition", new Vector3(-100, -100, -100), new Vector3(100, 100, 100), new Vector3(0, 40, 0)); Modifiers.addFloat("Ambient", 0, 1, 0.5f); Modifiers.addFloat("Diffuse", 0, 1, 0.6f); Modifiers.addFloat("Specular", 0, 1, 0.5f); Modifiers.addFloat("SpecularPower", 1, 100, 16); Camara = new TgcRotationalCamera(new Vector3(20, 20, 0), 300, TgcRotationalCamera.DEFAULT_ZOOM_FACTOR, 1.5f); // Creo un depthbuffer sin multisampling, para que sea compatible con el render to texture // Nota: // El render to Texture no es compatible con el multisampling en dx9 // Por otra parte la mayor parte de las placas de ultima generacion no soportan // mutisampling para texturas de punto flotante con lo cual // hay que suponer con generalidad que no se puede usar multisampling y render to texture // Para resolverlo hay que crear un depth buffer que no tenga multisampling, // (de lo contrario falla el zbuffer y se producen artifacts tipicos de que no tiene zbuffer) // Si uno quisiera usar el multisampling, la tecnica habitual es usar un RenderTarget // en lugar de una textura. // Por ejemplo en c++: // // Render Target formato color buffer con multisampling // // g_pd3dDevice->CreateRenderTarget(Ancho,Alto, // D3DFMT_A8R8G8B8, D3DMULTISAMPLE_2_SAMPLES, 0, // FALSE, &g_pRenderTarget, NULL); // // Luego, ese RenderTarget NO ES una textura, y nosotros necesitamos acceder a esos // pixeles, ahi lo que se hace es COPIAR del rendertartet a una textura, // para poder trabajar con esos datos en el contexto del Pixel shader: // // Eso se hace con la funcion StretchRect: // copia de rendertarget ---> sceneSurface (que es la superficie asociada a una textura) // g_pd3dDevice->StretchRect(g_pRenderTarget, NULL, g_pSceneSurface, NULL, D3DTEXF_NONE); // // Esta tecnica se llama downsampling // Y tiene el costo adicional de la transferencia de memoria entre el rendertarget y la // textura, pero que no traspasa los limites de la GPU. (es decir es muy performante) // no es lo mismo que lockear una textura para acceder desde la CPU, que tiene el problema // de transferencia via AGP. g_pDepthStencil = D3DDevice.Instance.Device.CreateDepthStencilSurface( D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth, D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true); // inicializo el render target g_pRenderTarget = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth , D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); effect.SetValue("g_RenderTarget", g_pRenderTarget); // inicializo el mapa de normales g_pNormals = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth , D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default); effect.SetValue("g_Normals", g_pNormals); // Resolucion de pantalla effect.SetValue("screen_dx", D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth); effect.SetValue("screen_dy", D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight); //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(-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.Instance.Device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); g_pVBV3D.SetData(vertices, 0, LockFlags.None); efecto_blur = false; }
///////////////////////////////////////////////////////////////////////// ////////////////////////////////INIT///////////////////////////////////// ///////////////////////////////////////////////////////////////////////// public void init(string MediaDir, string shaderDir, TgcCamera camara) { var d3dDevice = D3DDevice.Instance.Device; resolucionX = d3dDevice.PresentationParameters.BackBufferWidth; resolucionY = d3dDevice.PresentationParameters.BackBufferHeight; D3DDevice.Instance.ParticlesEnabled = true; D3DDevice.Instance.EnableParticles(); var loader = new TgcSceneLoader(); scene = loader.loadSceneFromFile(MediaDir + "NivelFisica1\\EscenaSceneEditorFisica1-TgcScene.xml"); SetearAguas(); pathDeLaCancion = MediaDir + "Musica\\FeverTime.mp3"; meshesDeLaEscena = new List <TgcMesh>(); HUD = new Sprite(D3DDevice.Instance.Device); vida = TgcTexture.createTexture(MediaDir + "Textures\\vida.png"); fisicaLib = TgcTexture.createTexture(MediaDir + "NivelFisica1\\Textures\\TexturaTapaLibro.jpg"); var skeletalLoader = new TgcSkeletalLoader(); personajePrincipal = skeletalLoader.loadMeshAndAnimationsFromFile( MediaDir + "Robot\\Robot-TgcSkeletalMesh.xml", MediaDir + "Robot\\", new[] { MediaDir + "Robot\\Caminando-TgcSkeletalAnim.xml", MediaDir + "Robot\\Parado-TgcSkeletalAnim.xml", MediaDir + "Robot\\Empujar-TgcSkeletalAnim.xml", }); //Configurar animacion inicial personajePrincipal.playAnimation("Parado", true); personajePrincipal.Position = puntoCheckpointActual; personajePrincipal.RotateY(Geometry.DegreeToRadian(180)); camaraInterna = new TgcThirdPersonCamera(personajePrincipal.Position, 250, 500); // camara = camaraInterna; camaraInterna.rotateY(Geometry.DegreeToRadian(180)); librosAdquiridos = new Boton(cantidadLibrosAdquiridos.ToString(), resolucionX - (resolucionX / 9), resolucionY - (resolucionY / 7), null); plataforma1 = scene.Meshes[164]; plataforma2 = scene.Meshes[165]; plataformasMovibles.Add(plataforma1); plataformasMovibles.Add(plataforma2); bolaDeCanion1 = scene.Meshes[172]; bolaDeCanion2 = scene.Meshes[173]; bolaDeCanion3 = scene.Meshes[174]; posicionInicialBolaDeCanion1 = scene.Meshes[172].Position; posicionInicialBolaDeCanion2 = scene.Meshes[173].Position; posicionInicialBolaDeCanion3 = scene.Meshes[174].Position; bolasDeCanion.Add(bolaDeCanion1); bolasDeCanion.Add(bolaDeCanion2); bolasDeCanion.Add(bolaDeCanion3); pathTexturaEmisorDeParticulas = MediaDir + "Textures\\fuego.png"; cantidadDeParticulas = 10; emisorDeParticulas1 = new ParticleEmitter(pathTexturaEmisorDeParticulas, cantidadDeParticulas); emisorDeParticulas1.MinSizeParticle = 30f; emisorDeParticulas1.MaxSizeParticle = 30f; emisorDeParticulas1.ParticleTimeToLive = 1f; emisorDeParticulas1.CreationFrecuency = 1f; //0.25 emisorDeParticulas1.Dispersion = 500; emisorDeParticulas1.Speed = new TGCVector3(-25, 40, 50); posicionInicialEmisorDeParticulas1 = new TGCVector3(1935, 200, 4345); emisorDeParticulas1.Position = posicionInicialEmisorDeParticulas1; emisorDeParticulas2 = new ParticleEmitter(pathTexturaEmisorDeParticulas, cantidadDeParticulas); emisorDeParticulas2 = new ParticleEmitter(pathTexturaEmisorDeParticulas, cantidadDeParticulas); emisorDeParticulas2.MinSizeParticle = 30f; emisorDeParticulas2.MaxSizeParticle = 30f; emisorDeParticulas2.ParticleTimeToLive = 1f; emisorDeParticulas2.CreationFrecuency = 1f; emisorDeParticulas2.Dispersion = 500; emisorDeParticulas2.Speed = new TGCVector3(-25, 40, 50); posicionInicialEmisorDeParticulas2 = new TGCVector3(2205, 200, 4345); emisorDeParticulas2.Position = posicionInicialEmisorDeParticulas2; emisorDeParticulas3 = new ParticleEmitter(pathTexturaEmisorDeParticulas, cantidadDeParticulas); emisorDeParticulas3 = new ParticleEmitter(pathTexturaEmisorDeParticulas, cantidadDeParticulas); emisorDeParticulas3.MinSizeParticle = 30f; emisorDeParticulas3.MaxSizeParticle = 30f; emisorDeParticulas3.ParticleTimeToLive = 1f; emisorDeParticulas3.CreationFrecuency = 1f; emisorDeParticulas3.Dispersion = 500; emisorDeParticulas3.Speed = new TGCVector3(-25, 40, 50); posicionInicialEmisorDeParticulas3 = new TGCVector3(2495, 200, 4345); emisorDeParticulas3.Position = posicionInicialEmisorDeParticulas3; reproductorMp3.FileName = pathDeLaCancion; reproductorMp3.play(true); AdministradorDeEscenarios.getSingleton().SetCamara(camaraInterna); cantVidas = 3; effect = TgcShaders.loadEffect(shaderDir + "MultiDiffuseLights.fx"); for (var i = 224; i < 250; ++i) { lights.Add(scene.Meshes[i]); } scene.Meshes[4].D3dMesh.ComputeNormals(); scene.Meshes[48].D3dMesh.ComputeNormals(); var lightColors = new ColorValue[lights.Count]; var pointLightPositions = new Vector4[lights.Count]; var pointLightIntensity = new float[lights.Count]; var pointLightAttenuation = new float[lights.Count]; for (var i = 0; i < lights.Count; i++) { var lightMesh = lights[i]; lightColors[i] = ColorValue.FromColor(Color.White); pointLightPositions[i] = TGCVector3.Vector3ToVector4(lightMesh.BoundingBox.Position); pointLightIntensity[i] = 20; pointLightAttenuation[i] = 0.07f; } tecnicaNormal = scene.Meshes[0].Technique; sinEfectos = scene.Meshes[0].Effect; foreach (var mesh in scene.Meshes) { //if (mesh.Name.Contains("Box") || mesh.Name.Contains("Madera") || mesh.Name.Contains("East") || mesh.Name.Contains("South") || mesh.Name.Contains("North") || mesh.Name.Contains("West")) if (!mesh.Name.Contains("Floor")) { continue; } mesh.Effect = effect; mesh.Effect.SetValue("lightColor", lightColors); mesh.Effect.SetValue("lightPosition", pointLightPositions); mesh.Effect.SetValue("lightIntensity", pointLightIntensity); mesh.Effect.SetValue("lightAttenuation", pointLightAttenuation); mesh.Effect.SetValue("materialEmissiveColor", ColorValue.FromColor(Color.Black)); mesh.Effect.SetValue("materialDiffuseColor", ColorValue.FromColor(Color.White)); mesh.Technique = "MultiDiffuseLightsTechnique"; if (mesh.Name.Contains("Box") || mesh.Name.Contains("Madera")) { mesh.Effect.SetValue("lightAttenuation", pointLightAttenuation); mesh.D3dMesh.ComputeNormals(); } } AplicarShaders(shaderDir); }
public override void init() { //Device de DirectX para crear primitivas d3dDevice = GuiController.Instance.D3dDevice; TgcSceneLoader loader = new TgcSceneLoader(); //cargamos los meshes de los barcos barcoJugador = new BarcoJugador(new Vector3(0, 0, 0), this, GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Vehiculos\\Canoa\\Canoa-TgcScene.xml"); barcoIA = new BarcoIA(new Vector3(200, 0, 0), this, GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Vehiculos\\Canoa\\Canoa-TgcScene.xml"); string shaderFolder = GuiController.Instance.AlumnoEjemplosMediaDir +"\\shaders"; time = 0; scaleXZ = 20f; scaleY = 1.3f; //cargamos el efecto que le vamos a aplicar a los meshes effect = TgcShaders.loadEffect(shaderFolder + "\\shaderLoco.fx"); heightmap = GuiController.Instance.AlumnoEjemplosMediaDir + "Heightmap\\" + "heightmap500.jpg"; textura = GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Textures\\Liquidos" + "\\water_flow.jpg"; //cargamos el terreno terreno = new TgcSimpleTerrain(); terreno.loadHeightmap(heightmap, scaleXZ, scaleY, new Vector3(0, 0, 0)); terreno.loadTexture(textura); terreno.Effect = effect; terreno.Technique = "LightScene"; // Creo SkyBox string texturesPath = GuiController.Instance.ExamplesMediaDir + "Texturas\\Quake\\SkyBox LostAtSeaDay\\"; string skyboxFolder = GuiController.Instance.AlumnoEjemplosMediaDir + "skybox\\"; skyBox = new TgcSkyBox(); skyBox.Center = new Vector3(0, 0, 0); skyBox.Size = new Vector3(8000, 8000, 8000); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, skyboxFolder + "skyboxArriba.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, skyboxFolder + "skyboxAbajo.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, skyboxFolder + "skybox2.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, skyboxFolder + "skybox2.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, skyboxFolder + "skybox1.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, skyboxFolder + "skybox2.jpg"); skyBox.SkyEpsilon = 50f; skyBox.updateValues(); barcoJugador.setEnemy(barcoIA); barcoJugador.setEffect(effect); barcoJugador.setTechnique("HeightScene"); barcoIA.setEnemy(barcoJugador); barcoIA.setEffect(effect); barcoIA.setTechnique("HeightScene"); barcoJugador.cargarCaniones(); barcoIA.cargarCaniones(); mediaAlturaBarco = barcoJugador.BoundingBox().calculateAxisRadius().Y; effect.SetValue("mediaAlturaBarco", mediaAlturaBarco); GuiController.Instance.Modifiers.addFloat("alturaOlas", 5f, 30f, 10f); GuiController.Instance.Modifiers.addFloat("frecuenciaOlas", 50f, 300f, 100f); GuiController.Instance.Modifiers.addBoolean("mostrar_lluvia", "Mostrar Lluvia", false); vecAux = new Vector3(0, 0, 0); ortogonal = new Vector3(0, 0, 0); sol = new Sol(effect); planoSubyacente = new Plano(); normalPlano = new Vector3(0, 0, 0); terminar = false; nube = new Nube(1000); //Centrar camara rotacional respecto a la canoa GuiController.Instance.ThirdPersonCamera.Enable = true; GuiController.Instance.ThirdPersonCamera.setCamera(barcoJugador.posicion(), 500, 600); GuiController.Instance.ThirdPersonCamera.updateCamera(); }
public override void Init() { var d3dDevice = D3DDevice.Instance.Device; MyShaderDir = ShadersDir + "WorkshopShaders\\"; //Cargamos un escenario var loader = new TgcSceneLoader(); //TgcScene scene = loader.loadSceneFromFile(this.MediaDir + "MeshCreator\\Scenes\\Deposito\\Deposito-TgcScene.xml"); var scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Scenes\\Selva\\Selva-TgcScene.xml"); meshes = scene.Meshes; var scene2 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Pasto\\Pasto-TgcScene.xml"); pasto = scene2.Meshes[0]; var scene3 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\ArbolSelvatico\\ArbolSelvatico-TgcScene.xml"); arbol = scene3.Meshes[0]; var scene4 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Arbusto2\\Arbusto2-TgcScene.xml"); arbusto = scene4.Meshes[0]; //Cargar personaje con animaciones var skeletalLoader = new TgcSkeletalLoader(); var rnd = new Random(); for (var t = 0; t < 25; ++t) { enemigos.Add(skeletalLoader.loadMeshAndAnimationsFromFile( MediaDir + "SkeletalAnimations\\BasicHuman\\" + "CombineSoldier-TgcSkeletalMesh.xml", MediaDir + "SkeletalAnimations\\BasicHuman\\", new[] { MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "StandBy-TgcSkeletalAnim.xml", MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Run-TgcSkeletalAnim.xml" })); //Configurar animacion inicial enemigos[t].playAnimation("StandBy", true); enemigos[t].Position = new TGCVector3(-rnd.Next(0, 1500) - 250, 0, -rnd.Next(0, 1500) - 250); enemigos[t].Scale = new TGCVector3(2f, 2f, 2f); enemigos[t].Transform = TGCMatrix.Scaling(enemigos[t].Scale) * TGCMatrix.Translation(enemigos[t].Position); //enemigos[t].UpdateMeshTransform(); bot_status[t] = 0; } //Cargar Shader personalizado string compilationErrors; effect = Effect.FromFile(D3DDevice.Instance.Device, MyShaderDir + "GaussianBlur.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors); if (effect == null) { throw new Exception("Error al cargar shader. Errores: " + compilationErrors); } //Configurar Technique dentro del shader effect.Technique = "DefaultTechnique"; //Camara en primera personas Camara = new TgcFpsCamera(new TGCVector3(-1000, 250, -1000), 1000f, 600f, Input); g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true); // inicializo el render target g_pRenderTarget = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pGlowMap = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pRenderTarget4 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth / 4, d3dDevice.PresentationParameters.BackBufferHeight / 4, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pRenderTarget4Aux = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth / 4, d3dDevice.PresentationParameters.BackBufferHeight / 4, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); effect.SetValue("g_RenderTarget", g_pRenderTarget); // Resolucion de pantalla effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth); effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight); 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 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); activarEfectoModifier = AddBoolean("activar_efecto", "Activar efecto", true); timer_firing = new float[100]; pos_bala = new TGCVector3[100]; dir_bala = new TGCVector3[100]; for (var i = 0; i < cant_balas; ++i) { timer_firing[i] = i / (float)cant_balas * total_timer_firing; } }
public ShaderEnvMap(string ShadersDir) { EnvMap = TGCShaders.Instance.LoadEffect(ShadersDir + "\\EnvMap.fx"); EnvMap.Technique = "RenderScene"; posicionLuz = new TGCVector3(1500, 600, 1500); }
/// <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(); }
public override void Init() { var d3dDevice = D3DDevice.Instance.Device; MyShaderDir = ShadersDir + "WorkshopShaders\\"; circuito = new F1Circuit(MediaDir); //Cargar terreno: cargar heightmap y textura de color terrain = new TgcSimpleTerrain(); terrain.loadHeightmap(MediaDir + "Heighmaps\\" + "TerrainTexture2.jpg", 20, 0.1f, new TGCVector3(0, -125, 0)); terrain.loadTexture(MediaDir + "Heighmaps\\" + "TerrainTexture2.jpg"); //Crear SkyBox skyBox = new TgcSkyBox(); skyBox.Center = new TGCVector3(0, 500, 0); skyBox.Size = new TGCVector3(10000, 10000, 10000); var texturesPath = MediaDir + "Texturas\\Quake\\SkyBox LostAtSeaDay\\"; skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "lostatseaday_up.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "lostatseaday_dn.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "lostatseaday_lf.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "lostatseaday_rt.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "lostatseaday_bk.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "lostatseaday_ft.jpg"); skyBox.Init(); var loader = new TgcSceneLoader(); var scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\Auto\\Auto-TgcScene.xml"); car = scene.Meshes[0]; //Cargar Shader personalizado string compilationErrors; effect = Effect.FromFile(D3DDevice.Instance.Device, MyShaderDir + "OutRun.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors); if (effect == null) { throw new Exception("Error al cargar shader. Errores: " + compilationErrors); } //Configurar Technique dentro del shader effect.Technique = "DefaultTechnique"; //Configurar FPS Camera Camera.SetCamera(new TGCVector3(315.451f, 40, -464.28490f), new TGCVector3(315.451f, 40, -465.28490f)); reset_pos(); // para capturar el mouse var focusWindows = D3DDevice.Instance.Device.CreationParameters.FocusWindow; mouseCenter = focusWindows.PointToScreen(new Point(focusWindows.Width / 2, focusWindows.Height / 2)); mouseCaptured = true; Cursor.Hide(); // stencil g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true); g_pDepthStencilOld = d3dDevice.DepthStencilSurface; // inicializo el render target g_pRenderTarget = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pRenderTarget2 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pRenderTarget3 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pRenderTarget4 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); g_pRenderTarget5 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); // Resolucion de pantalla effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth); effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight); 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 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); }
public void SetLight(int index, Microsoft.DirectX.Direct3D.Effect effect) { effect.SetValue("lights[" + index + "].Position", TGCVector3.TGCVector3ToFloat3Array(position)); effect.SetValue("lights[" + index + "].Color", TGCVector3.TGCVector3ToFloat3Array(color)); }
public Auto(string nombre, float vida, float avanceMaximo, float reversaMax, float aceleracion, float desaceleracion, TgcMesh mesh, GameModel model, Ruedas ruedasAdelante, Ruedas ruedasAtras, TgcMesh ruedaMainMesh, Velocimetro velocimetroIN) { DeformationConstant = 1f; MeshesCercanos = new List <TgcMesh>(); var scale = 0.4f; scale3 = new Vector3(scale, scale, scale); CrearHumoCanioDeEscape(model); humoChoque = new HumoEscape(model, true); AvanceMax = avanceMaximo; ReversaMax = -reversaMax; Desaceleracion = desaceleracion; InerciaNegativa = 1f; DireccionRuedas = 0f; Armas = new List <Arma>(); aceleracionVertical = 0f; Velocidad = 0f; Mesh = mesh; Mesh.Scale = scale3; Aceleracion = aceleracion; GameModel = model; RuedasTraseras = ruedasAtras; RuedasDelanteras = ruedasAdelante; RuedaMainMesh = ruedaMainMesh; //------------Ariel--------------- Mesh.AutoTransformEnable = false; Mesh.AutoUpdateBoundingBox = false; obb = TgcBoundingOrientedBox.computeFromAABB(Mesh.BoundingBox); var yMin = Mesh.BoundingBox.PMin.Y; var yMax = Mesh.BoundingBox.PMax.Y; obbPosY = (yMax + yMin) / 2 + yMin; obb.Extents = new Vector3(obb.Extents.X, obb.Extents.Y, obb.Extents.Z * -1); largo = obb.Extents.Z; ciudadScene = model.MapScene; //--------luces Luces = new LucesAuto(this, ruedasAdelante, ruedasAtras, CamaraAuto); RenderLuces = false; EsAutoJugador = true; fixEjecutado = false; //para arreglar el temita de que el auto no aparece. //shader pal hummer TechniqueOriginal = Mesh.Technique; efectoOriginal = Mesh.Effect; efectoShaderNitroHummer = TgcShaders.loadEffect(GameModel.ShadersDir + "ShaderHummer.fx"); velocimetro = velocimetroIN; //GameModel.shadowMap = new ShadowMap(GameModel);// para shadowmapFIX TodosLosMeshes = getAllMeshes(); }
public override void Render() { PreRender(); Microsoft.DirectX.Direct3D.Effect shaderActual = efectoLuz; string tecnica = "MultiDiffuseLightsTechnique"; /* * foreach (TgcMesh m in piso.MeshInstances) * { * m.Effect = efectoLuz; * m.Technique = tecnica; * } */ //piso.UpdateMeshTransform(); /* * foreach (TgcMesh caja in cajas) * { * caja.Effect = shaderActual; * caja.Technique = tecnica; * } * * var lightColors = new ColorValue[1]; * var pointLightPositions = new Vector4[1]; * var pointLightIntensity = new float[1]; * var pointLightAttenuation = new float[1]; * * lightColors[0] = ColorValue.FromColor(Color.Blue); * pointLightPositions[0] = TgcParserUtils.vector3ToVector4(cajaConLuz.Position); * pointLightIntensity[0] = 100; * pointLightAttenuation[0] = (float)0.1; * * foreach (TgcMesh caja in cajas) * { * caja.UpdateMeshTransform(); * * caja.Effect.SetValue("lightColor", lightColors); * caja.Effect.SetValue("lightPosition", pointLightPositions); * caja.Effect.SetValue("lightIntensity", pointLightIntensity); * caja.Effect.SetValue("lightAttenuation", pointLightAttenuation); * caja.Effect.SetValue("materialEmissiveColor", Color.Black.ToArgb()); * caja.Effect.SetValue("materialDiffuseColor", Color.White.ToArgb()); * * caja.render(); * }*/ /* * foreach(TgcMesh m in piso.MeshInstances) * { * m.Effect.SetValue("lightColor", lightColors); * m.Effect.SetValue("lightPosition", pointLightPositions); * m.Effect.SetValue("lightIntensity", pointLightIntensity); * m.Effect.SetValue("lightAttenuation", pointLightAttenuation); * m.Effect.SetValue("materialEmissiveColor", Color.Black.ToArgb()); * m.Effect.SetValue("materialDiffuseColor", Color.White.ToArgb()); * * m.render(); * }*/ piso.render(); moto.render(); controladorIA.renderOponentes(); skyBoxTron.render(); foreach (TgcMesh caja in cajas) { caja.render(); } if (perdido) { texto.render(); } if (moto.esDios()) { textoModoDios.render(); } //cajaConLuz.render(); gestorPowerUps.render(ElapsedTime); PostRender(); }
private void cargarShaders() { efectoShaderEnvironmentMap = TgcShaders.loadEffect(this.ShadersDir + "EnvMap.fx"); }
public override void Init() { var d3dDevice = D3DDevice.Instance.Device; moto = new Moto(MediaDir, new Vector3(0, 0, 0)); moto.init(); texturaPiso = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "SkyBoxTron\\bottom.png"); pisoPlane = new TgcPlane(); pisoPlane.Origin = new Vector3(-5000, 0, -5000); pisoPlane.Size = new Vector3(10000, 0, 10000); pisoPlane.Orientation = TgcPlane.Orientations.XZplane; pisoPlane.setTexture(texturaPiso); pisoPlane.updateValues(); piso = pisoPlane.toMesh("piso"); piso.AutoTransformEnable = true; camaraInterna = new camara(moto); Camara = camaraInterna; camaraInterna.rotateY(FastMath.ToRad(180)); skyBoxTron = new SkyBox(MediaDir); skyBoxTron.init(); texto = new TgcText2D(); texto.Color = Color.Red; texto.Align = TgcText2D.TextAlign.LEFT; texto.Text = "Perdiste, toca la tecla R para reiniciar"; texto.Size = new Size(700, 400); texto.Position = new Point(550, 150); textoModoDios = new TgcText2D(); textoModoDios.Color = Color.Red; textoModoDios.Text = "Modo Dios Activado"; textoModoDios.Position = new Point(0, 30); textoModoDios.Size = new Size(500, 200); controladorIA = new ControladorIA(); this.generarOponentes(); perdido = false; cajas = new List <TgcMesh>(); cajaConLuz = new TgcSceneLoader().loadSceneFromFile(MediaDir + Game.Default.pathCajaMetalica).Meshes[0]; cajaConLuz.Position = new Vector3(0, 0, -200); cajaConLuz.Scale = new Vector3(0.8f, 0.8f, 0.8f); efectoLuz = TgcShaders.loadEffect(ShadersDir + "MultiDiffuseLights.fx"); this.generarCajas(100); controladorIA.setObstaculosEscenario(cajas); gestorPowerUps = new GestorPowerUps(); mp3Player = new TgcMp3Player(); mp3Player.closeFile(); mp3Player.FileName = MediaDir + Game.Default.pathMusica; mp3Player.play(true); }
public override void Init() { var d3dDevice = D3DDevice.Instance.Device; deviceMusica = DirectSound.DsDevice; this.FixedTickEnable = false; GameModel.instancia = this; musicaMenu = new Sonido("SonidoPruebaTGC(Mono).wav", true); musicaFondoOutdoor = new Sonido("nocturno, continuo.wav", -3000, true); estatica = new Sonido("Radio Static-SoundBible.com-629277574.wav", -2500, true); agarrarPagina = new Sonido("Page_Turn-Mark_DiAngelo-1304638748.wav", -300, false); humanHeartbeat = new Sonido("human-heartbeat-daniel_simon.wav", -1000, false); respiracion = new Sonido("Breathing Vent-SoundBible.com-18702822.wav", -600, false); //CreateFullScreenQuad(); CreateRenderTarget(); personaje = new Personaje(); menu.instanciarMenu(); nota.instanciarNotas(0); vidaUtilVela.instanciarVelas(0); velita.instanciarVelita(); vidaUtilLinterna.instanciarLinternas(0); linternita.instanciarLinternita(); InstanciarSonidosRandoms(); InstanciarSonidosOutDoorRandoms(); InstanciasSonidosInDoorRandoms(); escenario.InstanciarEstructuras(); monster = new Monster(); monster.InstanciarMonster(monstruoActual); CrearObjetosEnEscenario(); //iluminables.Add(monster.ghost); //iluminables.AddRange(escenario.tgcScene.Meshes); TgcMesh mesh1 = escenario.tgcScene.Meshes.Find(mesh => mesh.Name.Equals("linterna_1")); TgcMesh mesh2 = escenario.tgcScene.Meshes.Find(mesh => mesh.Name.Equals("linterna_2")); var linterna = new Linterna(mesh1, mesh2, this); objetosInteractuables.Add(linterna); Camera = personaje; quads = new List <FullscreenQuad>(); //ShadersDir effectPosProcesado = TGCShaders.Instance.LoadEffect(ShadersDir + "PostProcesado.fx"); effectPosProcesado.Technique = "PostProcessDefault"; var unQuad = new FullscreenQuad(effectPosProcesado); unQuad.loEstoyUsando = true; this.quads.Add(unQuad); sombras = new Sombras(this); sombras.InstanciarSombras(); this.renderizado = sombras; monsterBlur = new MonsterBlur(escenario, this); monsterBlur.instanciarMonsterBlur(ShadersDir, monster, MediaDir); }
public override void Init() { MyMediaDir = MediaDir + "WorkshopShaders\\"; MyShaderDir = ShadersDir + "WorkshopShaders\\"; //Crear loader var loader = new TgcSceneLoader(); // Cargo la escena del cornell box. scene = loader.loadSceneFromFile(MyMediaDir + "cornell_box\\cornell_box-TgcScene.xml"); mesh = scene.Meshes[0]; //Cargar Shader personalizado effect = TgcShaders.loadEffect(MyShaderDir + "PhongShading.fx"); // Pasos standard: // le asigno el efecto a la malla mesh.Effect = effect; mesh.Technique = "DefaultTechnique"; Modifiers.addVertex3f("LightPosition", new Vector3(-100, -100, -100), new Vector3(100, 100, 100), new Vector3(0, 40, 0)); Modifiers.addFloat("Ambient", 0, 1, 0.5f); Modifiers.addFloat("Diffuse", 0, 1, 0.6f); Modifiers.addFloat("Specular", 0, 1, 0.5f); Modifiers.addFloat("SpecularPower", 1, 100, 16); //Crear caja para indicar ubicacion de la luz lightBox = TgcBox.fromSize(new Vector3(5, 5, 5), Color.Yellow); // Creo 3 viewport, para mostrar una comparativa entre los metodos de iluminacion Camara = new TgcRotationalCamera(new Vector3(20, 20, 0), 200); View1 = new Viewport(); View1.X = 0; View1.Y = 0; View1.Width = 400; View1.Height = 250; View1.MinZ = 0; View1.MaxZ = 1; View2 = new Viewport(); View2.X = 0; View2.Y = 250; View2.Width = 400; View2.Height = 250; View2.MinZ = 0; View2.MaxZ = 1; View3 = new Viewport(); View3.X = 400; View3.Y = 0; View3.Width = 400; View3.Height = 250; View3.MinZ = 0; View3.MaxZ = 1; ViewF = D3DDevice.Instance.Device.Viewport; // Creo la luz para el fixed pipeline D3DDevice.Instance.Device.Lights[0].Type = LightType.Point; D3DDevice.Instance.Device.Lights[0].Diffuse = Color.FromArgb(255, 255, 255, 255); D3DDevice.Instance.Device.Lights[0].Specular = Color.FromArgb(255, 255, 255, 255); D3DDevice.Instance.Device.Lights[0].Attenuation0 = 0.0f; D3DDevice.Instance.Device.Lights[0].Range = 50000.0f; D3DDevice.Instance.Device.Lights[0].Enabled = true; }
public override void init() { //GuiController.Instance: acceso principal a todas las herramientas del Framework enemigos = new List<Barco>(); terminoJuego = false; //Device de DirectX para crear primitivas Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice; //Activamos el renderizado customizado. De esta forma el framework nos delega control total sobre como dibujar en pantalla //La responsabilidad cae toda de nuestro lado GuiController.Instance.CustomRenderEnabled = true; g_pCubeMapAgua = TextureLoader.FromCubeFile(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Shaders\\CubeMap.dds"); //sol = TgcBox.fromSize(new Vector3(50, 50, 50), Color.LightYellow); //Cargo la escena completa que tendria que ser la del escenario con el cielo / la del agua //PROXIMAMENTE, ahora cargo otro escenario //Pruebo postprocess lluvia CustomVertex.PositionTextured[] screenQuadVertices = 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 screenQuadVB = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); screenQuadVB.SetData(screenQuadVertices, 0, LockFlags.None); //Creamos un Render Targer sobre el cual se va a dibujar la pantalla renderTarget2D = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); //Cargar shader con efectos de Post-Procesado effectlluvia = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\PostProcess.fx"); //Configurar Technique dentro del shader effectlluvia.Technique = "AlarmaTechnique"; //Cargar textura que se va a dibujar arriba de la escena del Render Target alarmTexture = TgcTexture.createTexture(d3dDevice, GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\rain.png"); //Interpolador para efecto de variar la intensidad de la textura de alarma intVaivenAlarm = new InterpoladorVaiven(); intVaivenAlarm.Min = 0; intVaivenAlarm.Max = 2; intVaivenAlarm.Speed = 10; intVaivenAlarm.reset(); //Modifier para activar/desactivar efecto de alarma GuiController.Instance.Modifiers.addBoolean("activar_efecto", "Activar efecto", true); //termina post process //inicio// spriteFondo = new TgcSprite(); spriteFondo.Texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\MenuPrincipal.jpg"); Size screenSize = GuiController.Instance.Panel3d.Size; Size textureSize = spriteFondo.Texture.Size; spriteFondo.Scaling = new Vector2(1f, 0.8f); spriteFondo.Position = new Vector2(FastMath.Max(screenSize.Width / 2 - textureSize.Width / 2, 0), FastMath.Max(screenSize.Height / 2 - textureSize.Height / 2, 0)); spriteLetras = new TgcSprite(); spriteLetras.Texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\Texto.png"); spriteInicio = new TgcSprite(); spriteInicio.Texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\inicio.png"); spriteLetras.Scaling = new Vector2(0.4f*1.65f, 0.3f*1.65f); Size textureSize2 = spriteLetras.Texture.Size; spriteInicio.Scaling = new Vector2(0.4f, 0.3f); Size textureSize3 = spriteInicio.Texture.Size; spriteTermino = new TgcSprite(); spriteTermino.Texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\termino.png"); //spriteTermino.Scaling = new Vector2(0.5f,0.5f); spriteTermino.Position = new Vector2(screenSize.Width / 4, screenSize.Height / 2); spriteLetras.Position = new Vector2(FastMath.Max(screenSize.Width / 2 - textureSize2.Width / 2, 0), FastMath.Max(screenSize.Height / 2 - textureSize2.Height / 2, 0)); spriteLetras.Position = new Vector2(spriteLetras.Position.X + 110, spriteLetras.Position.Y); spriteInicio.Position = new Vector2(FastMath.Max(screenSize.Width / 2 - textureSize3.Width / 2, 0), FastMath.Max(screenSize.Height / 2 - textureSize3.Height / 2, 0)); spriteInicio.Position = new Vector2(spriteInicio.Position.X + 210, spriteLetras.Position.Y+95); spriteMinimapa = new TgcSprite(); spriteMinimapa.Texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\minimapa.png"); spriteMinimapa.Scaling = new Vector2(0.2f, 0.2f); Size minimapSize = spriteMinimapa.Texture.Size; spriteMinimapa.Position = new Vector2(FastMath.Max(screenSize.Width - 210, 0), FastMath.Max(screenSize.Height - minimapSize.Height , 0)); spriteBarcoPrincipal = new TgcSprite(); spriteBarcoPrincipal.Texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\pointgreen.png"); spriteBarcoPrincipal.Scaling = new Vector2(0.5f,0.5f); //inicio// //ui sprBarraVida = new TgcSprite(); sprBarraVida.Texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\BarraVacia.png"); Size textureSize4 = sprBarraVida.Texture.Size; sprBarraVida.Scaling = new Vector2(1f, 1f); sprBarraVida.Position = new Vector2(1, 1); sprVidaLLena = new TgcSprite(); sprVidaLLena.Texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\vidallena.png"); Size textureSize5 = sprVidaLLena.Texture.Size; sprVidaLLena.Scaling = new Vector2(1f, 1f); sprVidaLLena.Position = new Vector2(1, 15); //ui Bitmap b = (Bitmap)Bitmap.FromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\wallhaven-276951.jpg"); //"water_water_0056_01_preview.jpg"); b.RotateFlip(RotateFlipType.Rotate90FlipX); textura = Texture.FromBitmap(d3dDevice, b, Usage.None, Pool.Managed); b = (Bitmap)Bitmap.FromFile(GuiController.Instance.ExamplesMediaDir + "Shaders\\BumpMapping_DiffuseMap.jpg"); diffuseMapTexture = Texture.FromBitmap(d3dDevice, b, Usage.None, Pool.Managed); oceano = new SmartTerrain(); //oceano.loadHeightmap(GuiController.Instance.ExamplesMediaDir + "Heighmaps\\" + "TerrainTexture1-256x256.jpg", 30.00f, 1.0f, new Vector3(0, 0, 0)); oceano.loadPlainHeightmap(256, 256, 0, 50.0f, 1.0f, new Vector3(0, 0, 0)); oceano.loadTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\water_water_0056_01_preview.jpg"); TgcSceneLoader loader = new TgcSceneLoader(); //escena = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Scenes\\Isla\\Isla-TgcScene.xml"); //Textura del skybox string texturesPath = GuiController.Instance.ExamplesMediaDir + "Texturas\\Quake\\SkyBox LostAtSeaDay\\"; //Crear SkyBox skyBox = new TgcSkyBox(); skyBox.Center = new Vector3(0, 0, 0); skyBox.Size = new Vector3(10000, 10000, 10000); //Configurar color //skyBox.Color = Color.OrangeRed; //Configurar las texturas para cada una de las 6 caras skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "lostatseaday_up.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "lostatseaday_dn.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "lostatseaday_lf.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "lostatseaday_rt.jpg"); //Hay veces es necesario invertir las texturas Front y Back si se pasa de un sistema RightHanded a uno LeftHanded skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "lostatseaday_bk.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "lostatseaday_ft.jpg"); //Actualizar todos los valores para crear el SkyBox skyBox.updateValues(); //Cargo el mesh del/los barco/s -> porque se carga como escena y no cargo el mesh directamente? TgcScene scene2 = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\Boteconcañon\\BoteConCanion-TgcScene.xml"); mainMesh = scene2.Meshes[0]; mainMesh.Position = new Vector3(-200f,0f, 200f); mainMesh.Scale = new Vector3(2f,2f,2f); TgcScene scene4 = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\Boteconcañon\\BoteConCanion-TgcScene.xml"); meshBot = scene4.Meshes[0]; meshBot.Position = new Vector3(-200f,0f,200f); meshBot.Scale = new Vector3(1.8f, 1.8f, 1.8f); TgcScene scene3 = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\Hacha\\Bala-TgcScene.xml"); balaMesh1 = scene3.Meshes[0]; TgcScene scene5 = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\Hacha\\Hacha-TgcScene.xml"); balaMesh2 = scene5.Meshes[0]; barcoPrincipal = new BarcoPlayer(150, 50, VELOCIDAD_MOVIMIENTO, ACELERACION, VELOCIDAD_ROTACION, mainMesh, 0.06, loader,balaMesh2); //pongo enemigos int rows = 12; float offset = 3000; for (int i = 0; i < rows; i++) { //Crear instancia de modelo TgcMesh instance = meshBot.createMeshInstance(meshBot.Name + i + "_" ); //Desplazarlo instance.move(offset * (FastMath.Cos((float)i * 0.523599f)),0,offset * FastMath.Sin((float)i * 0.523599f)); instance.Scale = new Vector3(1.5f, 1.5f, 1.5f); var barcoenem = new BarcoBot(100, 10, 100, ACELERACION, 18, instance, 0.05, barcoPrincipal, loader,balaMesh1); barcoenem.Mesh.Effect = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\shader_bote.fx"); //efectosAguaIluminacion; barcoenem.Mesh.Technique = GuiController.Instance.Shaders.getTgcMeshTechnique(barcoenem.Mesh.RenderType);//"EnvironmentMapTechnique"; barcoenem.BarcosEnemigos = new List<Barco>(); barcoenem.BarcosEnemigos.Add(barcoPrincipal); enemigos.Add(barcoenem); } //TgcScene scene3 = loader.loadSceneFromFile(GuiController.Instance.ExamplesDir + "Shaders\\WorkshopShaders\\Media\\Piso\\Agua-TgcScene.xml"); //agua = scene3.Meshes[0]; //agua.Scale = new Vector3(25f, 1f, 25f); //agua.Position = new Vector3(0f, 0f, 0f); efectosAguaIluminacion = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\shader_agua.fx"); oceano.Effect = efectosAguaIluminacion; oceano.Technique = "RenderAgua";//"EnvironmentMapTechnique"; //"RenderAgua"; oceano.AlphaBlendEnable = true; //barcoEnemigo = new BarcoBot(100, 35,100, ACELERACION, 18, meshBot, 0.05,barcoPrincipal,loader); barcoPrincipal.BarcosEnemigos = enemigos; // iluminacion en los barcos barcoPrincipal.Mesh.Effect = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "quicksort\\shader_bote.fx");//GuiController.Instance.Shaders.TgcMeshPointLightShader;// efectosAguaIluminacion; //GuiController.Instance.Shaders.TgcMeshPointLightShader;// efectosAguaIluminacion; barcoPrincipal.Mesh.Technique = GuiController.Instance.Shaders.getTgcMeshTechnique(barcoPrincipal.Mesh.RenderType); //"EnvironmentMapTechnique"; //barcoEnemigo.Mesh.Effect = GuiController.Instance.Shaders.TgcMeshPointLightShader; //efectosAguaIluminacion; //barcoEnemigo.Mesh.Technique = GuiController.Instance.Shaders.getTgcMeshTechnique(barcoEnemigo.Mesh.RenderType);//"EnvironmentMapTechnique"; //Camara en tercera persona focuseada en el barco (canoa) //PARA DESARROLLO DEL ESCENARIO ES MEJOR MOVERSE CON ESTA CAMARA GuiController.Instance.FpsCamera.Enable = true; GuiController.Instance.FpsCamera.Velocity = new Vector3(0.0f,0.0f,0.0f); GuiController.Instance.FpsCamera.JumpSpeed = 0f; GuiController.Instance.FpsCamera.setCamera(new Vector3(0f,700f,-2300f), new Vector3(900f, 100f, -300f)); GuiController.Instance.ThirdPersonCamera.rotateY(Geometry.DegreeToRadian(180)); ////GuiController.Instance.Fog.Enabled = true; //GuiController.Instance.Modifiers.addFloat("reflection", 0, 1, 0.35f); //GuiController.Instance.Modifiers.addVertex3f("lightPos", new Vector3(-3000, 0, -3000), new Vector3(3000, 3000, 3000), new Vector3(-300, 1500, 3000)); GuiController.Instance.Modifiers.addColor("lightColor", Color.LightYellow); //GuiController.Instance.Modifiers.addFloat("bumpiness", 0, 1, 1f); GuiController.Instance.Modifiers.addFloat("lightIntensity", 0, 500, 150); GuiController.Instance.Modifiers.addFloat("lightAttenuation", 0.1f, 2, 0.1f); GuiController.Instance.Modifiers.addFloat("specularEx", 0, 100, 20f); GuiController.Instance.Modifiers.addColor("mEmissive", Color.Black); GuiController.Instance.Modifiers.addColor("mAmbient", Color.White); GuiController.Instance.Modifiers.addColor("mDiffuse", Color.White); GuiController.Instance.Modifiers.addColor("mSpecular", Color.White); //Carpeta de archivos Media del alumno //string alumnoMediaFolder = GuiController.Instance.AlumnoEjemplosMediaDir; Mapa.oceano_mesh = oceano; }
private void cargarShaders() { efectoOlas = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "RenderGroup\\shaders\\shaderOlas.fx"); terrain.Effect = efectoOlas; terrain.Technique = "RenderScene"; efectoCascada = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "RenderGroup\\shaders\\shaderCascada.fx"); terrain2.Effect = efectoCascada; terrain2.Technique = "RenderScene"; }