Beispiel #1
0
        public TextureManager()
        {
            device = GlobalRenderSettings.Instance.Device;

            defaultTexture = new Texture(device, 1, 1, 1, Usage.None, Format.X8R8G8B8, Pool.Managed);
            var dataRect = defaultTexture.LockRectangle(0, LockFlags.None);

            dataRect.Data.Write(defaultData, 0, 4);

            enviroMap = new CubeTexture(device, 256, 1, Usage.None, Format.X8R8G8B8, Pool.Managed);
            LoadCubeMapFace(enviroMap, CubeMapFace.NegativeX, "ModelViewer.Resources.landscape_negative_x.png", 256, Format.X8R8G8B8);
            LoadCubeMapFace(enviroMap, CubeMapFace.NegativeY, "ModelViewer.Resources.landscape_negative_y.png", 256, Format.X8R8G8B8);
            LoadCubeMapFace(enviroMap, CubeMapFace.NegativeZ, "ModelViewer.Resources.landscape_negative_z.png", 256, Format.X8R8G8B8);
            LoadCubeMapFace(enviroMap, CubeMapFace.PositiveX, "ModelViewer.Resources.landscape_positive_x.png", 256, Format.X8R8G8B8);
            LoadCubeMapFace(enviroMap, CubeMapFace.PositiveY, "ModelViewer.Resources.landscape_positive_y.png", 256, Format.X8R8G8B8);
            LoadCubeMapFace(enviroMap, CubeMapFace.PositiveZ, "ModelViewer.Resources.landscape_positive_z.png", 256, Format.X8R8G8B8);

            lightDiffuseMap = new CubeTexture(device, 1, 1, Usage.None, Format.X8R8G8B8, Pool.Managed);
            FillLightDiffuseMap(CubeMapFace.NegativeX, 0xFFDDDDDD);
            FillLightDiffuseMap(CubeMapFace.NegativeY, 0xFFCCCCCC);
            FillLightDiffuseMap(CubeMapFace.NegativeZ, 0xFFDDDDDD);
            FillLightDiffuseMap(CubeMapFace.PositiveX, 0xFFDDDDDD);
            FillLightDiffuseMap(CubeMapFace.PositiveY, 0xFFFFFFFF);
            FillLightDiffuseMap(CubeMapFace.PositiveZ, 0xFFDDDDDD);
        }
Beispiel #2
0
        /// <summary>
        /// Unload contents
        /// </summary>
        public override void UnloadContent()
        {
            if (TarnishTexture != null)
            {
                TarnishTexture.Dispose();
            }

            if (CubeTexture != null)
            {
                CubeTexture.Dispose();
            }

            if (Cube != null)
            {
                Cube.Dispose();
            }

            if (Sphere != null)
            {
                Sphere.Dispose();
            }

            if (Skybox != null)
            {
                Skybox.Dispose();
            }

            if (Reflection != null)
            {
                Reflection.Dispose();
            }
        }
        public void Run(OpsContext context, OpsStatement statement)
        {
            TexFormatArgs args = statement.Arguments as TexFormatArgs;

            ArrayList containers = statement.GetContent(context);

            OpsConsole.WriteLine("Changing texture formats to " + args.Format);

            foreach (OpsTexture container in containers)
            {
                if (container.Texture is Texture)
                {
                    Texture            oldTexture = container.Texture as Texture;
                    SurfaceDescription sd         = oldTexture.GetLevelDescription(0);

                    container.Texture = OpsTextureHelper.CloneTexture(oldTexture, sd.Width, sd.Height, oldTexture.LevelCount, args.Format, Usage.None, Filter.Triangle | Filter.Dither | (container.SRGB?Filter.Srgb:0), Pool.Managed);
                }
                else if (container.Texture is VolumeTexture)
                {
                    VolumeTexture     oldTexture = container.Texture as VolumeTexture;
                    VolumeDescription vd         = oldTexture.GetLevelDescription(0);

                    container.Texture = OpsTextureHelper.CloneVolume(oldTexture, vd.Width, vd.Height, vd.Depth, oldTexture.LevelCount, args.Format, Usage.None, Filter.Triangle | Filter.Dither | (container.SRGB?Filter.Srgb:0), Pool.Managed);
                }
                else if (container.Texture is CubeTexture)
                {
                    CubeTexture        oldTexture = container.Texture as CubeTexture;
                    SurfaceDescription sd         = oldTexture.GetLevelDescription(0);

                    container.Texture = OpsTextureHelper.CloneCube(oldTexture, sd.Width, oldTexture.LevelCount, args.Format, Usage.None, Filter.Triangle | Filter.Dither | (container.SRGB?Filter.Srgb:0), Pool.Managed);
                }
            }
        }
Beispiel #4
0
    // Use this for initialization
    void Start()
    {
        TextureLoader.Load();
        var path = "/Users/alexis/Desktop/base.json";
        var sw   = File.CreateText(path);

        var cubeTexture = new CubeTexture();

        cubeTexture.FaceBack   = new Vector2(0, 0);
        cubeTexture.FaceRight  = new Vector2(0, 0);
        cubeTexture.FaceFront  = new Vector2(0, 0);
        cubeTexture.FaceLeft   = new Vector2(0, 0);
        cubeTexture.FaceTop    = new Vector2(0, 0);
        cubeTexture.FaceBottom = new Vector2(0, 0);

        cubeTexture.TextureTileSet = "http://mon.addresse.fr/mon.fichier.json";
        cubeTexture.isLocal        = false;

        cubeTexture.Author      = "Alex";
        cubeTexture.TextureName = "First Cube";

        sw.Write(JsonUtility.ToJson(cubeTexture, true));
        sw.Flush();
        sw.Close();
    }
Beispiel #5
0
        /// <summary>
        /// The device exists, but may have just been Reset().  Resources in
        /// Pool.Default and any other device state that persists during
        /// rendering should be set here.  Render states, matrices, textures,
        /// etc., that don't change during rendering can be set once here to
        /// avoid redundant state setting during Render() or FrameMove().
        /// </summary>
        protected override void RestoreDeviceObjects(object sender, System.EventArgs e)
        {
            // InitializeDeviceObjects for file objects (build textures and vertex buffers)
            skyBox.RestoreDeviceObjects(device, null);

            // Create the cubemap
            cubeTex = new CubeTexture(device, 256, 1, Usage.RenderTarget, device.PresentationParameters.BackBufferFormat, Pool.Default);

            // Set default render states
            device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor;
            device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse;
            device.TextureState[0].ColorOperation = TextureOperation.SelectArg1;
            device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor;
            device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse;
            device.TextureState[0].AlphaOperation = TextureOperation.SelectArg1;
            device.SamplerState[0].AddressU       = TextureAddress.Mirror;
            device.SamplerState[0].AddressV       = TextureAddress.Mirror;
            device.SamplerState[0].MinFilter      = TextureFilter.Linear;
            device.SamplerState[0].MagFilter      = TextureFilter.Linear;
            device.SamplerState[0].MipFilter      = TextureFilter.None;

            // Set the transforms
            Vector3 eyeVector    = new Vector3(0.0f, 0.0f, -5.0f);
            Vector3 lookAtVector = new Vector3(0.0f, 0.0f, 0.0f);
            Vector3 upVector     = new Vector3(0.0f, 1.0f, 0.0f);

            Matrix matView, matProj;

            matView = Matrix.LookAtLH(eyeVector, lookAtVector, upVector);
            matProj = Matrix.OrthoLH(2.0f, 2.0f, 0.5f, 100.0f);
            device.Transform.World      = Matrix.Identity;
            device.Transform.View       = matView;
            device.Transform.Projection = matProj;
        }
        /// <summary>Create a cube texture from a file</summary>
        public CubeTexture CreateCubeTextureFromFileEx(Device device, string filename, int size, int mip, Usage usage, Format fmt, Pool pool, Filter filter, Filter mipfilter, int colorkey)
        {
            // Search the cache first
            foreach (CachedTexture ct in textureCache.Keys)
            {
                if ((string.Compare(ct.Source, filename, true) == 0) &&
                    ct.Width == size &&
                    ct.MipLevels == mip &&
                    ct.Usage == usage &&
                    ct.Format == fmt &&
                    ct.Pool == pool &&
                    ct.Type == ResourceType.CubeTexture)
                {
                    // A match was found, return that
                    return(textureCache[ct] as CubeTexture);
                }
            }

            // No matching entry, load the resource and add it to the cache
            CubeTexture   t     = TextureLoader.FromCubeFile(device, filename, size, mip, usage, fmt, pool, filter, mipfilter, colorkey);
            CachedTexture entry = new CachedTexture();

            entry.Source    = filename;
            entry.Width     = size;
            entry.MipLevels = mip;
            entry.Usage     = usage;
            entry.Format    = fmt;
            entry.Pool      = pool;
            entry.Type      = ResourceType.CubeTexture;

            textureCache.Add(entry, t);

            return(t);
        }
Beispiel #7
0
        public Oceano(int size, int cuadSize, CubeTexture cubeMap)
        {
            this.cubeMap = cubeMap;
            //{ 0.042, 20, 0.5, float2(1, 0) }
            waves[0].freq = 0.0125f;
            waves[0].amp = 75;
            waves[0].phase = 0.5f;
            waves[0].dir = new Vector2(0, 1);
            //{ 0.005, 30, 0.35, float2(0.9, 0.3) },
            waves[1].freq = 0.005f;
            waves[1].amp = 35;
            waves[1].phase = 0.25f;
            waves[1].dir = new Vector2(0.9f, 0.3f);
            //{ 0.25, 0.25, 4.5, float2(0, 1) }
            //{ 0.29, 0.25, 4.75, float2(1, 0) }

            //Modifiers
            //Modifiers de la luz
            GuiController.Instance.Modifiers.addVertex2f("1) Dirección", new Vector2(-1, -1), new Vector2(1, 1), waves[0].dir);
            GuiController.Instance.Modifiers.addFloat("1) Amplitud", 0, 200, waves[0].amp);
            GuiController.Instance.Modifiers.addFloat("1) Frecuencia", 0, 1250, waves[0].freq * freqMult);
            GuiController.Instance.Modifiers.addFloat("1) Fase", 0, 3, waves[0].phase);
            GuiController.Instance.Modifiers.addVertex2f("2) Dirección", new Vector2(-1, -1), new Vector2(1, 1), waves[1].dir);
            GuiController.Instance.Modifiers.addFloat("2) Amplitud", 0, 200, waves[1].amp);
            GuiController.Instance.Modifiers.addFloat("2) Frecuencia", 0, 1250, waves[1].freq * freqMult);
            GuiController.Instance.Modifiers.addFloat("2) Fase", 0, 3, waves[1].phase);

            this.size = size;
            this.radio = size / 2;
            this.cuadSize = cuadSize;
            d3dDevice = GuiController.Instance.D3dDevice;
            this.effect = TgcShaders.loadEffect(EjemploAlumno.media() + "Shaders\\agua.fx");
            center = new Vector2(0, 0);
            createVertexBuffer(size, cuadSize);
        }
Beispiel #8
0
        public override void Initialize(DrawArgs drawArgs)
        {
            base.Initialize(drawArgs);
            Device device = drawArgs.device;
            //load the mesh

            //Vertex elements that describe the new format of the mesh
            VertexElement[] elements = new VertexElement[]
			{
				new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
				new VertexElement(0, 12, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0),
				new VertexElement(0, 24, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
				new VertexElement(0, 36, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Tangent, 0),
				new VertexElement(0, 48, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Binormal, 0),
				VertexElement.VertexDeclarationEnd,
			};
            VertexDeclaration decl = new VertexDeclaration(device, elements);
            Mesh tempMesh = this.m_meshElems[0].mesh.Clone(MeshFlags.Managed, elements, device);
            this.m_meshElems[0].mesh.Dispose();
            this.m_meshElems[0].mesh = tempMesh;

            /* Performs tangent frame computations on a mesh. Tangent, binormal, and optionally normal vectors are generated. 
              * Singularities are handled as required by grouping edges and splitting vertices.
             */
            this.m_meshElems[0].mesh.ComputeTangentFrame(0);

            //load the effect
            this.effect = Effect.FromFile(device, this.effectFilename, null, null, ShaderFlags.Debug | ShaderFlags.PartialPrecision, null);

            //load the texture
            this.texCube = TextureLoader.FromCubeFile(device, cloudFilename);
            this.texture = TextureLoader.FromFile(device, textureFilename);
            this.isInitialized = true;
        }
Beispiel #9
0
        /*
		public void Render(Device device, Texture waterTexture)
		{
			float time = (float)(Environment.TickCount * 0.001);
			waterTime += 0.002f;
			//Calculate the matrices
			Matrix modelViewProj = matWorld * matView * matProj;
			Matrix modelViewIT = matWorld * matView * matProj;
			modelViewIT.Invert();
			modelViewIT = Matrix.TransposeMatrix(modelViewIT);
			//set the technique
			effect.Technique = "water";
			//set the texturs
			effect.SetValue("texture0", waterTexture);
			effect.SetValue("texture1", texCube);
			//set the matrices
			effect.SetValue("ModelViewProj", modelViewProj);
			effect.SetValue("ModelWorld", matWorld);
			//set eye position
			effect.SetValue("eyePos", new Vector4(450.0f, 250.0f, 750.0f, 1.0f));
			//set the light position
			effect.SetValue("lightPos", new Vector4((float)(300 * Math.Sin(time)), 40.0f, (float)(300 * Math.Cos(time)), 1.0f));
			//set the time
			effect.SetValue("time", waterTime);

			//render the effect
			//device.SetRenderState(RenderState.AlphaBlendEnable , true);
			effect.Begin(0);
			effect.BeginPass(0);
			mesh.DrawSubset(0);
			effect.EndPass();
			effect.End();
			//device.SetRenderState(RenderState.AlphaBlendEnable , false);
		}
        */
        public override void Dispose()
        {
            //set initialization state to false
            this.isInitialized = false;
            
            //Dispose Textures
            if (this.texCube != null)
            {
                this.texCube.Dispose();
                this.texCube = null;
            }
            if (this.texture != null)
            {
                this.texture.Dispose();
                this.texture = null;
            }
            //Dispose Effects
            if (this.effect != null)
            {
                this.effect.Dispose();
                this.effect = null;
            }
            //Dispose Mesh
            base.Dispose();
        }
Beispiel #10
0
        /// <summary>Set up the cube map by rendering the scene into it</summary>
        private void RenderSceneIntoCubeMap(Device device, double totalTime, float elapsedTime, Vector3 position)
        {
            if (invalidated)
            {
                rendering = true;
                CameraBase cam = Framework.Instance.CurrentCamera;
                cubeCamera.LookFrom = position;
                Framework.Instance.CurrentCamera = cubeCamera;
                for (int f = 0; f < 6; ++f)
                {
                    CubeTexture cubeTex = cubeTexture.Texture as CubeTexture;
                    using (Surface s = cubeTex.GetCubeMapSurface((CubeMapFace)f, 0))
                    {
                        SetCubeMapCamera((CubeMapFace)f);

                        renderHelper.BeginScene(s);
                        cubeCamera.OnFrameMove(device, totalTime, elapsedTime);
                        cubeCamera.OnFrameRender(device, totalTime, elapsedTime);
                        if (OnFrameRenderMethod != null)
                        {
                            OnFrameRenderMethod(device, totalTime, elapsedTime);
                        }
                        device.Transform.World = Matrix.Identity;
                        renderHelper.EndScene(Filter.None);
                    }
                }
                Framework.Instance.CurrentCamera = cam;
                Framework.Instance.CurrentCamera.OnFrameRender(device, totalTime, elapsedTime);
                rendering   = false;
                invalidated = false;
            }
        }
Beispiel #11
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            await Init();

            GpuFence fence             = Device.DefaultQueue.CreateFence();
            UInt64   currentFenceValue = 0;

            while (true)
            {
                if (SwapChain == null)
                {
                    SwapChainDescriptor = new GpuSwapChainDescriptor(GpuTextureFormat.BGRA8UNorm, (uint)GpuView.Width, (uint)GpuView.Height);
                    SwapChain           = Device.ConfigureSwapChainForSwapChainPanel(SwapChainDescriptor, GpuView);
                    DepthTexture        = Device.CreateTexture(new GpuTextureDescriptor(new GpuExtend3DDict {
                        Width = SwapChainDescriptor.Width, Height = SwapChainDescriptor.Height, Depth = 1
                    }, GpuTextureFormat.Depth24PlusStencil8, GpuTextureUsageFlags.OutputAttachment));
                    CubeTexture = Device.CreateTexture(new GpuTextureDescriptor(new GpuExtend3DDict {
                        Width = SwapChainDescriptor.Width, Height = SwapChainDescriptor.Height, Depth = 1
                    }, GpuTextureFormat.BGRA8UNorm, GpuTextureUsageFlags.Sampled | GpuTextureUsageFlags.CopyDst));
                    UniformBindGroup = Device.CreateBindGroup(new GpuBindGroupDescriptor(UniformBindGroupLayout, new GpuBindGroupEntry[]
                    {
                        new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, UniformBufferSize)),
                        new GpuBindGroupEntry(1, Sampler),
                        new GpuBindGroupEntry(2, CubeTexture.CreateView())
                    }));
                }
                DrawFrame();
                var fenceValueWaitFor = ++currentFenceValue;
                Device.DefaultQueue.Signal(fence, fenceValueWaitFor);
                await fence.OnCompletionAsync(fenceValueWaitFor);
            }
        }
Beispiel #12
0
        public override void LoadResources()
        {
            string base_path = (string)settings["Base.Path"];

            string errors;

            pEffect = Effect.FromFile(device, base_path + "Media/Effects/Blobs.fx", null, null, ShaderFlags.NotCloneable, null, out errors);

            if (errors.Length > 0)
            {
                throw new Exception("HLSL compile error");
            }

            // Initialize the technique for blending
            if (nPasses == 1)
            {
                // Multiple RT available
                hBlendTech = pEffect.GetTechnique("BlobBlend");
            }
            else
            {
                // Single RT. Multiple passes.
                hBlendTech = pEffect.GetTechnique("BlobBlendTwoPasses");
            }

            // Create the environment map
            pEnvMap = TextureLoader.FromCubeFile(device, base_path + "Media/Effects/LobbyCube.dds");
        }
Beispiel #13
0
        public static void CopyToCubeSide(OpsContext context, CubeTexture newTexture, string srcArg, CubeMapFace face, Filter filter)
        {
            if (srcArg == null || srcArg.Length == 0)
            {
                return;
            }

            OpsTexture src = context.GetTexture(srcArg);

            if (src == null)
            {
                throw new OpsException("Could not find source texture: " + srcArg);
            }

            if (src.Texture is CubeTexture)
            {
                SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(face, 0), ((CubeTexture)src.Texture).GetCubeMapSurface(face, 0), filter | (src.SRGB?Filter.SrgbIn:0), 0);
            }
            else if (src.Texture is Texture)
            {
                SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(face, 0), ((Texture)src.Texture).GetSurfaceLevel(0), filter | (src.SRGB?Filter.SrgbIn:0), 0);
            }
            else
            {
                throw new OpsException("Source texture is not a texture2D: " + srcArg);
            }
        }
        private void DumpCubeTexture(NovaTexture texture, BabylonTexture babylonTexture, BabylonScene babylonScene)
        {
            var textureFilename = Path.Combine(texture.LoadedTexture.Directory, texture.LoadedTexture.Filename);
            var baseName        = Path.GetFileNameWithoutExtension(texture.LoadedTexture.Filename);

            babylonTexture.isCube = true;
            babylonTexture.name   = baseName;

            baseName = Path.Combine(babylonScene.OutputPath, baseName);

            if (!File.Exists(textureFilename))
            {
                texture.LoadedTexture.SaveToDDS(false, textureFilename);
            }

            if (!alreadyExportedTextures.Contains(textureFilename))
            {
                alreadyExportedTextures.Add(textureFilename);

                // Use SharpDX to extract face images
                var form = new Form {
                    ClientSize = new Size(64, 64)
                };
                var device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle,
                                        CreateFlags.HardwareVertexProcessing,
                                        new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

                var cubeTexture = CubeTexture.FromFile(device, textureFilename);

                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.PositiveX, 0))
                {
                    Surface.ToFile(surface, baseName + "_px.jpg", ImageFileFormat.Jpg);
                }
                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.PositiveY, 0))
                {
                    Surface.ToFile(surface, baseName + "_py.jpg", ImageFileFormat.Jpg);
                }
                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.PositiveZ, 0))
                {
                    Surface.ToFile(surface, baseName + "_pz.jpg", ImageFileFormat.Jpg);
                }
                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.NegativeX, 0))
                {
                    Surface.ToFile(surface, baseName + "_nx.jpg", ImageFileFormat.Jpg);
                }
                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.NegativeY, 0))
                {
                    Surface.ToFile(surface, baseName + "_ny.jpg", ImageFileFormat.Jpg);
                }
                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.NegativeZ, 0))
                {
                    Surface.ToFile(surface, baseName + "_nz.jpg", ImageFileFormat.Jpg);
                }

                cubeTexture.Dispose();
                device.Dispose();
                form.Dispose();
            }
        }
        public void SetRenderTarget(CubeTexture environmentRT, CubeTexture ambientRT, Texture fullSizeRT)
        {
            m_setup.RenderTargets[0] = fullSizeRT;

            m_environmentRT = environmentRT;
            m_ambientRT     = ambientRT;
            m_fullSizeRT    = fullSizeRT;
        }
Beispiel #16
0
        /// <summary>
        /// Handle the device reset event, recreate our
        /// environment maps
        /// </summary>
        private void OnDeviceReset(object sender, EventArgs e)
        {
            Device dev = (Device)sender;

            rte = new RenderToEnvironmentMap(dev, CubeMapSize, 1,
                                             Format.X8R8G8B8, true, DepthFormat.D16);

            environment = new CubeTexture(dev, CubeMapSize, 1,
                                          Usage.RenderTarget, Format.X8R8G8B8, Pool.Default);
        }
Beispiel #17
0
        private void CreateCubeTexture(Device device)
        {
            CubeTexture = new CubeTexture(device, _edgeSize, 1, _usage, _format, _pool);

            CubeMapSurface = new ISurface[6];
            for (var i = 0; i < 6; i++)
            {
                CubeMapSurface[i] = WrappedSurface.CubeMapSurface((CubeMapFaceEnum) i, this);
            }
        }
        static void CreateRenderTargetCube(MyRenderTargets renderTarget, int size, Format surfaceFormat)
        {
            DisposeRenderTarget(renderTarget);
            if (size <= 0)
            {
                return;
            }

            m_renderTargets[(int)renderTarget]           = new CubeTexture(GraphicsDevice, size, 0, Usage.RenderTarget | Usage.AutoGenerateMipMap, surfaceFormat, Pool.Default);
            m_renderTargets[(int)renderTarget].DebugName = renderTarget.ToString();
        }
Beispiel #19
0
        public void Run(OpsContext context, OpsStatement statement)
        {
            OpsConsole.WriteLine("Texture information");
            OpsConsole.WriteLine(format, "Names", "Type", "Width", "Height", "Depth", "Mips", "Format");

            foreach (OpsTexture container in statement.GetContent(context))
            {
                string name        = container.Name;
                string type        = container.Texture.GetType().Name;
                int    width       = 0;
                int    height      = 0;
                int    depth       = 0;
                int    mips        = 0;
                string pixelFormat = "";

                if (container.Texture is Texture)
                {
                    Texture            texture = container.Texture as Texture;
                    SurfaceDescription sd      = texture.GetLevelDescription(0);
                    width       = sd.Width;
                    height      = sd.Height;
                    mips        = texture.LevelCount;
                    pixelFormat = sd.Format.ToString();
                }
                else if (container.Texture is VolumeTexture)
                {
                    VolumeTexture     texture = container.Texture as VolumeTexture;
                    VolumeDescription vd      = texture.GetLevelDescription(0);
                    width       = vd.Width;
                    height      = vd.Height;
                    depth       = vd.Depth;
                    mips        = texture.LevelCount;
                    pixelFormat = vd.Format.ToString();
                }
                else if (container.Texture is CubeTexture)
                {
                    CubeTexture        texture = container.Texture as CubeTexture;
                    SurfaceDescription sd      = texture.GetLevelDescription(0);
                    width       = sd.Width;
                    height      = sd.Height;
                    mips        = texture.LevelCount;
                    pixelFormat = sd.Format.ToString();
                }

                OpsConsole.WriteLine(format,
                                     name,
                                     type,
                                     width,
                                     height,
                                     depth,
                                     mips,
                                     pixelFormat);
            }
        }
        /// <summary>
        /// </summary>
        /// <returns>
        /// </returns>
        public override BaseTexture clone()
        {
            var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);

            newTexture.level            = this.level;
            newTexture.wrapU            = this.wrapU;
            newTexture.wrapV            = this.wrapV;
            newTexture.coordinatesIndex = this.coordinatesIndex;
            newTexture.coordinatesMode  = this.coordinatesMode;
            return(newTexture);
        }
Beispiel #21
0
        public Oceano(float XZ, float Y)
        {
            currentScaleXZ = XZ;
            currentScaleY  = Y;
            //Cargar textura de CubeMap para Environment Map
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;
            cubeMap = TextureLoader.FromCubeFile(d3dDevice, GuiController.Instance.AlumnoEjemplosMediaDir + "RenderGroup\\Shaders\\cubemap-evul2.dds");

            crearModifiers();
            crearHeightmaps();
            cargarShaders();
        }
Beispiel #22
0
        public Oceano(float XZ, float Y)
        {
            currentScaleXZ = XZ;
            currentScaleY = Y;
            //Cargar textura de CubeMap para Environment Map
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;
            cubeMap = TextureLoader.FromCubeFile(d3dDevice, GuiController.Instance.AlumnoEjemplosMediaDir + "RenderGroup\\Shaders\\cubemap-evul2.dds");

            crearModifiers();
            crearHeightmaps();
            cargarShaders();
        }
Beispiel #23
0
 public override void init()
 {
     cubeMap = TextureLoader.FromCubeFile(GuiController.Instance.D3dDevice, EjemploAlumno.media() + "Texturas\\Skybox\\Skybox.dds");
     GuiController.Instance.Modifiers.addBoolean("Lluvia", "Activar Lluvia", false);
     GuiController.Instance.Modifiers.addFloat("Reflexion", 0, 1, 0.2f);
     agua = new Oceano(2000, 25, cubeMap);
     bote = new Bote(agua);
     bote.init();
     lluvia.init();
     Sonido.Init();
     skybox.init();
 }
Beispiel #24
0
        public static CubeTexture CloneCube(CubeTexture oldTexture, int size, int mips, Format format, Usage usage, Filter filter, Pool pool)
        {
            CubeTexture newTexture = new CubeTexture(oldTexture.Device, size, mips, usage, format, pool);

            SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.NegativeX, 0), oldTexture.GetCubeMapSurface(CubeMapFace.NegativeX, 0), filter, 0);
            SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.NegativeY, 0), oldTexture.GetCubeMapSurface(CubeMapFace.NegativeY, 0), filter, 0);
            SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.NegativeZ, 0), oldTexture.GetCubeMapSurface(CubeMapFace.NegativeZ, 0), filter, 0);
            SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.PositiveX, 0), oldTexture.GetCubeMapSurface(CubeMapFace.PositiveX, 0), filter, 0);
            SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.PositiveY, 0), oldTexture.GetCubeMapSurface(CubeMapFace.PositiveY, 0), filter, 0);
            SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.PositiveZ, 0), oldTexture.GetCubeMapSurface(CubeMapFace.PositiveZ, 0), filter, 0);
            return(newTexture);
        }
Beispiel #25
0
        public void Run(OpsContext context, OpsStatement statement)
        {
            Slice2dArgs args = statement.Arguments as Slice2dArgs;

            ArrayList containers = statement.GetContent(context);

            if (containers.Count != 1)
            {
                throw new OpsException("Src argument does not resolve to 1 texture.  Textures found: " + containers.Count);
            }

            OpsTexture container = containers[0] as OpsTexture;

            OpsConsole.WriteLine("Slicing from texture:{0} and saving as {1}", container.Name, args.Dst);

            OpsTexture result = new OpsTexture();

            result.Name = args.Dst;
            result.SRGB = container.SRGB;

            Texture newTexture = null;

            if (container.Texture is Texture)
            {
                Texture            srcTexture = container.Texture as Texture;
                SurfaceDescription sd         = srcTexture.GetLevelDescription(args.Mips);

                newTexture = new Texture(srcTexture.Device, sd.Width, sd.Height, 1, Usage.None, sd.Format, Pool.Managed);
                SurfaceLoader.FromSurface(newTexture.GetSurfaceLevel(0), srcTexture.GetSurfaceLevel(0), Filter.Dither | Filter.Triangle | (container.SRGB?Filter.Srgb:0), 0);
            }
            else if (container.Texture is VolumeTexture)
            {
                VolumeTexture     srcTexture = container.Texture as VolumeTexture;
                VolumeDescription vd         = srcTexture.GetLevelDescription(args.Mips);

                newTexture = new Texture(srcTexture.Device, vd.Width, vd.Height, 1, Usage.None, vd.Format, Pool.Managed);
                OpsTextureHelper.LoadSurfaceFromVolumeSlice(srcTexture, args.Mips, args.Volume, Filter.Dither | Filter.Triangle | (container.SRGB?Filter.Srgb:0), newTexture.GetSurfaceLevel(0));
            }
            else if (container.Texture is CubeTexture)
            {
                CubeTexture        srcTexture = container.Texture as CubeTexture;
                SurfaceDescription sd         = srcTexture.GetLevelDescription(args.Mips);

                newTexture = new Texture(srcTexture.Device, sd.Width, sd.Height, 1, Usage.None, sd.Format, Pool.Managed);
                SurfaceLoader.FromSurface(newTexture.GetSurfaceLevel(0), srcTexture.GetCubeMapSurface(args.Face, 0), Filter.Dither | Filter.Triangle | (container.SRGB?Filter.Srgb:0), 0);
            }

            result.Texture = newTexture;

            context.AddTexture(result);
        }
Beispiel #26
0
        private void LoadCubeMapFace(CubeTexture tex, CubeMapFace face, string fileName, int size, Format format)
        {
            var data = Surface.CreateOffscreenPlain(device, size, size, format, Pool.Scratch);

            Surface.FromFileInStream(data, this.GetType().Assembly.GetManifestResourceStream(fileName), Filter.None, 0);
            var dstRect = tex.LockRectangle(face, 0, LockFlags.None);
            var srcRect = data.LockRectangle(LockFlags.ReadOnly);

            srcRect.Data.CopyTo(dstRect.Data);

            data.UnlockRectangle();
            tex.UnlockRectangle(face, 0);

            data.Dispose();
        }
Beispiel #27
0
        public static void DDSFromFile(string fileName, Device device, bool loadMipMap, int offsetMipMaps, out CubeTexture texture)
        {
            Stream      stream = File.OpenRead(fileName);
            CubeTexture tex    = null;

            InternalDDSFromStream(stream, device, 0, loadMipMap, 0, out tex);
            stream.Close();
            stream.Dispose();

            texture = tex as CubeTexture;
            if (texture == null)
            {
                throw new Exception("Error while loading TextureCube");
            }
        }
Beispiel #28
0
    private void SetTextureSide(Renderer sideRenderer, float number)
    {
        if (mCubeTexture == null)
        {
            mCubeTexture = GameData.Get.CubeTextureData;
            if (mCubeTexture == null)
            {
                Debug.LogError("No textureManager loaded", this);
                return;
            }
        }
        var tex = mCubeTexture.GetTexture((int)number, number - (int)number > 0 ? true: false);

        sideRenderer.material.mainTexture = tex;
    }
Beispiel #29
0
        static void CreateRenderTargetCube(MyRenderTargets renderTarget, int size, Format surfaceFormat)
        {
            MyMwcLog.WriteLine("MyRender.CreateRenderTargetCube - START");

            DisposeRenderTarget(renderTarget);
            if (size <= 0)
            {
                return;
            }

            m_renderTargets[(int)renderTarget]           = new CubeTexture(m_device, size, 0, Usage.RenderTarget, surfaceFormat, Pool.Default);
            m_renderTargets[(int)renderTarget].DebugName = renderTarget.ToString();
            m_renderTargets[(int)renderTarget].Tag       = new Vector2(size, size);

            MyMwcLog.WriteLine("MyRender.CreateRenderTargetCube - END");
        }
Beispiel #30
0
        public void Run(OpsContext context, OpsStatement statement)
        {
            Splice2dArgs args = statement.Arguments as Splice2dArgs;

            ArrayList srcList = statement.GetContent(context);

            if (srcList.Count != 1)
            {
                throw new OpsException("Could not find the source texture.  1 is require but found " + srcList.Count);
            }

            OpsTexture srcContainer = ((OpsTexture)srcList[0]);

            if (!(srcContainer.Texture is Texture))
            {
                throw new OpsException("Source texture is not 2D");
            }

            Texture srcTexture = srcContainer.Texture as Texture;

            OpsConsole.WriteLine("Splicing texture:{0} into one or more textures", srcContainer.Name);


            ArrayList dstContainers = context.FindTextures(args.Dst);

            foreach (OpsTexture dstContainer in dstContainers)
            {
                if (dstContainer.Texture is Texture)
                {
                    Texture dstTexture = dstContainer.Texture as Texture;

                    SurfaceLoader.FromSurface(dstTexture.GetSurfaceLevel(args.Mips), srcTexture.GetSurfaceLevel(0), Filter.Dither | Filter.Triangle | (srcContainer.SRGB?Filter.SrgbIn:0) | (dstContainer.SRGB?Filter.SrgbOut:0), 0);
                }
                else if (dstContainer.Texture is VolumeTexture)
                {
                    VolumeTexture dstTexture = dstContainer.Texture as VolumeTexture;

                    OpsTextureHelper.LoadVolumeSliceFromSurface(dstTexture, args.Mips, args.Volume, Filter.Dither | Filter.Triangle | (srcContainer.SRGB?Filter.SrgbIn:0) | (dstContainer.SRGB?Filter.SrgbOut:0), srcTexture.GetSurfaceLevel(0));
                }
                else if (dstContainer.Texture is CubeTexture)
                {
                    CubeTexture dstTexture = dstContainer.Texture as CubeTexture;

                    SurfaceLoader.FromSurface(dstTexture.GetCubeMapSurface(args.Face, args.Mips), srcTexture.GetSurfaceLevel(0), Filter.Dither | Filter.Triangle | (srcContainer.SRGB?Filter.SrgbIn:0) | (dstContainer.SRGB?Filter.SrgbOut:0), 0);
                }
            }
        }
Beispiel #31
0
        /// <summary>
        /// Crea el SkyDome.
        /// </summary>
        public static void Cargar()
        {
            Textura = TextureLoader.FromCubeFile(GuiController.Instance.D3dDevice, Utiles.TexturasDir("cubemap-evul.dds"));

            VerticesBuffer = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), NivelDeDetalle * NivelDeDetalle * CustomVertex.PositionNormalTextured.StrideSize, GuiController.Instance.D3dDevice, Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default);
            Vertices       = new CustomVertex.PositionNormalTextured[NivelDeDetalle * NivelDeDetalle];
            for (int v = 0; v < NivelDeDetalle; v++)
            {
                for (int u = 0; u < NivelDeDetalle; u++)
                {
                    // Alpha es el desplazamiento horizontal
                    float al = (float)(-2.0f * Math.PI * ((float)u / (NivelDeDetalle - 1.0f)));
                    // Theta es el desplazamiento vertical
                    float th = (float)(0.6f * Math.PI * ((float)v / (NivelDeDetalle - 1.0f)));
                    // Armo los vertices para el domo
                    Vertices[v * NivelDeDetalle + u].X = (float)(Math.Sin(th) * Math.Sin(al));
                    Vertices[v * NivelDeDetalle + u].Y = (float)Math.Cos(th);
                    Vertices[v * NivelDeDetalle + u].Z = (float)(Math.Sin(th) * Math.Cos(al));
                }
            }
            VerticesBuffer.SetData(Vertices, 0, LockFlags.None);

            IndicesBuffer = new IndexBuffer(typeof(int), sizeof(int) * 6 * (NivelDeDetalle - 1) * (NivelDeDetalle - 1), GuiController.Instance.D3dDevice, Usage.WriteOnly, Pool.Default);
            int[] Indices = new int[sizeof(int) * 6 * (NivelDeDetalle - 1) * (NivelDeDetalle - 1)];
            int   i       = 0;

            for (int v = 0; v < NivelDeDetalle - 1; v++)
            {
                for (int u = 0; u < NivelDeDetalle - 1; u++)
                {
                    // Triangulo 1 |/
                    Indices[i++] = v * NivelDeDetalle + u;
                    Indices[i++] = v * NivelDeDetalle + u + 1;
                    Indices[i++] = (v + 1) * NivelDeDetalle + u;

                    // Triangulo 2 /|
                    Indices[i++] = (v + 1) * NivelDeDetalle + u;
                    Indices[i++] = v * NivelDeDetalle + u + 1;
                    Indices[i++] = (v + 1) * NivelDeDetalle + u + 1;
                }
            }
            IndicesBuffer.SetData(Indices, 0, LockFlags.None);

            // Carga el Effect para el SkyDome.
            Shader = Utiles.CargarShaderConTechnique("skybox.fx");
        }
Beispiel #32
0
        private void InitializeTextures()
        {
            var device = D3DDevice.Instance.Device;

            cubeMap = new CubeTexture(device, 512, 0, Usage.RenderTarget | Usage.AutoGenerateMipMap, Format.A16B16G16R16F, Pool.Default);

            for (int stencilForSides = 0; stencilForSides < 6; stencilForSides++)
            {
                depthStencils.Add(device.CreateDepthStencilSurface(512, 512, DepthFormat.D24S8, MultiSampleType.None, 0, true));
            }

            irradianceMap = new CubeTexture(device, 32, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);

            prefilterMap = new CubeTexture(device, 128, 0, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);

            bdrfLUT = new Texture(device, 512, 512, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);
        }
Beispiel #33
0
        private void GenerateGaussianTexture()
        {
            Surface pBlobTemp = null;
            Surface pBlobNew  = null;

            // Create a temporary texture
            Texture texTemp;

            texTemp = new Texture(device, GAUSSIAN_TEXSIZE, GAUSSIAN_TEXSIZE, 1, Usage.Dynamic, Format.R32F, Pool.Default);
            // Create the gaussian texture
            pTexBlob = new Texture(device, GAUSSIAN_TEXSIZE, GAUSSIAN_TEXSIZE, 1, Usage.Dynamic, blobTexFormat, Pool.Default);

            // Create the environment map
            pEnvMap = TextureLoader.FromCubeFile(device, "../../../Media/LobbyCube.dds");

            // Fill in the gaussian texture data
            GraphicsStream Rect = texTemp.LockRectangle(0, LockFlags.None);
            int            u, v;
            float          dx, dy, I;

            for (v = 0; v < GAUSSIAN_TEXSIZE; ++v)
            {
                for (u = 0; u < GAUSSIAN_TEXSIZE; ++u)
                {
                    dx = 2.0f * (float)u / (float)GAUSSIAN_TEXSIZE - 1.0f;
                    dy = 2.0f * (float)v / (float)GAUSSIAN_TEXSIZE - 1.0f;
                    I  = GAUSSIAN_HEIGHT * (float)Math.Exp(-((dx * dx) + (dy * dy)) / GAUSSIAN_DEVIATION);

                    //byte[] data = BitConverter.GetBytes(I);
                    Rect.Write(I);//data, 0, data.Length);
                }
            }

            texTemp.UnlockRectangle(0);

            // Copy the temporary surface to the stored gaussian texture
            pBlobTemp = texTemp.GetSurfaceLevel(0);
            pBlobNew  = pTexBlob.GetSurfaceLevel(0);
            SurfaceLoader.FromSurface(pBlobNew, pBlobTemp, Filter.None, 0);
            //SurfaceLoader.Save("c:/gaussdump.dds", ImageFileFormat.Dds, pBlobTemp);
            //SurfaceLoader.FromFile(pBlobNew, "c:/gaussdump.dds", Filter.None, 0);

            pBlobTemp.Dispose();
            pBlobNew.Dispose();
            texTemp.Dispose();
        }
Beispiel #34
0
        protected void UpdateProperties(BaseTexture texture)
        {
            SurfaceDescription desc;
            Texture            tex = texture as Texture;

            if (tex != null)
            {
                desc = tex.GetLevelDescription(0);
            }
            else
            {
                CubeTexture ctex = texture as CubeTexture;
                desc = ctex.GetLevelDescription(0);
            }

            Width  = desc.Width;
            Height = desc.Height;
            Format = desc.Format;
        }
        public TextureManager()
        {
            device = GlobalRenderSettings.Instance.Device;

            defaultTexture = new Texture(device, 1, 1, 1, Usage.None, Format.X8R8G8B8, Pool.Managed);
            var dataRect = defaultTexture.LockRectangle(0, LockFlags.None);
            dataRect.Data.Write(defaultData, 0, 4);

            enviroMap = new CubeTexture(device, 256, 1, Usage.None, Format.X8R8G8B8, Pool.Managed);
            LoadCubeMapFace(enviroMap, CubeMapFace.NegativeX, "ModelViewer.Resources.landscape_negative_x.png", 256, Format.X8R8G8B8);
            LoadCubeMapFace(enviroMap, CubeMapFace.NegativeY, "ModelViewer.Resources.landscape_negative_y.png", 256, Format.X8R8G8B8);
            LoadCubeMapFace(enviroMap, CubeMapFace.NegativeZ, "ModelViewer.Resources.landscape_negative_z.png", 256, Format.X8R8G8B8);
            LoadCubeMapFace(enviroMap, CubeMapFace.PositiveX, "ModelViewer.Resources.landscape_positive_x.png", 256, Format.X8R8G8B8);
            LoadCubeMapFace(enviroMap, CubeMapFace.PositiveY, "ModelViewer.Resources.landscape_positive_y.png", 256, Format.X8R8G8B8);
            LoadCubeMapFace(enviroMap, CubeMapFace.PositiveZ, "ModelViewer.Resources.landscape_positive_z.png", 256, Format.X8R8G8B8);

            lightDiffuseMap = new CubeTexture(device, 1, 1, Usage.None, Format.X8R8G8B8, Pool.Managed);
            FillLightDiffuseMap(CubeMapFace.NegativeX, 0xFFDDDDDD);
            FillLightDiffuseMap(CubeMapFace.NegativeY, 0xFFCCCCCC);
            FillLightDiffuseMap(CubeMapFace.NegativeZ, 0xFFDDDDDD);
            FillLightDiffuseMap(CubeMapFace.PositiveX, 0xFFDDDDDD);
            FillLightDiffuseMap(CubeMapFace.PositiveY, 0xFFFFFFFF);
            FillLightDiffuseMap(CubeMapFace.PositiveZ, 0xFFDDDDDD);
        }
Beispiel #36
0
 public void AttachTexture(CubeTexture tex, CubemapSide side)
 {
     MakeCurrent();
     //OpenGL.glFramebufferTexture(OpenGL.Const.GL_FRAMEBUFFER, OpenGL.Const.GL_COLOR_ATTACHMENT0, tex.Handle, 0, (uint)side);
 }
Beispiel #37
0
 /// <summary>
 /// Set up a new cube map texture for reflections
 /// </summary>
 /// <param name="t"></param>
 public static void SetEnvTexture(CubeTexture t)
 {
     effect.SetValue(envTexture, t);
     // TODO: Add boolean so can switch off if not supported?
 }
        public void Run(OpsContext context, OpsStatement statement)
        {
            NewTexCubeArgs args = statement.Arguments as NewTexCubeArgs;

            OpsConsole.WriteLine( "Creating new cube texture named" + args.Name);

            OpsTexture result = new OpsTexture();
            result.Name = args.Name;
            CubeTexture newTexture =  new CubeTexture( context.Device, args.Size , args.Mips , Usage.None , args.Format , Pool.Managed );
            result.Texture = newTexture;

            CopyToCubeSide( context, newTexture, args.SrcXP, CubeMapFace.PositiveX, Filter.Triangle|Filter.Dither);
            CopyToCubeSide( context, newTexture, args.SrcYP, CubeMapFace.PositiveY, Filter.Triangle|Filter.Dither);
            CopyToCubeSide( context, newTexture, args.SrcZP, CubeMapFace.PositiveZ, Filter.Triangle|Filter.Dither);
            
            CopyToCubeSide( context, newTexture, args.SrcXM, CubeMapFace.NegativeX, Filter.Triangle|Filter.Dither);
            CopyToCubeSide( context, newTexture, args.SrcYM, CubeMapFace.NegativeY, Filter.Triangle|Filter.Dither);
            CopyToCubeSide( context, newTexture, args.SrcZM, CubeMapFace.NegativeZ, Filter.Triangle|Filter.Dither);    

            context.AddTexture(result);
        }
        public override void LoadResources()
        {
            string base_path = (string)settings["Base.Path"];

            string errors;
            pEffect = Effect.FromFile(device, base_path + "Media/Effects/Blobs.fx", null, null, ShaderFlags.NotCloneable, null, out errors);

            if (errors.Length > 0)
                throw new Exception("HLSL compile error");

            // Initialize the technique for blending
            if (nPasses == 1)
            {
                // Multiple RT available
                hBlendTech = pEffect.GetTechnique("BlobBlend");
            }
            else
            {
                // Single RT. Multiple passes.
                hBlendTech = pEffect.GetTechnique("BlobBlendTwoPasses");
            }

            // Create the environment map
            pEnvMap = TextureLoader.FromCubeFile(device, base_path + "Media/Effects/LobbyCube.dds");
        }
 /// <summary>
 /// Inizializza un oggetto CubeMap caricandolo da un file esterno in formato "dds" 
 /// </summary>
 /// <param name="Path"></param>
 public CubeMap(string Path)
 {
     try
     {
         path = Path;
         cube = TextureLoader.FromCubeFile(LogiX_Engine.Device, Path);
         correct = true;
     }
     catch
     {
         Error("OnLoadCubeMap");
     }
 }
        public static void CopyToCubeSide(OpsContext context, CubeTexture newTexture, string srcArg, CubeMapFace face, Filter filter)
        {
            if(srcArg == null || srcArg.Length == 0)
                return;

            OpsTexture src = context.GetTexture(srcArg);
                
            if(src == null)
                throw new OpsException("Could not find source texture: "+srcArg );

            if(src.Texture is CubeTexture)
            {
                SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(face, 0), ((CubeTexture)src.Texture).GetCubeMapSurface(face,0), filter| (src.SRGB?Filter.SrgbIn:0), 0);             
            }
            else if (src.Texture is Texture)
            {
                SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(face, 0), ((Texture)src.Texture).GetSurfaceLevel(0), filter| (src.SRGB?Filter.SrgbIn:0), 0);             
            }
            else
                throw new OpsException("Source texture is not a texture2D: "+srcArg);

        }
        private void LoadCubeMapFace(CubeTexture tex, CubeMapFace face, string fileName, int size, Format format)
        {
            var data = Surface.CreateOffscreenPlain(device, size, size, format, Pool.Scratch);
            Surface.FromFileInStream(data, this.GetType().Assembly.GetManifestResourceStream(fileName), Filter.None, 0);
            var dstRect = tex.LockRectangle(face, 0, LockFlags.None);
            var srcRect = data.LockRectangle(LockFlags.ReadOnly);

            srcRect.Data.CopyTo(dstRect.Data);

            data.UnlockRectangle();
            tex.UnlockRectangle(face, 0);

            data.Dispose();
        }
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            //Cargar escenario
            TgcSceneLoader loader = new TgcSceneLoader();

            //Cargar textura de CubeMap para Environment Map, fijo para todos los meshes
            cubeMap = TextureLoader.FromCubeFile(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Shaders\\CubeMap.dds");

            //Cargar Shader personalizado de EnvironmentMap
            effect = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosDir + "AlumnoMedia\\RideTheLightning\\Shaders\\EnvironmentMap_Integrador2.fx");

            //Configurar MeshFactory customizado
            //scene = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Scenes\\DepositoMin\\Deposito-TgcScene.xml");
               // scene = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Scenes\\Deposito2\\Deposito-TgcScene.xml");
            //Cargar escenario, pero inicialmente solo hacemos el parser, para separar los objetos que son solo luces y no meshes
            string scenePath = GuiController.Instance.AlumnoEjemplosDir + "AlumnoMedia\\RideTheLightning\\Scenes\\Deposito\\Deposito-TgcScene.xml";
            string mediaPath = GuiController.Instance.AlumnoEjemplosDir + "AlumnoMedia\\RideTheLightning\\Scenes\\Deposito\\";
            TgcSceneParser parser = new TgcSceneParser();
            TgcSceneData sceneData = parser.parseSceneFromString(File.ReadAllText(scenePath));

            //Separar modelos reales de las luces, segun layer "Lights"
            lights = new List<LightData>();
            List<TgcMeshData> realMeshData = new List<TgcMeshData>();
            for (int i = 0; i < sceneData.meshesData.Length; i++)
            {
                TgcMeshData meshData = sceneData.meshesData[i];

                //Es una luz, no cargar mesh, solo importan sus datos
                if (meshData.layerName == "lights")
                {
                    //Guardar datos de luz
                    LightData light = new LightData();
                    light.color = Color.FromArgb((int)meshData.color[0], (int)meshData.color[1], (int)meshData.color[2]);
                    light.aabb = new TgcBoundingBox(TgcParserUtils.float3ArrayToVector3(meshData.pMin), TgcParserUtils.float3ArrayToVector3(meshData.pMax));
                    light.pos = light.aabb.calculateBoxCenter();
                    light.spot = meshData.userProperties["esSpot"].Equals("SI");
                    light.direccion = convertirDireccion(meshData.userProperties["dir"]);
                    lights.Add(light);
                }
                //Es un mesh real, agregar a array definitivo
                else
                {
                    realMeshData.Add(meshData);
                }
            }

            //Reemplazar array original de meshData de sceneData por el definitivo
            sceneData.meshesData = realMeshData.ToArray();

            //Ahora si cargar meshes reales

            scene = loader.loadScene(sceneData, mediaPath);

            //Pre-calculamos las 3 luces mas cercanas de cada mesh
            meshesYLuces = new List<MeshLightData>();
            foreach (TgcMesh mesh in scene.Meshes)
            {
                MeshLightData meshData = new MeshLightData();
                meshData.mesh = mesh;
                Vector3 meshCeter = mesh.BoundingBox.calculateBoxCenter();
                meshData.lights = lucesMasCercanas(meshCeter, 3);
                meshesYLuces.Add(meshData);
            }

            //Camara en 1ra persona

            GuiController.Instance.FpsCamera.Enable = true;
            GuiController.Instance.FpsCamera.MovementSpeed = 400f;
            GuiController.Instance.FpsCamera.JumpSpeed = 300f;
            GuiController.Instance.FpsCamera.setCamera(new Vector3(80, 80, 0), new Vector3(0, 80, 1));

            //Mesh para la luz

            //Modifiers de la luz
            GuiController.Instance.Modifiers.addBoolean("lightEnable", "lightEnable", true);
            GuiController.Instance.Modifiers.addBoolean("linterna", "linterna", true);
            GuiController.Instance.Modifiers.addBoolean("foco", "foco", true);

            GuiController.Instance.Modifiers.addColor("lightColor", Color.White);
            GuiController.Instance.Modifiers.addFloat("lightIntensity", 0, 150, 35);
            GuiController.Instance.Modifiers.addFloat("lightAttenuation", 0.1f, 2, 0.3f);
            GuiController.Instance.Modifiers.addFloat("specularEx", 0, 20, 9f);
            GuiController.Instance.Modifiers.addFloat("spotAngle", 0, 180, 39f);
            GuiController.Instance.Modifiers.addFloat("spotExponent", 0, 20, 7f);

            //Modifiers de material
            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);
        }
 /// <summary>
 /// Predispone l'oggetto CubeMap ad essere generato dall'ambiente circostante (Rendering to target) (da utilizzare all'esterno del GameLoop)
 /// </summary>
 /// <param name="EdgeLength"></param>
 /// <returns></returns>
 public bool InitializeRenderToCube(int EdgeLength)
 {
     try
     {
         viewport = new Viewport();
         viewport.MaxZ = 1;
         viewport.Width = EdgeLength;
         viewport.Height = EdgeLength;
         LogiX_Engine.Device.RenderState.NormalizeNormals = true;
         cube = new CubeTexture(LogiX_Engine.Device, EdgeLength, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default);
         renderToEnvy = new RenderToEnvironmentMap(LogiX_Engine.Device, EdgeLength, 1, Format.X8R8G8B8, true, DepthFormat.D16);
         cam = new Camera(new VertexData(0, 0, 0), new VertexData(0, 0, 0));
         cam.FarPlane = 100000;
         cam.AspectRatio = 1;
         cam.FieldOfView = (float)Math.PI / 2;
         path = null;
         correct = true;
         return true;
     }
     catch
     {
         Error("OnInitializeRenderToCube");
         return false;
     }
 }
Beispiel #45
0
        public void CrearEnvMapAgua()
        {
            // creo el enviroment map para el agua
            Device device = GuiController.Instance.D3dDevice;
            g_pCubeMapAgua = new CubeTexture(device, 256, 1, Usage.RenderTarget,
                Format.A16B16G16R16F, Pool.Default);
            Surface pOldRT = device.GetRenderTarget(0);
            // ojo: es fundamental que el fov sea de 90 grados.
            // asi que re-genero la matriz de proyeccion
            device.Transform.Projection =
                Matrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f),
                    1f, near_plane, far_plane);
            // Genero las caras del enviroment map
            for (CubeMapFace nFace = CubeMapFace.PositiveX; nFace <= CubeMapFace.NegativeZ; ++nFace)
            {
                Surface pFace = g_pCubeMapAgua.GetCubeMapSurface(nFace, 0);
                device.SetRenderTarget(0, pFace);
                Vector3 Dir, VUP;
                Color color;
                switch (nFace)
                {
                    default:
                    case CubeMapFace.PositiveX:
                        // Left
                        Dir = new Vector3(1, 0, 0);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Black;
                        break;
                    case CubeMapFace.NegativeX:
                        // Right
                        Dir = new Vector3(-1, 0, 0);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Red;
                        break;
                    case CubeMapFace.PositiveY:
                        // Up
                        Dir = new Vector3(0, 1, 0);
                        VUP = new Vector3(0, 0, -1);
                        color = Color.Gray;
                        break;
                    case CubeMapFace.NegativeY:
                        // Down
                        Dir = new Vector3(0, -1, 0);
                        VUP = new Vector3(0, 0, 1);
                        color = Color.Yellow;
                        break;
                    case CubeMapFace.PositiveZ:
                        // Front
                        Dir = new Vector3(0, 0, 1);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Green;
                        break;
                    case CubeMapFace.NegativeZ:
                        // Back
                        Dir = new Vector3(0, 0, -1);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Blue;
                        break;
                }

                Vector3 Pos = piso.Position;
                if (nFace == CubeMapFace.NegativeY)
                    Pos.Y += 2000;

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

                device.EndScene();
            }
            // restuaro el render target
            device.SetRenderTarget(0, pOldRT);
        }
Beispiel #46
0
 /// <summary>
 /// Método que se llama cuando termina la ejecución del ejemplo.
 /// Hacer dispose() de todos los objetos creados.
 /// </summary>
 public override void close()
 {
     //escena.disposeAll();
     GuiController.Instance.Modifiers.clear();
     mainMesh.dispose();
     meshBot.dispose();
     balaMesh1.dispose();
     balaMesh2.dispose();
     barcoEnemigo = null;
     barcoPrincipal = null;
     enemigos = null;
     g_pCubeMapAgua = null;
 }
        public static CubeTexture CloneCube( CubeTexture oldTexture, Usage usage, Pool pool)
        {
            SurfaceDescription sd = oldTexture.GetLevelDescription(0);

            return CloneCube(oldTexture, sd.Width, oldTexture.LevelCount, sd.Format, usage, Filter.None, pool);
        }
Beispiel #48
0
        public override void render(float elapsedTime)
        {
            Device device = GuiController.Instance.D3dDevice;
            Control panel3d = GuiController.Instance.Panel3d;
            float aspectRatio = (float)panel3d.Width / (float)panel3d.Height;
            time += elapsedTime;

            if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.C))
            {
                timer_preview = 0;
                camara_rot = !camara_rot;
            }

            if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.F))
            {
                if (tipo_vista == 1)
                    tipo_vista = 0;
                else
                    tipo_vista = 1;
                ant_vista = tipo_vista;
            }

            if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.D))
            {
                if (tipo_vista == 2)
                    tipo_vista = ant_vista;
                else
                    tipo_vista = 2;
            }

            if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.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);
            float alfa = an_tanque;
            float x0 = 2000f * (float)Math.Cos(alfa);
            float z0 = 2000f * (float)Math.Sin(alfa);
            float offset_rueda = 10;
            float H = terrain.CalcularAltura(x0, z0) + alto_tanque / 2 - offset_rueda;
            if (H < nivel_mar)
                H = nivel_mar;
            mesh.Position = new Vector3(x0, H, z0);
            // direccion tangente sobre el piso: 
            Vector2 dir_tanque = new Vector2(-(float)Math.Sin(alfa), (float)Math.Cos(alfa));
            dir_tanque.Normalize();
            // Posicion de la parte de adelante del tanque
            Vector2 pos2d = new Vector2(x0, z0);
            pos2d = pos2d + dir_tanque * (largo_tanque / 2);
            float H_frente = terrain.CalcularAltura(pos2d.X, pos2d.Y) + alto_tanque / 2 - offset_rueda;
            if (H_frente < nivel_mar-15)
                H_frente = nivel_mar-15;
            Vector3 pos_frente = new Vector3(pos2d.X, H_frente, pos2d.Y);
            Vector3 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 Vector3(x0, 150, z0);
            dir_canoa = new Vector3(-(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 Vector3(1500f * (float)Math.Cos(alfa_sol), 1500f * (float)Math.Sin(alfa_sol), 0f);
            g_LightPos = new Vector3(2000f * (float)Math.Cos(alfa_sol), 2000f * (float)Math.Sin(alfa_sol), 0f);
            g_LightDir = -g_LightPos;
            g_LightDir.Normalize();

            if (timer_preview > 0)
            {
                float an = -time * Geometry.DegreeToRadian(10.0f);
                LookFrom.X = 1500f * (float)Math.Sin(an);
                LookFrom.Z = 1500f * (float)Math.Cos(an);
            }
            else
            {
                if (camara_rot)
                {
                    GuiController.Instance.RotCamera.targetObject(mesh.BoundingBox);
                    GuiController.Instance.CurrentCamera.updateCamera();
                }
                else
                {
                    GuiController.Instance.RotCamera.CameraCenter = new Vector3(0, 200, 0);
                    GuiController.Instance.RotCamera.CameraDistance = 2000;
                    GuiController.Instance.RotCamera.RotationSpeed = 1f;
                    GuiController.Instance.RotCamera.ZoomFactor = 0.1f;
                }
            }

            // --------------------------------------------------------------------
            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: 
            CubeTexture g_pCubeMap = new CubeTexture(device, 256, 1, Usage.RenderTarget,
                Format.A16B16G16R16F, Pool.Default);
            Surface pOldRT = device.GetRenderTarget(0);
            // ojo: es fundamental que el fov sea de 90 grados.
            // asi que re-genero la matriz de proyeccion
            device.Transform.Projection =
                Matrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f),1f, near_plane,far_plane);

            // Genero las caras del enviroment map
            for (CubeMapFace nFace = CubeMapFace.PositiveX; nFace <= CubeMapFace.NegativeZ; ++nFace)
            {
                Surface pFace = g_pCubeMap.GetCubeMapSurface(nFace, 0);
                device.SetRenderTarget(0, pFace);
                Vector3 Dir, VUP;
                Color color;
                switch (nFace)
                {
                    default:
                    case CubeMapFace.PositiveX:
                        // Left
                        Dir = new Vector3(1, 0, 0);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Black;
                        break;
                    case CubeMapFace.NegativeX:
                        // Right
                        Dir = new Vector3(-1, 0, 0);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Red;
                        break;
                    case CubeMapFace.PositiveY:
                        // Up
                        Dir = new Vector3(0, 1, 0);
                        VUP = new Vector3(0, 0, -1);
                        color = Color.Gray;
                        break;
                    case CubeMapFace.NegativeY:
                        // Down
                        Dir = new Vector3(0, -1, 0);
                        VUP = new Vector3(0, 0, 1);
                        color = Color.Yellow;
                        break;
                    case CubeMapFace.PositiveZ:
                        // Front
                        Dir = new Vector3(0, 0, 1);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Green;
                        break;
                    case CubeMapFace.NegativeZ:
                        // Back
                        Dir = new Vector3(0, 0, -1);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Blue;
                        break;
                }

                //Obtener ViewMatrix haciendo un LookAt desde la posicion final anterior al centro de la camara
                Vector3 Pos = mesh.Position;
                device.Transform.View = Matrix.LookAtLH(Pos, Pos + Dir, VUP);


                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, color, 1.0f, 0);
                device.BeginScene();

                //Renderizar 
                renderScene(elapsedTime, true);

                device.EndScene();
                //string fname = string.Format("face{0:D}.bmp", nFace);
                //SurfaceLoader.Save(fname, ImageFileFormat.Bmp, pFace);
            }
            // restuaro el render target
            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)
                device.Transform.View = Matrix.LookAtLH(LookFrom,LookAt,new Vector3(0,1,0));
            else
                GuiController.Instance.CurrentCamera.updateViewMatrix(device);
            device.Transform.Projection =
                Matrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f),
                    aspectRatio, near_plane, far_plane);

            // Cargo las var. del shader:
            effect.SetValue("g_txCubeMap", g_pCubeMap);
            effect.SetValue("fvLightPosition", new Vector4(0, 400, 0, 0));
            effect.SetValue("fvEyePosition",
                    TgcParserUtils.vector3ToFloat3Array(timer_preview > 0 ? LookFrom :
                    GuiController.Instance.RotCamera.getPosition()));
            effect.SetValue("time", time);

            // -----------------------------------------------------
            // dibujo la escena pp dicha:
            device.BeginScene();

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

                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                // 1ero sin el agua
                renderScene(elapsedTime, false);

                // Ahora dibujo el agua
                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:
                    device.Viewport = View2;
                else
                    // dibujo en la pantalla completa
                    device.Viewport = ViewF;

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

            }

            g_pCubeMap.Dispose();

        }
 public static CubeTexture CloneCube( CubeTexture oldTexture, int size, int mips, Format format, Usage usage, Filter filter , Pool pool)
 {
     CubeTexture newTexture = new CubeTexture(oldTexture.Device, size, mips, usage, format, pool);
     SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.NegativeX,0), oldTexture.GetCubeMapSurface(CubeMapFace.NegativeX,0), filter, 0);
     SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.NegativeY,0), oldTexture.GetCubeMapSurface(CubeMapFace.NegativeY,0), filter, 0);
     SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.NegativeZ,0), oldTexture.GetCubeMapSurface(CubeMapFace.NegativeZ,0), filter, 0);
     SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.PositiveX,0), oldTexture.GetCubeMapSurface(CubeMapFace.PositiveX,0), filter, 0);
     SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.PositiveY,0), oldTexture.GetCubeMapSurface(CubeMapFace.PositiveY,0), filter, 0);
     SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(CubeMapFace.PositiveZ,0), oldTexture.GetCubeMapSurface(CubeMapFace.PositiveZ,0), filter, 0);    
     return newTexture;
 }
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;


            //Cargar textura de CubeMap para Environment Map
            cubeMap = TextureLoader.FromCubeFile(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Shaders\\CubeMap.dds");


            //Crear 3 paredes y un piso con textura comun y textura de normalMap
            TgcTexture diffuseMap = TgcTexture.createTexture(GuiController.Instance.ExamplesMediaDir + "Shaders\\BumpMapping_DiffuseMap.jpg");
            TgcTexture normalMap = TgcTexture.createTexture(GuiController.Instance.ExamplesMediaDir + "Shaders\\BumpMapping_NormalMap.jpg");
            TgcTexture[] normalMapArray = new TgcTexture[] { normalMap };

            TgcBox paredSur = TgcBox.fromExtremes(new Vector3(-200, 0, -210), new Vector3(200, 100, -200), diffuseMap);
            TgcBox paredOeste = TgcBox.fromExtremes(new Vector3(-210, 0, -200), new Vector3(-200, 100, 200), diffuseMap);
            TgcBox paredEste = TgcBox.fromExtremes(new Vector3(200, 0, -200), new Vector3(210, 100, 200), diffuseMap);
            TgcBox piso = TgcBox.fromExtremes(new Vector3(-200, -1, -200), new Vector3(200, 0, 200), diffuseMap);

            //Convertir TgcBox a TgcMesh
            TgcMesh m1 = paredSur.toMesh("paredSur");
            TgcMesh m2 = paredOeste.toMesh("paredOeste");
            TgcMesh m3 = paredEste.toMesh("paredEste");
            TgcMesh m4 = piso.toMesh("piso");

            //Convertir TgcMesh a TgcMeshBumpMapping
            meshes = new List<TgcMeshBumpMapping>();
            meshes.Add(TgcMeshBumpMapping.fromTgcMesh(m1, normalMapArray));
            meshes.Add(TgcMeshBumpMapping.fromTgcMesh(m2, normalMapArray));
            meshes.Add(TgcMeshBumpMapping.fromTgcMesh(m3, normalMapArray));
            meshes.Add(TgcMeshBumpMapping.fromTgcMesh(m4, normalMapArray));

            
            //Borrar TgcMesh y TgcBox, ya no se usan
            paredSur.dispose();
            paredOeste.dispose();
            paredEste.dispose();
            piso.dispose();
            m1.dispose();
            m2.dispose();
            m3.dispose();
            m4.dispose();


            
            //Camara en 1ra persona
            GuiController.Instance.FpsCamera.Enable = true;
            GuiController.Instance.FpsCamera.setCamera(new Vector3(0, 50, 100), new Vector3(0, 50, -1));

            //Cargar Shader personalizado para EnviromentMap
            effect = TgcShaders.loadEffect(GuiController.Instance.ExamplesMediaDir + "Shaders\\EnvironmentMap.fx");

            //Cargar shader en meshes
            foreach (TgcMeshBumpMapping m in meshes)
            {
                m.Effect = effect;
                m.Technique = "EnvironmentMapTechnique";
            }
            
            //Mesh para la luz
            lightMesh = TgcBox.fromSize(new Vector3(10, 10, 10), Color.Red);
            GuiController.Instance.Modifiers.addFloat("reflection", 0, 1, 0.35f);
            GuiController.Instance.Modifiers.addFloat("bumpiness", 0, 1, 1f);
            GuiController.Instance.Modifiers.addVertex3f("lightPos", new Vector3(-200, 0, -200), new Vector3(200, 100, 200), new Vector3(0, 80, 0));
            GuiController.Instance.Modifiers.addColor("lightColor", Color.White);
            GuiController.Instance.Modifiers.addFloat("lightIntensity", 0, 150, 20);
            GuiController.Instance.Modifiers.addFloat("lightAttenuation", 0.1f, 2, 0.3f);
            GuiController.Instance.Modifiers.addFloat("specularEx", 0, 20, 9f);
            

            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);
        }
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;


            //Cargar textura de CubeMap para Environment Map, fijo para todos los meshes
            cubeMap = TextureLoader.FromCubeFile(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Shaders\\CubeMap.dds");

            //Cargar Shader personalizado de EnvironmentMap
            effect = TgcShaders.loadEffect(GuiController.Instance.ExamplesMediaDir + "Shaders\\EnvironmentMap.fx");


            //Cargar escenario, pero inicialmente solo hacemos el parser, para separar los objetos que son solo luces y no meshes
            string scenePath = GuiController.Instance.ExamplesDir + "Lights\\NormalMapRoom\\NormalMapRoom-TgcScene.xml";
            string mediaPath = GuiController.Instance.ExamplesDir + "Lights\\NormalMapRoom\\";
            TgcSceneParser parser = new TgcSceneParser();
            TgcSceneData sceneData = parser.parseSceneFromString(File.ReadAllText(scenePath));

            //Separar modelos reales de las luces, segun layer "Lights"
            lights = new List<LightData>();
            List<TgcMeshData> realMeshData = new List<TgcMeshData>();
            for (int i = 0; i < sceneData.meshesData.Length; i++)
            {
                TgcMeshData meshData = sceneData.meshesData[i];

                //Es una luz, no cargar mesh, solo importan sus datos
                if (meshData.layerName == "Lights")
                {
                    //Guardar datos de luz
                    LightData light = new LightData();
                    light.color = Color.FromArgb((int)meshData.color[0], (int)meshData.color[1], (int)meshData.color[2]);
                    light.aabb = new TgcBoundingBox(TgcParserUtils.float3ArrayToVector3(meshData.pMin), TgcParserUtils.float3ArrayToVector3(meshData.pMax));
                    light.pos = light.aabb.calculateBoxCenter();
                    lights.Add(light);
                }
                //Es un mesh real, agregar a array definitivo
                else
                {
                    realMeshData.Add(meshData);
                }
            }

            //Reemplazar array original de meshData de sceneData por el definitivo
            sceneData.meshesData = realMeshData.ToArray();

            //Ahora si cargar meshes reales
            TgcSceneLoader loader = new TgcSceneLoader();
            TgcScene scene = loader.loadScene(sceneData, mediaPath);

            //Separar meshes con bumpMapping de los comunes
            bumpMeshes = new List<TgcMeshBumpMapping>();
            commonMeshes = new List<TgcMesh>();
            foreach (TgcMesh mesh in scene.Meshes)
            {
                //Mesh con BumpMapping
                if (mesh.Layer == "BumpMap")
                {
                    //Por convencion de este ejemplo el NormalMap se llama igual que el DiffuseMap (y cada mesh tiene una sola)
                    string path = mesh.DiffuseMaps[0].FilePath;
                    string[] split = path.Split('.');
                    path = split[0] + "_NormalMap.png";

                    //Convertir TgcMesh a TgcMeshBumpMapping
                    TgcTexture normalMap = TgcTexture.createTexture(path);
                    TgcTexture[] normalMapArray = new TgcTexture[] { normalMap };
                    TgcMeshBumpMapping bumpMesh = TgcMeshBumpMapping.fromTgcMesh(mesh, normalMapArray);
                    bumpMesh.Effect = effect;
                    bumpMesh.Technique = "EnvironmentMapTechnique";
                    bumpMeshes.Add(bumpMesh);

                    //Liberar original
                    mesh.dispose();
                }
                //Mesh normal
                else
                {
                    commonMeshes.Add(mesh);
                }
            }



            
            //Camara en 1ra persona
            GuiController.Instance.FpsCamera.Enable = true;
            GuiController.Instance.FpsCamera.setCamera(new Vector3(0, 50, 100), new Vector3(0, 50, -1));

            
            
            //Modifiers
            GuiController.Instance.Modifiers.addBoolean("lightEnable", "lightEnable", true);
            GuiController.Instance.Modifiers.addFloat("reflection", 0, 1, 0.2f);
            GuiController.Instance.Modifiers.addFloat("bumpiness", 0, 2, 1f);
            GuiController.Instance.Modifiers.addFloat("lightIntensity", 0, 150, 20);
            GuiController.Instance.Modifiers.addFloat("lightAttenuation", 0.1f, 2, 0.3f);
            GuiController.Instance.Modifiers.addFloat("specularEx", 0, 20, 9f);

            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);
        }
        public void Add(TextureSection textureSection)
        {
            Texture texture = null;
            CubeTexture cube = null;
            try
            {
                TextureHolder texHolder = new TextureHolder();
                int texWidth = textureSection.Gtex.Header.Width;
                int texHeight = textureSection.Gtex.Header.Height;
                if (textureSection.Gtex.Header.IsCubeMap)
                {
                    cube = new CubeTexture(device, texWidth, 0, Usage.None, textureSection.Gtex.Format, Pool.Managed);
                    texHolder.Texture = cube;
                    texHolder.Name = textureSection.ResourceId;
                    texHolder.Gtex = textureSection.Gtex;

                    CubeMapFace[] faces = new CubeMapFace[] { CubeMapFace.NegativeX,
                                                              CubeMapFace.NegativeY,
                                                              CubeMapFace.NegativeZ,
                                                              CubeMapFace.PositiveX,
                                                              CubeMapFace.PositiveY,
                                                              CubeMapFace.PositiveZ };
                    for (var i = 0; i < 6; i++)
                    {
                        var texData = cube.LockRectangle(faces[i], 0, LockFlags.None);
                        texData.Data.Write(texHolder.Gtex.TextureData[i], 0, texHolder.Gtex.TextureData[i].Length);
                        cube.UnlockRectangle(faces[i], 0);
                    }
                }
                else
                {
                    int numMipMaps = textureSection.Gtex.Header.MipMapCount;
                    Format format = textureSection.Gtex.Format;

                    texture = new Texture(device, texWidth, texHeight, numMipMaps, Usage.None, format, Pool.Managed);

                    texHolder.Texture = texture;
                    texHolder.Name = textureSection.ResourceId;
                    texHolder.Gtex = textureSection.Gtex;

                    for (var i = 0; i < numMipMaps; i++)
                    {
                        var texData = texture.LockRectangle(i, LockFlags.None);
                        texData.Data.Write(texHolder.Gtex.TextureData[i], 0, texHolder.Gtex.TextureData[i].Length);
                        texture.UnlockRectangle(i);
                    }
                }

                TextureHolder removeMe;
                if (this.textureLookup.TryGetValue(texHolder.Name, out removeMe))
                {
                    removeMe.Texture.Dispose();
                    this.textures.Remove(removeMe);
                    this.textureLookup.Remove(texHolder.Name);
                }

                this.textures.Add(texHolder);
                this.textureLookup.Add(texHolder.Name, texHolder);
            }
            catch
            {
                if (texture != null) { texture.Dispose(); }
                if (cube != null) { cube.Dispose(); }

                throw;
            }
        }
Beispiel #53
0
        public override void render(float elapsedTime)
        {
            Device device = GuiController.Instance.D3dDevice;
            Control panel3d = GuiController.Instance.Panel3d;
            float aspectRatio = (float)panel3d.Width / (float)panel3d.Height;
            if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.Space))
            {
                vel_tanque++;
                if (vel_tanque > 10)
                    vel_tanque = 0;
            }
            if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.X))
                volar = !volar;

            if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.S))
            {
                // swap mesh
                TgcMesh mesh_aux = mesh;
                mesh = meshX;
                meshX = mesh;
            }

            //Cargar variables de shader
            effect.SetValue("fvLightPosition", new Vector4(0,400,0,0));
            effect.SetValue("fvEyePosition", TgcParserUtils.vector3ToFloat3Array(GuiController.Instance.RotCamera.getPosition()));
            effect.SetValue("kx", (float)GuiController.Instance.Modifiers["Reflexion"]);
            effect.SetValue("kc", (float)GuiController.Instance.Modifiers["Refraccion"]);
            effect.SetValue("usar_fresnel", (bool)GuiController.Instance.Modifiers["Fresnel"]);

            time += elapsedTime;
            // animar tanque
            float alfa = -time * Geometry.DegreeToRadian(vel_tanque);
            float x0 = 2000f * (float)Math.Cos(alfa);
            float z0 = 2000f * (float)Math.Sin(alfa);
            float offset_rueda = 13;
            float H = CalcularAltura(x0, z0) + alto_tanque / 2 - offset_rueda;
            if (volar)
                H += 300;
            mesh.Position = new Vector3(x0, H, z0);
            // direccion tangente sobre el piso:
            Vector2 dir_tanque = new Vector2(-(float)Math.Sin(alfa), (float)Math.Cos(alfa));
            dir_tanque.Normalize();
            // Posicion de la parte de adelante del tanque
            Vector2 pos2d = new Vector2(x0, z0);
            pos2d = pos2d + dir_tanque * (largo_tanque / 2);
            float H_frente = CalcularAltura(pos2d.X, pos2d.Y) + alto_tanque / 2 - offset_rueda;
            if (volar)
                H_frente += 300;
            Vector3 pos_frente = new Vector3(pos2d.X, H_frente, pos2d.Y);
            Vector3 Vel = pos_frente - mesh.Position;
            Vel.Normalize();

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

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

            GuiController.Instance.RotCamera.targetObject(mesh.BoundingBox);
            GuiController.Instance.CurrentCamera.updateCamera();
            // --------------------------------------------------------------------
            device.EndScene();
            CubeTexture g_pCubeMap = new CubeTexture(device, 256, 1, Usage.RenderTarget,
                Format.A16B16G16R16F, Pool.Default);
            Surface pOldRT = device.GetRenderTarget(0);
            // ojo: es fundamental que el fov sea de 90 grados.
            // asi que re-genero la matriz de proyeccion
            device.Transform.Projection =
                Matrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f),
                    1f, 1f, 10000f);

            // Genero las caras del enviroment map
            for (CubeMapFace nFace = CubeMapFace.PositiveX; nFace <= CubeMapFace.NegativeZ; ++nFace)
            {
                Surface pFace = g_pCubeMap.GetCubeMapSurface(nFace, 0);
                device.SetRenderTarget(0, pFace);
                Vector3 Dir, VUP;
                Color color;
                switch (nFace)
                {
                    default:
                    case CubeMapFace.PositiveX:
                        // Left
                        Dir = new Vector3(1, 0, 0);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Black;
                        break;
                    case CubeMapFace.NegativeX:
                        // Right
                        Dir = new Vector3(-1, 0, 0);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Red;
                        break;
                    case CubeMapFace.PositiveY:
                        // Up
                        Dir = new Vector3(0, 1, 0);
                        VUP = new Vector3(0, 0, -1);
                        color = Color.Gray;
                        break;
                    case CubeMapFace.NegativeY:
                        // Down
                        Dir = new Vector3(0, -1, 0);
                        VUP = new Vector3(0, 0, 1);
                        color = Color.Yellow;
                        break;
                    case CubeMapFace.PositiveZ:
                        // Front
                        Dir = new Vector3(0, 0, 1);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Green;
                        break;
                    case CubeMapFace.NegativeZ:
                        // Back
                        Dir = new Vector3(0, 0, -1);
                        VUP = new Vector3(0, 1, 0);
                        color = Color.Blue;
                        break;
                }

                //Obtener ViewMatrix haciendo un LookAt desde la posicion final anterior al centro de la camara
                Vector3 Pos = mesh.Position;
                device.Transform.View = Matrix.LookAtLH(Pos, Pos + Dir, VUP);

                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, color, 1.0f, 0);
                device.BeginScene();

                //Renderizar
                renderScene(elapsedTime, true);

                device.EndScene();
                //string fname = string.Format("face{0:D}.bmp", nFace);
                //SurfaceLoader.Save(fname, ImageFileFormat.Bmp, pFace);

            }
            // restuaro el render target
            device.SetRenderTarget(0, pOldRT);
            //TextureLoader.Save("test.bmp", ImageFileFormat.Bmp, g_pCubeMap);

            // Restauro el estado de las transformaciones
            GuiController.Instance.CurrentCamera.updateViewMatrix(device);
            device.Transform.Projection =
                Matrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f),
                    aspectRatio, 1f, 10000f);

            // dibujo pp dicho
            device.BeginScene();
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            effect.SetValue("g_txCubeMap", g_pCubeMap);
            renderScene(elapsedTime, false);
            g_pCubeMap.Dispose();
        }
Beispiel #54
0
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

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


            // ------------------------------------------------------------
            // Creo el Heightmap para el terreno:
            terrain = new MySimpleTerrain();
            terrain.loadHeightmap(GuiController.Instance.ExamplesDir
                    + "Shaders\\WorkshopShaders\\Media\\Heighmaps\\" + "Heightmap3.jpg", 100f, 1f, new Vector3(0, 0, 0));
            terrain.loadTexture(GuiController.Instance.ExamplesDir
                    + "Shaders\\WorkshopShaders\\Media\\Heighmaps\\" + "TerrainTexture3.jpg");

            // ------------------------------------------------------------
            // Crear SkyBox:
            skyBox = new TgcSkyBox();
            skyBox.Center = new Vector3(0, 0, 0);
            skyBox.Size = new Vector3(8000, 8000, 8000);
            string texturesPath = GuiController.Instance.ExamplesMediaDir + "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.updateValues();

            // ------------------------------------------------------------
            //Cargar los mesh:
            scene = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir
                            + "MeshCreator\\Meshes\\Vehiculos\\TanqueFuturistaRuedas\\TanqueFuturistaRuedas-TgcScene.xml");
            mesh = scene.Meshes[0];
            
            scene2 = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir
                            + "MeshCreator\\Meshes\\Vegetacion\\Palmera\\Palmera-TgcScene.xml");
            palmera = scene2.Meshes[0];
            
            scene3 = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir
                            + "MeshCreator\\Meshes\\Vehiculos\\Canoa\\Canoa-TgcScene.xml");
            canoa = scene3.Meshes[0];

            scene4 = loader.loadSceneFromFile(GuiController.Instance.ExamplesDir
                            + "Shaders\\WorkshopShaders\\Media\\Piso\\Agua-TgcScene.xml");
            piso = scene4.Meshes[0];

            mesh.Scale = new Vector3(0.5f, 0.5f, 0.5f);
            mesh.Position = new Vector3(0f, 0f, 0f);
            mesh.AutoTransformEnable = false;
            Vector3 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 Vector3(1f, 1f, 1f);
            canoa.Position = new Vector3(3000f, 550f, 0f);
            canoa.AutoTransformEnable = false;
            dir_canoa = new Vector3(0, 0, 1);
            nivel_mar = 135f;
            piso.Scale = new Vector3(25f, 1f, 25f);
            piso.Position = new Vector3(0f, nivel_mar, 0f);

            size = palmera.BoundingBox.calculateSize();
            float 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 (int j = 0; j < 15; j++)
                {
                    TgcMesh instance = palmera.createMeshInstance(palmera.Name + i);
                    instance.Scale = new Vector3(0.5f, 1.5f, 0.5f);
                    float x = r[i] * (float)Math.Cos(Geometry.DegreeToRadian(100 + 10.0f * j));
                    float z = r[i] * (float)Math.Sin(Geometry.DegreeToRadian(100 + 10.0f * j));
                    instance.Position = new Vector3(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 (int j = 0; j < 5; j++)
                {
                    TgcMesh instance = palmera.createMeshInstance(palmera.Name + i);
                    instance.Scale = new Vector3(0.5f, 1f + j/5f*0.33f, 0.5f);
                    float x = r2[i] * (float)Math.Cos(Geometry.DegreeToRadian(25.0f * j));
                    float z = r2[i] * (float)Math.Sin(Geometry.DegreeToRadian(25.0f * j));
                    instance.Position = new Vector3(x, terrain.CalcularAltura(x, z) /*+ alto_palmera / 2 * instance.Scale.Y*/ , z);
                    bosque.Add(instance);
                }

            GuiController.Instance.RotCamera.CameraDistance = 300;
            GuiController.Instance.RotCamera.RotationSpeed = 1.5f;

            // 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.loadEffect(GuiController.Instance.ExamplesDir + "Shaders\\WorkshopShaders\\Shaders\\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, 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 tamaño que el shadowmap, y que no tenga 
            // multisample, etc etc.
            g_pDSShadow = d3dDevice.CreateDepthStencilSurface(SHADOWMAP_SIZE,
                                                             SHADOWMAP_SIZE,
                                                             DepthFormat.D24S8,
                                                             MultiSampleType.None,
                                                             0,
                                                             true);
            // por ultimo necesito una matriz de proyeccion para el shadowmap, ya 
            // que voy a dibujar desde el pto de vista de la luz.
            // El angulo tiene que ser mayor a 45 para que la sombra no falle en los extremos del cono de luz
            // de hecho, un valor mayor a 90 todavia es mejor, porque hasta con 90 grados es muy dificil
            // lograr que los objetos del borde generen sombras
            Control panel3d = GuiController.Instance.Panel3d;
            float aspectRatio = (float)panel3d.Width / (float)panel3d.Height;
            g_mShadowProj = Matrix.PerspectiveFovLH(Geometry.DegreeToRadian(130.0f),
                aspectRatio, near_plane, far_plane);
            d3dDevice.Transform.Projection =
                Matrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f),
                aspectRatio, near_plane, far_plane);

            alfa_sol = 1.7f;
            //alfa_sol = 0;

            //--------------------------------------------------------------------------------------
            //Centrar camara rotacional respecto a este mesh
            camara_rot = false;
            GuiController.Instance.RotCamera.targetObject(mesh.BoundingBox);
            LookFrom = new Vector3(0, 400, 2000);
            LookAt = new Vector3(0,200,0);


            // inicio unos segundos de preview
            timer_preview = 50;

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

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

        }
Beispiel #55
0
        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;
        }
Beispiel #56
0
        private void RenderCubeMapFace(OpsContext context, CubeTexture newTexture, Surface rt, CubeMapFace face, int mip, int size, bool SRGB)
        {
            context.Device.SetRenderTarget(0, rt);
                        
            ShadeVertex[] vb = new ShadeVertex[]
                                {
                                    ShadeVertex.ForCube(-1.0f, -1.0f, size, face),
                                    ShadeVertex.ForCube( 1.0f, -1.0f, size, face),
                                    ShadeVertex.ForCube(-1.0f,  1.0f, size, face),
                                    ShadeVertex.ForCube( 1.0f,  1.0f, size, face),
                                };

            context.Device.BeginScene();
            context.Device.DrawUserPrimitives(PrimitiveType.TriangleStrip, 2, vb);
            context.Device.EndScene();

            context.Device.SetRenderTarget(0, context.Device.GetBackBuffer(0, 0, BackBufferType.Mono) );

            SurfaceLoader.FromSurface(newTexture.GetCubeMapSurface(face, mip), rt, Filter.None| (SRGB?Filter.SrgbOut:0), 0);
        }
Beispiel #57
0
        /// <summary>
        /// Device has been reset - rebuild unmanaged resources
        /// </summary>
        public static void OnReset()
        {
            Debug.WriteLine("Water.OnReset()");

            // Load caustic textures
            for (int i = 0; i < NUMCAUSTICS; i++)
            {
                string fsp = "caust" + i.ToString("00") + ".tga";
                texCaustic[i] = TextureLoader.FromFile(Engine.Device, FileResource.Fsp("textures", fsp));
                texCaustic[i].GenerateMipSubLevels();
            }

            // Load wave textures (normal maps)
            for (int i = 0; i < NUMWAVES; i++)
            {
                string fsp = "wave" + i.ToString("00") + "DOT3.tga";
                texNormal[i] = TextureLoader.FromFile(Engine.Device, FileResource.Fsp("textures", fsp));
                texNormal[i].GenerateMipSubLevels();
            }

            // Load the cube map for the reflections - NOTE!!!! NEED TO CHECK CAPABILITIES IN REAL LIFE - TextureLoader class can do this
            texReflection = TextureLoader.FromCubeFile(Engine.Device, FileResource.Fsp("textures", "WaterEnv.dds"));		// Longer overload needed???
        }
        internal void Init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            score = 0; //lleva el score del jugador
            capturas = 0;
            WINNER = false;

            killMultiTracker = 0;
            KILL_DELAY = 0;
            SPAWN_TIME_COUNTER = 0f;
            time = 0;

            // creo meshes de modelo para clonar y asi optimizar
            TgcSceneLoader loader2 = new TgcSceneLoader();
            TgcScene scene = loader2.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Robot\\Robot-TgcScene.xml");
            this.ModeloRobot = scene.Meshes[0];
            TgcScene scene2 = loader2.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Vehiculos\\StarWars-Speeder\\StarWars-Speeder-TgcScene.xml");
            this.ModeloNave = scene2.Meshes[0];
            TgcScene scene3 = loader2.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Meshes\\proyectiles\\EnergyBall-TgcScene.xml");
            this.ModeloProyectil = scene3.Meshes[0];

            //Cargar textura de CubeMap para Environment Map
            cubeMap = TextureLoader.FromCubeFile(d3dDevice, GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Shaders\\CubemapRobot.dds");

            //Cargar Shader de DynamicLights
            envMap = TgcShaders.loadEffect(GuiController.Instance.ExamplesMediaDir + "Shaders\\EnvironmentMap.fx");
            envMap.Technique = "SimpleEnvironmentMapTechnique";

            skeletalEnvMap = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Shaders\\" + "SkeletalEnvMap.fx");

            //Creo skybox
            skyBox = new CustomSkyBox();
            skyBox.Center = new Vector3(0, 0, 0);
            float farplane = CustomFpsCamera.FAR_PLANE;
            skyBox.Size = new Vector3(farplane, farplane, farplane);

            string texturesPath = GuiController.Instance.ExamplesMediaDir + "Texturas\\Quake\\SkyBox1\\";

            skyBox.setFaceTexture(CustomSkyBox.SkyFaces.Up, texturesPath + "phobos_up.jpg");
            skyBox.setFaceTexture(CustomSkyBox.SkyFaces.Down, texturesPath + "phobos_dn.jpg");
            skyBox.setFaceTexture(CustomSkyBox.SkyFaces.Left, texturesPath + "phobos_lf.jpg");
            skyBox.setFaceTexture(CustomSkyBox.SkyFaces.Right, texturesPath + "phobos_rt.jpg");
            skyBox.setFaceTexture(CustomSkyBox.SkyFaces.Front, texturesPath + "phobos_bk.jpg");
            skyBox.setFaceTexture(CustomSkyBox.SkyFaces.Back, texturesPath + "phobos_ft.jpg");
            skyBox.updateValues();

            //Creacion del terreno
            currentHeightmap = GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Mapas\\" + "experimento-editando4_3.jpg";
            //Seteo de la resolucion del jpg de heightmap para la interpolacion de altura, como es cuadrado se usa una sola variable
            heightmapResolution = 800;
            textureResolution = 1600;

            Vector3 posInicial = new Vector3(0, 0, 0);
            currentTexture = GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Mapas\\" + "grunge.jpg";
            terrain = new CustomTerrain();
            terrain.loadHeightmap(currentHeightmap, currentScaleXZ, currentScaleY, posInicial, cantidadFilasColumnas);
            terrain.loadTexture(currentTexture);
            terrain.Effect = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Shaders\\RenderTerrain.fx");
            terrain.Technique = "RenderTerrain";

            //Creacion del shader de viento
            windShader = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Shaders\\WindTree.fx");

            //Creacion de la Vegetacion
            this.vegetation = new List<TgcMesh>();
            TgcSceneLoader loader = new TgcSceneLoader();
            Vegetation = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Mapas\\100x8 v4-TgcScene.xml");

            vegetation = Vegetation.Meshes;
            int i;
            for (i = 1; i < vegetation.Count; i++)
            {
                float randScaleXZ = (float)random.Next(85, 115) / 100;
                float randScaleY = (float)random.Next(70, 130) / 100;
                Matrix scale = Matrix.Scaling(new Vector3(0.06f * randScaleXZ, 0.4f * randScaleY, 0.06f * randScaleXZ));

                vegetation[i].setColor(Color.Purple);
                vegetation[i].Effect = windShader;
                vegetation[i].Technique = "WindTree";
                vegetation[i].Scale = new Vector3(randScaleXZ, randScaleY, randScaleXZ);
                Vector3 center = vegetation[i].BoundingBox.calculateBoxCenter();
                float y;
                interpoledHeight(center.X, center.Z, out y);
                center.Y = y;
                Matrix trans = Matrix.Translation(center + new Vector3(-4f, 0, 0));
                vegetation[i].BoundingBox.transform(scale * trans);
            }

            //Creacion de la Arbustos
            this.arbustos = new List<TgcMesh>();
            TgcSceneLoader loader6 = new TgcSceneLoader();
            Arbustos = loader6.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Mapas\\Arbustos-TgcScene.xml");

            arbustos = Arbustos.Meshes;

            for (i = 1; i < arbustos.Count; i++)
            {
                float randScaleXZ = (float)random.Next(90, 110) / 100;
                float randScaleY = (float)random.Next(75, 125) / 100;

                arbustos[i].Effect = windShader;
                arbustos[i].Technique = "WindTree";
                arbustos[i].setColor(Color.DarkOrange);
                arbustos[i].Scale = new Vector3(randScaleXZ, randScaleY, randScaleXZ);
            }

            //Creacion de la Tesoros
            this.tesoros = new List<TgcMesh>();
            TgcSceneLoader loader5 = new TgcSceneLoader();
            Tesoros = loader5.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Mapas\\Tesoros-TgcScene.xml");

            tesoros = Tesoros.Meshes;
            pointerTexture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Sprites\\TreasurePointer.png");
            initPointer();
            int k;
            for (k = 1; k < tesoros.Count; k++)
            {
                TgcSprite pointer = new TgcSprite();
                pointer.Texture = pointerTexture;
                pointer.Scaling = pointerScaling;
                pointers.Add(pointer);
            }

                //Creacion de barriles
                this.meshesBarril = new List<TgcMesh>();
            TgcSceneLoader loader4 = new TgcSceneLoader();
            Barriles = loader4.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Mapas\\Barriles2-TgcScene.xml");
            Barriles.setMeshesEnabled(true);
            meshesBarril = Barriles.Meshes;
            int j;
            //Matrix scale = Matrix.Scaling(new Vector3(0.06f, 0.4f, 0.06f));
            for (j = 1; j < meshesBarril.Count; j++)
            {
                Barril barril = new Barril();

                meshesBarril[j].Scale = new Vector3(0.3f, 0.3f, 0.3f);
                barril.mesh = meshesBarril[j];
                barril.Init();
                barriles.Add(barril);
                //vegetation[i].setColor(Color.SkyBlue);
                //Vector3 center = vegetation[i].BoundingBox.calculateBoxCenter();
                //float y;
                //interpoledHeight(center.X, center.Z, out y);
                //center.Y = y;
                //Matrix trans = Matrix.Translation(center + new Vector3(-4f, 0, 0));
                //vegetation[i].BoundingBox.transform(scale * trans);
            }

            //inicializamos al player
            player1.Init();

            enemies = new List<Enemy>();
            proyectiles = new List<Proyectil>();

            ScreenWidth = GuiController.Instance.D3dDevice.Viewport.Width;
            ScreenHeight = GuiController.Instance.D3dDevice.Viewport.Height;

            obstaculos = new List<TgcMesh>();
            obstaculos.AddRange(vegetation);
            obstaculos.AddRange(meshesBarril);
            obstaculos.AddRange(arbustos);

            quadTree = new Quadtree();
            quadTree.create(obstaculos, Vegetation.BoundingBox);
            quadTree.createDebugQuadtreeMeshes();

            //seteamos niebla
            //d3dDevice.RenderState.FogTableMode = FogMode.Linear;
            d3dDevice.RenderState.FogTableMode = FogMode.Exp2;
            d3dDevice.RenderState.FogVertexMode = FogMode.None;
            d3dDevice.RenderState.FogColor = Color.MediumPurple;
            //d3dDevice.RenderState.FogStart = 3000f;
            //d3dDevice.RenderState.FogEnd = farplane;
            d3dDevice.RenderState.FogDensity = 0.00006f;
            d3dDevice.RenderState.FogEnable = true;

            initPastos();

            int secuense = 0;
            int part = 0;
            Pasto pasto = new Pasto();
            foreach (Vector3 pastoCoord in pastosCoords)
            {
                pasto.crearPasto(d3dDevice, secuense, pastoCoord);
                if (part == 5)
                {
                    pastos.Add(pasto);
                    pasto = new Pasto();
                }
                secuense++;
                part++;
                if (secuense > 2) secuense = 0;
                if (part > 5) part = 0;
            }
        }