private void crearSemaforos()
        {
            var sceneSemaforo = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Semaforo\\Semaforo-TgcScene.xml");

            semaforo = sceneSemaforo.Meshes[0];

            for (int i = 0; i < veredas.Count; i++)
            {
                var instanciaIda = semaforo.createMeshInstance(semaforo.Name + i);
                instanciaIda.Scale = new Vector3(2, 3, 2);
                instanciaIda.AutoTransformEnable = true;
                var posicionX = (veredas[i].Position.X) + (veredas[i].Size.X) - 20;
                var posicionY = 40;
                var posicionZ = veredas[i].Position.Z + 20;
                instanciaIda.move(posicionX, posicionY, posicionZ);
                instanciaIda.BoundingBox.transform(Matrix.Scaling(new Vector3(0.1f, 3, 0.1f)) * Matrix.Translation(instanciaIda.Position));
                semaforos.Add(instanciaIda);

                var instanciaVuelta = semaforo.createMeshInstance(semaforo.Name + i);
                instanciaVuelta.AutoTransformEnable = true;
                instanciaVuelta.Scale = new Vector3(2, 3, 2);
                var posicionX2 = (veredas[i].Position.X) + 20;
                var posicionY2 = 40;
                var posicionZ2 = veredas[i].Position.Z + (veredas[i].Size.Z) - 20;
                instanciaVuelta.move(posicionX2, posicionY2, posicionZ2);
                instanciaVuelta.rotateY(FastMath.PI);
                instanciaVuelta.BoundingBox.transform(Matrix.Scaling(new Vector3(0.1f, 3, 0.1f)) * Matrix.Translation(instanciaVuelta.Position));
                semaforos.Add(instanciaVuelta);
            }
        }
        // TODO modificar, por ahora es de ejemplo
        private void CreateObjects(int cantidad)
        {
            TgcMesh teapotMesh = Loader.loadSceneFromFile(MediaDir + "Meshes\\Teapot\\Teapot-TgcScene.xml").Meshes[0];

            teapotMesh.Scale = new Vector3(0.5f, 0.5f, 0.5f);

            if (null == Objetos)
            {
                Objetos = new List <InteractiveObject>();
            }

            TgcMesh instance;

            for (int i = 1; i <= cantidad; i++)
            {
                instance = teapotMesh.createMeshInstance(teapotMesh.Name + "_" + i);
                //instance.Scale = GameUtils.getRandomScaleVector();
                instance.Position  = GameUtils.getRandomPositionVector();
                instance.Transform = Matrix.Scaling(instance.Scale) * Matrix.Translation(instance.Position);
                instance.updateBoundingBox();
                InteractiveObject interactiveObject = new InteractiveObject("Teapot", 3, instance, InteractiveObject.Materials.Glass, InteractiveObject.ObjectTypes.Misc);
                interactiveObject.drops.Add(InventoryObject.ObjectTypes.Water);
                interactiveObject.drops.Add(InventoryObject.ObjectTypes.Water);
                Objetos.Add(interactiveObject);
            }
        }
        /// <summary>
        ///     Genera la disposición de los árboles en el mapa
        ///     TODO: hacer que no se toquen...
        /// </summary>
        private void CreateTrees(int cantidad)
        {
            TgcMesh tree = Loader.loadSceneFromFile(MediaDir + "Meshes\\Pino\\Pino-TgcScene.xml").Meshes[0];

            if (null == Objetos)
            {
                Objetos = new List <InteractiveObject>();
            }

            TgcMesh instance;

            for (int i = 1; i <= cantidad; i++)
            {
                instance           = tree.createMeshInstance(tree.Name + "_" + i);
                instance.Scale     = GameUtils.getRandomScaleVector();
                instance.Position  = GameUtils.getRandomPositionVector();
                instance.Transform = Matrix.Scaling(instance.Scale) * Matrix.Translation(instance.Position);
                instance.updateBoundingBox();
                instance.AlphaBlendEnable = true;
                InteractiveObject interactiveObject = new InteractiveObject("Tree", 5, instance, InteractiveObject.Materials.Wood, InteractiveObject.ObjectTypes.Tree);
                interactiveObject.drops.Add(InventoryObject.ObjectTypes.Wood);
                interactiveObject.drops.Add(InventoryObject.ObjectTypes.Leaf);
                Objetos.Add(interactiveObject);
            }
        }
Exemple #4
0
        private void generarBancoPasto(List <TgcMesh> objs, Vector3 pos, Random rdm)
        {
            for (int q = 0; q < 1; q++)
            {
                for (int w = 0; w < 1; w++)
                {
                    scale = rdm.Next(10, 20);

                    TgcMesh pastoBanco = pastoOriginal.createMeshInstance(pastoOriginal.Name + q + w + pos.X + pos.Z);
                    pastoBanco.AlphaBlendEnable = true;
                    pastoBanco.Scale            = new Vector3(0.025f * scale, 0.025f * scale, 0.025f * scale);
                    pastoBanco.move(pos.X + q * 2.6f, 0, pos.Z + w * 2.6f);
                    pastoBanco.UserProperties = new Dictionary <string, string>();
                    pastoBanco.Effect         = treeWindEffect;
                    pastoBanco.Technique      = "SimpleWindGrass";

                    // gana algunos fps
                    pastoBanco.AutoTransformEnable = false;
                    pastoBanco.Transform           =
                        Matrix.Scaling(pastoBanco.Scale) *
                        Matrix.Translation(pastoBanco.Position);

                    objs.Add(pastoBanco);
                }
            }
        }
        protected TgcMesh instanceOf(TgcMesh m)
        {
            TgcMesh i = m.createMeshInstance(m.Name + m.MeshInstances.Count.ToString());

            i.AlphaBlendEnable = m.AlphaBlendEnable;
            return(i);
        }
Exemple #6
0
        private void CreateObjectsFromModel(TgcMesh model, int count, Vector3 center, Vector3 scale, int sparse, float[] scalaVariableObjetos)
        {
            var rnd = new Random();

            // TODO: buscar una mejor forma de tener una distribucion pareja
            var rows = (int)Math.Sqrt(count);
            var cols = (int)Math.Sqrt(count);

            float[] scalaRotacionObjetos = { FastMath.QUARTER_PI, FastMath.PI, FastMath.PI_HALF, FastMath.TWO_PI };

            for (var i = 0; i < rows; i++)
            {
                for (var j = 0; j < cols; j++)
                {
                    var instance = model.createMeshInstance(model.Name + i + "_" + j);
                    instance.AutoTransformEnable = true;

                    // Escalo el objeto en forma Random
                    instance.Scale = scale * scalaVariableObjetos[rnd.Next(0, scalaVariableObjetos.Length)];

                    var x = center.X + rnd.Next(-sparse, sparse);
                    var z = center.Z + rnd.Next(-sparse, sparse);

                    // Posiciono el objeto en el Escenario
                    instance.Position = new Vector3(x * SceneScaleXZ, CalcularAlturaTerreno(x, z) * SceneScaleY, z * SceneScaleXZ);
                    instance.rotateY(scalaRotacionObjetos[rnd.Next(0, scalaRotacionObjetos.Length)]);
                    instance.AlphaBlendEnable = true;
                    instance.Enabled          = true;

                    // Lo guardo en una Lista de Objetos que están en el Escenario
                    SceneMeshes.Add(instance);
                }
            }
        }
        private void crearUnaPlanta(TgcScene unaScene, int i, Vector3 vectorPosicion, int n)
        {
            Planta = unaScene.Meshes[0];
            //      Planta.Scale = new Vector3(1, 3, 1);
            var instancia = Planta.createMeshInstance(Planta.Name + i);

            instancia.AutoTransformEnable = true;
            instancia.AlphaBlendEnable    = true;
            instancia.move(vectorPosicion.X, vectorPosicion.Y, vectorPosicion.Z);


            var scenePasto = loader.loadSceneFromFile(MediaDir + "Pasto\\Pasto-TgcScene.xml");
            var pasto      = scenePasto.Meshes[0];

            pasto.AutoTransformEnable = true;
            pasto.AlphaBlendEnable    = true;
            pasto.move(vectorPosicion.X, vectorPosicion.Y, vectorPosicion.Z);

            if (n == 3)
            {
                instancia.Scale = new Vector3((float)0.5, (float)0.5, (float)0.5);
                pasto.Scale     = new Vector3(1, 1, 1);
            }
            instancia.BoundingBox.transform(Matrix.Scaling(new Vector3(0.1f, 3, 0.1f)) * Matrix.Translation(instancia.Position));
            //     instancia.BoundingBox.scaleTranslate
            arboles.Add(instancia);
            pasto.BoundingBox.transform(Matrix.Scaling(new Vector3(0.2f, 1, 0.2f)) * Matrix.Translation(pasto.Position));
            arboles.Add(pasto);
            meshes.Add(instancia);
            meshes.Add(pasto);
        }
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            meshes = new List <TgcMesh>();

            TgcSceneLoader loader       = new TgcSceneLoader();
            TgcScene       scene        = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\BoxAlpha\\Box-TgcScene.xml");
            TgcMesh        originalMesh = scene.Meshes[0];

            meshes.Add(originalMesh);
            originalMesh.Position         = new Vector3(0, 0, 0);
            originalMesh.AlphaBlendEnable = true;

            TgcMesh instanceMesh;

            for (int i = 0; i < 5; i++)
            {
                instanceMesh                  = originalMesh.createMeshInstance("Box" + (i + 1));
                instanceMesh.Position         = new Vector3(0, 0, i * 50);
                instanceMesh.AlphaBlendEnable = true;
                meshes.Add(instanceMesh);
            }


            GuiController.Instance.FpsCamera.Enable = true;
        }
Exemple #9
0
        protected TgcMesh instanceOf(TgcMesh m)
        {
            var i = m.createMeshInstance(m.Name + m.MeshInstances.Count);

            i.AlphaBlendEnable    = m.AlphaBlendEnable;
            i.AutoTransformEnable = true;
            return(i);
        }
Exemple #10
0
        private TgcMesh CreateMeshInstance(TgcMesh originalMesh, TGCVector3 position, TGCVector3 scale, string name)
        {
            var instance = originalMesh.createMeshInstance(originalMesh.Name + name);

            instance.Transform = TGCMatrix.Scaling(scale) * TGCMatrix.Translation(position);

            instance.Effect    = recoltableItemEffect;
            instance.Technique = "RecolectableItemTechnique";

            return(instance);
        }
Exemple #11
0
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            //Crear suelo
            TgcTexture texture = TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\Quake\\quakeWall3.jpg");

            suelo = TgcBox.fromSize(new Vector3(0, 0, 0), new Vector3(500, 0.1f, 500), texture);


            //Iniciarlizar PickingRay
            pickingRay = new TgcPickingRay();


            //Cargar modelos que se pueden seleccionar
            modelos = new List <TgcMesh>();
            modelosSeleccionados = new List <TgcMesh>();

            //Modelo 1, original
            TgcSceneLoader loader        = new TgcSceneLoader();
            TgcScene       scene         = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Vehiculos\\Carretilla\\Carretilla-TgcScene.xml");
            TgcMesh        modeloOrignal = scene.Meshes[0];

            modelos.Add(modeloOrignal);

            //Modelos instancias del original
            modelos.Add(modeloOrignal.createMeshInstance("Carretilla2", new Vector3(100, 0, 0), Vector3.Empty, new Vector3(1, 1, 1)));
            modelos.Add(modeloOrignal.createMeshInstance("Carretilla3", new Vector3(50, 0, -70), Vector3.Empty, new Vector3(1, 1, 1)));
            modelos.Add(modeloOrignal.createMeshInstance("Carretilla4", new Vector3(-100, 0, -30), Vector3.Empty, new Vector3(1, 1, 1)));
            modelos.Add(modeloOrignal.createMeshInstance("Carretilla5", new Vector3(-70, 0, -80), Vector3.Empty, new Vector3(1, 1, 1)));

            //Crear caja para marcar en que lugar hubo colision
            selectionBox = TgcBox.fromSize(new Vector3(3, SELECTION_BOX_HEIGHT, 3), Color.Red);
            selectionBox.BoundingBox.setRenderColor(Color.Red);
            selecting = false;

            //Camara fija
            GuiController.Instance.RotCamera.Enable = false;
            GuiController.Instance.setCamera(new Vector3(-4.4715f, 239.1167f, 179.248f), new Vector3(-4.4742f, 238.3456f, 178.6113f));
        }
Exemple #12
0
 public Pasto(TgcMesh mesh, Effect effect, int capasCount, float altura) : base(mesh, default, default, default)
 {
     this.altura = altura;
     capas       = new List <TgcMesh>();
     for (int i = 0; i < capasCount; i++)
     {
         TgcMesh pasto = mesh.createMeshInstance("Pasto" + i);
         pasto.Position += TGCVector3.Up * (i * altura / capasCount);
         pasto.Transform = TGCMatrix.Scaling(pasto.Scale) * TGCMatrix.RotationYawPitchRoll(pasto.Rotation.Y, pasto.Rotation.X, pasto.Rotation.Z) * TGCMatrix.Translation(pasto.Position);
         pasto.Effect    = effect.Clone(D3DDevice.Instance.Device);
         pasto.Technique = "Pasto";
         pasto.Effect.SetValue("nivel", (float)i / capasCount);
         capas.Add(pasto);
     }
 }
Exemple #13
0
        public Ruedas(TgcMesh ruedaMainMesh, Vector3 offsetRuedaIzq, Vector3 offsetRuedaDer, bool sonDelanteras, float scale)
        {
            scale3         = new Vector3(scale, scale, scale);
            OffsetRuedaDer = offsetRuedaDer;
            OffsetRuedaIzq = offsetRuedaIzq;
            //Escala = scale3;
            Escala = new Vector3(2f, 2f, 2f);
            angulo = 0;
            //Escala = ruedaMainMesh.Scale;
            SonDelanteras = sonDelanteras;

            //------------------- RUEDA IZQUIERDA --------------------------
            RuedaMeshIzq = ruedaMainMesh.createMeshInstance
                               (ruedaMainMesh.Name + offsetRuedaIzq.ToString() + "_Izq");
            RuedaMeshIzq.Scale = scale3;
            RuedaMeshIzq.AutoTransformEnable = false;
            MatrizPosInicialIzquierda        = Matrix.Translation(OffsetRuedaIzq);
            //------------------- RUEDA DERECHA   --------------------------
            RuedaMeshDer = ruedaMainMesh.createMeshInstance
                               (ruedaMainMesh.Name + offsetRuedaDer.ToString() + "_Der");
            RuedaMeshDer.Scale = scale3;
            RuedaMeshDer.AutoTransformEnable = false;
            MatrizPosInicialDerecha          = Matrix.Translation(offsetRuedaDer);
        }
        public void GenerateDuplicates(TgcMesh common, ref List <TypeCommon> commons, int quantity, bool createRB = true)
        {
            foreach (int index in Enumerable.Range(0, quantity))
            {
                TypeCommon newCommon = new TypeCommon
                {
                    Quantity = index,
                    Name     = common.Name + "_" + index
                };
                newCommon.Mesh           = common.createMeshInstance(newCommon.Name);
                newCommon.Mesh.Transform = TGCMatrix.Scaling(Constants.Scale);
                if (createRB)
                {
                    CreateRigidBody(ref newCommon);
                }

                commons.Add(newCommon);
            }
        }
Exemple #15
0
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            //Crear suelo
            TgcTexture pisoTexture = TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\pasto.jpg");

            suelo = TgcBox.fromSize(new Vector3(500, 0, 500), new Vector3(2000, 0, 2000), pisoTexture);

            //Cargar modelo de palmera original
            TgcSceneLoader loader = new TgcSceneLoader();
            TgcScene       scene  = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera\\Palmera-TgcScene.xml");

            palmeraOriginal = scene.Meshes[0];

            //Crear varias instancias del modelo original, pero sin volver a cargar el modelo entero cada vez
            int   rows   = 5;
            int   cols   = 6;
            float offset = 200;

            meshes = new List <TgcMesh>();
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    //Crear instancia de modelo
                    TgcMesh instance = palmeraOriginal.createMeshInstance(palmeraOriginal.Name + i + "_" + j);

                    //Desplazarlo
                    instance.move(i * offset, 70, j * offset);
                    instance.Scale = new Vector3(0.25f, 0.25f, 0.25f);

                    meshes.Add(instance);
                }
            }


            //Camara en primera persona
            GuiController.Instance.FpsCamera.Enable        = true;
            GuiController.Instance.FpsCamera.MovementSpeed = 400;
            GuiController.Instance.FpsCamera.JumpSpeed     = 400;
            GuiController.Instance.FpsCamera.setCamera(new Vector3(61.8657f, 403.7024f, -527.558f), new Vector3(379.7143f, 12.9713f, 336.3295f));
        }
        public override void Init()
        {
            //Crear suelo
            var pisoTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\pasto.jpg");

            suelo = new TgcPlane(new TGCVector3(-500, 0, -500), new TGCVector3(2000, 0, 2000), TgcPlane.Orientations.XZplane, pisoTexture, 10f, 10f);

            //Cargar modelo de palmera original
            var loader = new TgcSceneLoader();
            var scene  =
                loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera\\Palmera-TgcScene.xml");

            palmeraOriginal = scene.Meshes[0];

            //Crear varias instancias del modelo original, pero sin volver a cargar el modelo entero cada vez
            var   rows   = 5;
            var   cols   = 6;
            float offset = 250;

            meshes = new List <TgcMesh>();
            for (var i = 0; i < rows; i++)
            {
                for (var j = 0; j < cols; j++)
                {
                    //Crear instancia de modelo
                    var instance = palmeraOriginal.createMeshInstance(palmeraOriginal.Name + i + "_" + j);
                    //No recomendamos utilizar AutoTransform, en juegos complejos se pierde el control. mejor utilizar Transformaciones con matrices.
                    instance.AutoTransform = true;
                    //Desplazarlo
                    instance.Move(i * offset, 0, j * offset);
                    //instance.Scale = new TGCVector3(0.25f, 0.25f, 0.25f);

                    meshes.Add(instance);
                }
            }

            //Camara en primera persona
            Camara = new TgcFpsCamera(new TGCVector3(900f, 400f, 900f), Input);
        }
        public override void Init()
        {
            //Crear suelo
            var pisoTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\pasto.jpg");

            suelo = TgcBox.fromSize(new Vector3(500, 0, 500), new Vector3(2000, 0, 2000), pisoTexture);

            //Cargar modelo de palmera original
            var loader = new TgcSceneLoader();
            var scene  =
                loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera\\Palmera-TgcScene.xml");

            palmeraOriginal = scene.Meshes[0];

            //Crear varias instancias del modelo original, pero sin volver a cargar el modelo entero cada vez
            var   rows   = 5;
            var   cols   = 6;
            float offset = 200;

            meshes = new List <TgcMesh>();
            for (var i = 0; i < rows; i++)
            {
                for (var j = 0; j < cols; j++)
                {
                    //Crear instancia de modelo
                    var instance = palmeraOriginal.createMeshInstance(palmeraOriginal.Name + i + "_" + j);

                    //Desplazarlo
                    instance.move(i * offset, 70, j * offset);
                    instance.Scale = new Vector3(0.25f, 0.25f, 0.25f);

                    meshes.Add(instance);
                }
            }

            //Camara en primera persona
            Camara = new TgcFpsCamera(new Vector3(61.8657f, 403.7024f, -527.558f));
        }
        /// <summary>
        ///     Genera las piedras en el mapa
        /// </summary>
        /// <param name="cantidad"></param>
        private void CreateRocks(int cantidad)
        {
            TgcMesh rock = Loader.loadSceneFromFile(MediaDir + "Meshes\\Roca\\Roca-TgcScene.xml").Meshes[0];

            if (null == Objetos)
            {
                Objetos = new List <InteractiveObject>();
            }

            TgcMesh instance;

            for (int i = 1; i <= cantidad; i++)
            {
                instance           = rock.createMeshInstance(rock.Name + "_" + i);
                instance.Scale     = GameUtils.getRandomScaleVector() * 0.2f;
                instance.Position  = GameUtils.getRandomPositionVector();
                instance.Transform = Matrix.Scaling(instance.Scale) * Matrix.Translation(instance.Position);
                instance.updateBoundingBox();
                //instance.AlphaBlendEnable = true;
                InteractiveObject interactiveObject = new InteractiveObject("Rock", 1, instance, InteractiveObject.Materials.Rock, InteractiveObject.ObjectTypes.Rock);
                interactiveObject.drops.Add(InventoryObject.ObjectTypes.Rock);
                Objetos.Add(interactiveObject);
            }
        }
        private void CrearObjetosEnElEscenario(CustomVertex.PositionNormalTextured[] vertices)
        {
            Random random             = new Random();
            int    posicionesTotales  = vertices.Length; // Le resto 2 para que no tener en cuenta los bordes del mapa
            int    posicionesASaltear = 1;               // Este valor se cambia adentro del for con un random
            int    minSalto           = 1;               // Valores para usar en el next del random para saltear
            int    maxSalto           = 9;

            for (int i = verticesWidth; i < posicionesTotales; i += posicionesASaltear)
            {
                CustomVertex.PositionNormalTextured verticeActual = vertices[i];
                TGCVector3 rotation = TGCVector3.Up * random.Next(10);
                int        scale    = random.Next(10, 30);
                TGCVector3 position = MathExtended.Vector3ToTGCVector3(verticeActual.Position);
                TgcMesh    mesh     = meshesPlantas[random.Next(meshesPlantas.Count)];

                //GameInstance.InstanceObject(new Collectable(GameInstance, "coral", new List<TgcMesh>(new TgcMesh[] { mesh.createMeshInstance("coral") }), position, scale, rotation, Items.EItemID.CORAL_PIECE));
                GameInstance.InstanceStaticSceneObject(new Collectable(GameInstance, "coral", new List <TgcMesh>(new TgcMesh[] { mesh.createMeshInstance("coral") }), position, scale, rotation, Items.EItemID.CORAL_PIECE));
                posicionesASaltear = random.Next(minSalto, maxSalto);
            }
        }
Exemple #20
0
 private void LoadShip()
 {
     OutdoorMesh = new TgcSceneLoader().loadSceneFromFile(MediaDir + Constants.FILE_NAME).Meshes[0];
     IndoorMesh  = OutdoorMesh.createMeshInstance("InsideRoom");
 }
Exemple #21
0
        public override void Init()
        {
            //Crear loader
            var loader = new TgcSceneLoader();

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

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

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

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

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

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

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

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

            largo_tanque              = Math.Abs(size.Z);
            alto_tanque               = Math.Abs(size.Y) * mesh.Scale.Y;
            vel_tanque                = 10;
            an_tanque                 = 0;
            canoa.Scale               = new 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();
            var alto_palmera = Math.Abs(size.Y);

            cant_palmeras = 0;
            int i;

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

            // Arreglo las normales del tanque

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

            g_pCubeMapAgua = null;

            //Cargar Shader personalizado
            effect =
                TgcShaders.loadEffect(ShadersDir + "WorkshopShaders\\Demo.fx");

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

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

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

            g_mShadowProj = Matrix.PerspectiveFovLH(Geometry.DegreeToRadian(130.0f),
                                                    aspectRatio, near_plane, far_plane);
            D3DDevice.Instance.Device.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;
            CamaraRot  = new TgcRotationalCamera(mesh.BoundingBox.calculateBoxCenter(),
                                                 mesh.BoundingBox.calculateBoxRadius() * 2);
            CamaraRot.CameraDistance = 300;
            CamaraRot.RotationSpeed  = 1.5f;
            DefaultCamera            = new TgcRotationalCamera(new Vector3(0, 200, 0), 5000, 0.1f, 1f);
            Camara = DefaultCamera;

            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  = D3DDevice.Instance.Width;
            View1.Height = D3DDevice.Instance.Height / 2;
            View1.MinZ   = 0;
            View1.MaxZ   = 1;
            View2        = new Viewport();
            View2.X      = 0;
            View2.Y      = View1.Height;
            View2.Width  = D3DDevice.Instance.Width;
            View2.Height = D3DDevice.Instance.Height / 2;
            View2.MinZ   = 0;
            View2.MaxZ   = 1;

            ViewF = D3DDevice.Instance.Device.Viewport;
        }
Exemple #22
0
        public override void Init()
        {
            MyMediaDir  = MediaDir;
            MyShaderDir = ShadersDir + "WorkshopShaders\\";

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

            // ------------------------------------------------------------
            // Creo el Heightmap para el terreno:
            var PosTerrain = new Vector3(0, 0, 0);

            currentHeightmap = MyMediaDir + "Heighmaps\\Heightmap2.jpg";
            currentScaleXZ   = 100f;
            currentScaleY    = 2f;
            currentTexture   = MyMediaDir + "Heighmaps\\TerrainTexture3.jpg";
            terrain          = new TgcSimpleTerrain();
            terrain.loadHeightmap(currentHeightmap, currentScaleXZ, currentScaleY, PosTerrain);
            terrain.loadTexture(currentTexture);

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

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

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

            sceneX = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Sphere\\Sphere-TgcScene.xml");
            meshX  = sceneX.Meshes[0];

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

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

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

            largo_tanque              = Math.Abs(size.Z);
            alto_tanque               = Math.Abs(size.Y) * mesh.Scale.Y;
            avion.Scale               = new Vector3(1f, 1f, 1f);
            avion.Position            = new Vector3(3000f, 550f, 0f);
            avion.AutoTransformEnable = false;
            dir_avion = new Vector3(0, 0, 1);
            size      = palmera.BoundingBox.calculateSize();
            var alto_palmera = Math.Abs(size.Y);
            int i;

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

            // Arreglo las normales del tanque

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

            // Arreglo las normales de la esfera
            {
                var adj = new int[meshX.D3dMesh.NumberFaces * 3];
                meshX.D3dMesh.GenerateAdjacency(0, adj);
                meshX.D3dMesh.ComputeNormals(adj);
            }

            //Cargar Shader personalizado
            effect =
                TgcShaders.loadEffect(ShadersDir + "WorkshopShaders\\EnvMap.fx");

            // le asigno el efecto a la malla
            mesh.Effect  = effect;
            meshX.Effect = effect;

            vel_tanque = 10;

            //Centrar camara rotacional respecto a este mesh
            CamaraRot = new TgcRotationalCamera(mesh.BoundingBox.calculateBoxCenter(),
                                                mesh.BoundingBox.calculateBoxRadius() * 2);
            CamaraRot.CameraDistance = 300;
            CamaraRot.RotationSpeed  = 1.5f;
            Camara = CamaraRot;

            kx = kc = 0.5f;
            Modifiers.addFloat("Reflexion", 0, 1, kx);
            Modifiers.addFloat("Refraccion", 0, 1, kc);
            Modifiers.addBoolean("Fresnel", "fresnel", true);
        }
Exemple #23
0
        public PlayScene()
        {
            string mediaDir         = GuiController.Instance.AlumnoEjemplosMediaDir;
            string examplesMediaDir = GuiController.Instance.ExamplesMediaDir;

            TgcTexture pisoTexture = TgcTexture.createTexture(GuiController.Instance.D3dDevice,
                                                              mediaDir + "CEGA\\Textures\\Grass.jpg");

            suelo = TgcBox.fromSize(new Vector3(1300, 0, 1300), new Vector3(2800, 0, 2800), pisoTexture);


            heightMap = new SimpleTerrain();

            heightMap.loadHeightmap(GuiController.Instance.AlumnoEjemplosMediaDir + "CEGA\\Heightmap\\" + "hmap4.jpg", 26, 0.4f, new Vector3(52, 0, 48));
            heightMap.loadTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "CEGA\\Textures\\" + "Pasto2.jpg");


            treeWindEffect = TgcShaders.loadEffect(
                GuiController.Instance.AlumnoEjemplosMediaDir + "CEGA\\Shaders\\TreeWind.fx");

            TgcSceneLoader loader       = new TgcSceneLoader();
            TgcScene       scene        = loader.loadSceneFromFile(mediaDir + "CEGA\\Pino-TgcScene.xml");
            TgcMesh        pinoOriginal = scene.Meshes[0];

            scene = loader.loadSceneFromFile(mediaDir + "CEGA\\BarrilPolvora-TgcScene.xml");
            TgcMesh barrilOriginal = scene.Meshes[0];

            scene         = loader.loadSceneFromFile(mediaDir + "CEGA\\Pasto3-TgcScene.xml");
            pastoOriginal = scene.Meshes[0];

            //Crear varias instancias del modelo original, pero sin volver a cargar el modelo entero cada vez, hace 23*23 = 529 pinos
            int rows = 22;
            int cols = 22;

            Random RandomPlayScene = new Random(10);

            int offset = RandomPlayScene.Next(100);

            otrosObjetos = new List <TgcMesh>();

            for (int i = 1; i <= rows; i++)
            {
                for (int j = 1; j <= cols; j++)
                {
                    //Randomeo el proximo offset, de esta forma nunca vamos a tener 2 escenarios iguales, si queremos evitar que se superpongan cosas hay que fijarse acá.
                    //Si les parece que quedan muy concentrados en el origen podemos separarlo en 2 For (o en 4) para que no se peguen tanto cuando i=1 y j=1.

                    offset = RandomPlayScene.Next(50, 150);
                    scale  = RandomPlayScene.Next(10, 30);

                    //Me fijo que quede dentro de los limites del mapa

                    if (i * offset > 2600 || j * offset > 2600)
                    {
                        offset = RandomPlayScene.Next(10, 100);
                    }

                    //Crear instancia de modelo
                    //  Barriles
                    if (i == 21)
                    {
                        TgcMesh BarrilInstance = barrilOriginal.createMeshInstance(barrilOriginal.Name + i + j);
                        BarrilInstance.move(j * offset, 0, i * offset);
                        BarrilInstance.AlphaBlendEnable = true;
                        BarrilInstance.Scale            = new Vector3(0.09f, 0.09f, 0.09f);

                        // gana algunos fps
                        BarrilInstance.AutoTransformEnable = false;
                        BarrilInstance.Transform           =
                            Matrix.Scaling(BarrilInstance.Scale) *
                            Matrix.Translation(BarrilInstance.Position);

                        BarrilInstance.UserProperties = new Dictionary <string, string>();
                        BarrilInstance.UserProperties["colisionable"] = "";

                        otrosObjetos.Add(BarrilInstance);
                    }

                    //  Pinos
                    //

                    TgcMesh instance = pinoOriginal.createMeshInstance(pinoOriginal.Name + i + "_" + j);

                    instance.AlphaBlendEnable = true;
                    instance.Position         = new Vector3(i * offset, 0, j * offset);
                    instance.Scale            = new Vector3(0.05f * (scale), 0.05f * (scale), 0.05f * (scale));

                    // gana algunos fps
                    instance.AutoTransformEnable = false;
                    instance.Transform           =
                        Matrix.Scaling(instance.Scale) *
                        Matrix.Translation(instance.Position);

                    instance.UserProperties = new Dictionary <string, string>();
                    instance.UserProperties["colisionable"] = "";

                    //Modifico el BB del arbol para que sea solo el tronco
                    instance.AutoUpdateBoundingBox = false;
                    instance.BoundingBox.scaleTranslate(instance.Position, new Vector3(0.0012f * instance.BoundingBox.calculateSize().X, 0.0016f * instance.BoundingBox.calculateSize().Y, 0.0012f * instance.BoundingBox.calculateSize().Z));
                    //Effecto de Viento (Shader);
                    instance.Effect    = treeWindEffect;
                    instance.Technique = "SimpleWindTree";
                    //Agrego a la coleccion
                    otrosObjetos.Add(instance);

                    //  Bancos de Pasto

                    if (j == 20)
                    {
                        generarBancoPasto(otrosObjetos, new Vector3(j * offset, 0, i * offset), RandomPlayScene);
                    }
                }
            }

            //Sky Box

            string texturesPath = mediaDir + "CEGA\\Skyboxes\\SkyBox4\\";

            //Creo el SkyBox
            skyBox        = new TgcSkyBox();
            skyBox.Center = new Vector3(1300, 250, 1300);
            skyBox.Size   = new Vector3(4000, 1500, 4000);

            //Cargo las texturas de las caras, (algunas no tienen "down" así que uso TOP, por que igual no se debería ver en nuestro caso)
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "top.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "top.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "left.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "right.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "front.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "back.jpg");

            //Actualizar todos los valores para crear el SkyBox
            skyBox.updateValues();

            sound_WindLong = new TgcStaticSound();
            sound_WindLong.loadSound(mediaDir + @"CEGA\Sound\viento_largo.wav", -2000);

            sound_WindMedium = new TgcStaticSound();
            sound_WindMedium.loadSound(mediaDir + @"CEGA\Sound\viento_medio.wav", -2000);

            sound_WindLeaves = new TgcStaticSound();
            sound_WindLeaves.loadSound(examplesMediaDir + @"\Sound\viento en arbustos.wav", -2000);

            sound_music = new TgcStaticSound();
            sound_music.loadSound(mediaDir + @"CEGA\Sound\rabbia.wav", -2000);
            sound_music.play(true);

            //Crear Grilla
            grilla = new GrillaRegular();
            grilla.create(otrosObjetos, heightMap.BoundingBox);
            grilla.createDebugMeshes();
        }
Exemple #24
0
        public override void Init()
        {
            //Crear loader
            var loader = new TgcSceneLoader();

            //Cargar mesh
            scene = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Teapot\\Teapot-TgcScene.xml");

            mesh          = scene.Meshes[0];
            mesh.Scale    = TGCVector3.One;
            mesh.Position = new TGCVector3(-100f, -5f, 0f);

            // Arreglo las normales
            var adj = new int[mesh.D3dMesh.NumberFaces * 3];

            mesh.D3dMesh.GenerateAdjacency(0, adj);
            mesh.D3dMesh.ComputeNormals(adj);

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

            // le asigno el efecto a la malla
            mesh.Effect    = effect;
            mesh.Technique = "DefaultTechnique";

            // Creo las instancias de malla
            instances = new List <TgcMesh>();
            for (var i = -5; i < 5; i++)
            {
                for (var j = -5; j < 5; j++)
                {
                    var instance = mesh.createMeshInstance(mesh.Name + i);
                    instance.Position  = new TGCVector3(i * 50, (i + j) * 5, j * 50);
                    instance.Transform = TGCMatrix.Scaling(instance.Scale)
                                         * TGCMatrix.RotationYawPitchRoll(instance.Rotation.X, instance.Rotation.Y, instance.Rotation.Z)
                                         * TGCMatrix.Translation(instance.Position);
                    instances.Add(instance);
                }
            }

            blurActivatedModifier = AddBoolean("blurActivated", "activar blur", false);
            lightPositionModifier = AddVertex3f("LightPosition", new TGCVector3(-100, -100, -100), new TGCVector3(100, 100, 100), new TGCVector3(0, 40, 0));
            ambientModifier       = AddFloat("Ambient", 0, 1, 0.5f);
            diffuseModifier       = AddFloat("Diffuse", 0, 1, 0.6f);
            specularModifier      = AddFloat("Specular", 0, 1, 0.5f);
            specularPowerModifier = AddFloat("SpecularPower", 1, 100, 16);

            Camera = new TgcRotationalCamera(new TGCVector3(20, 20, 0), 300, TgcRotationalCamera.DEFAULT_ZOOM_FACTOR, 1.5f, Input);

            // Creo un depthbuffer sin multisampling, para que sea compatible con el render to texture

            // Nota:
            // El render to Texture no es compatible con el multisampling en dx9
            // Por otra parte la mayor parte de las placas de ultima generacion no soportan
            // mutisampling para texturas de punto flotante con lo cual
            // hay que suponer con generalidad que no se puede usar multisampling y render to texture

            // Para resolverlo hay que crear un depth buffer que no tenga multisampling,
            // (de lo contrario falla el zbuffer y se producen artifacts tipicos de que no tiene zbuffer)

            // Si uno quisiera usar el multisampling, la tecnica habitual es usar un RenderTarget
            // en lugar de una textura.
            // Por ejemplo en c++:
            //
            // Render Target formato color buffer con multisampling
            //
            //  g_pd3dDevice->CreateRenderTarget(Ancho,Alto,
            //          D3DFMT_A8R8G8B8, D3DMULTISAMPLE_2_SAMPLES, 0,
            //          FALSE, &g_pRenderTarget, NULL);
            //
            // Luego, ese RenderTarget NO ES una textura, y nosotros necesitamos acceder a esos
            // pixeles, ahi lo que se hace es COPIAR del rendertartet a una textura,
            // para poder trabajar con esos datos en el contexto del Pixel shader:
            //
            // Eso se hace con la funcion StretchRect:
            // copia de rendertarget ---> sceneSurface (que es la superficie asociada a una textura)
            // g_pd3dDevice->StretchRect(g_pRenderTarget, NULL, g_pSceneSurface, NULL, D3DTEXF_NONE);
            //
            // Esta tecnica se llama downsampling
            // Y tiene el costo adicional de la transferencia de memoria entre el rendertarget y la
            // textura, pero que no traspasa los limites de la GPU. (es decir es muy performante)
            // no es lo mismo que lockear una textura para acceder desde la CPU, que tiene el problema
            // de transferencia via AGP.

            g_pDepthStencil = D3DDevice.Instance.Device.CreateDepthStencilSurface(D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth,
                                                                                  D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true);

            // inicializo el render target
            g_pRenderTarget = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth,
                                          D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default);

            effect.SetValue("g_RenderTarget", g_pRenderTarget);

            // inicializo el mapa de normales
            g_pNormals = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth,
                                     D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);

            effect.SetValue("g_Normals", g_pNormals);

            // Resolucion de pantalla
            effect.SetValue("screen_dx", D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth);
            effect.SetValue("screen_dy", D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight);

            //Se crean 2 triangulos con las dimensiones de la pantalla con sus posiciones ya transformadas
            // x = -1 es el extremo izquiedo de la pantalla, x=1 es el extremo derecho
            // Lo mismo para la Y con arriba y abajo
            // la Z en 1 simpre
            CustomVertex.PositionTextured[] vertices =
            {
                new CustomVertex.PositionTextured(-1,  1, 1, 0, 0),
                new CustomVertex.PositionTextured(1,   1, 1, 1, 0),
                new CustomVertex.PositionTextured(-1, -1, 1, 0, 1),
                new CustomVertex.PositionTextured(1,  -1, 1, 1, 1)
            };
            //vertex buffer de los triangulos
            g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, D3DDevice.Instance.Device, Usage.Dynamic | Usage.WriteOnly,
                                        CustomVertex.PositionTextured.Format, Pool.Default);
            g_pVBV3D.SetData(vertices, 0, LockFlags.None);
        }
        private bool dibujarEdificio(int nMesh, int i, int j, TgcScene scene)
        {
            float offset_row = 300;
            float offset_Col = 100;
            float offset_Y   = 5;

            if (nMesh == 0)
            { //Edificio Blanco Espejado - chiquito
                offset_row = 220 + ((i - 1) * 900);
                offset_Col = 10 + ((j - 1) * 900);
            }
            if (nMesh == 2)
            {//Edicio Ladrillos
                offset_row = -280 + ((i - 1) * 900);
                offset_Col = 480 + ((j - 1) * 900);
            }
            if (nMesh == 3)
            { //edifcio amarillo
                offset_row = 1050 + ((i - 1) * 900);
                offset_Col = 900 + ((j - 1) * 900);
            }

            if (nMesh == 4)
            { //Edificio espejado - gris mediano
                offset_row = 300 + ((i - 1) * 900);
                offset_Col = 1000 + ((j - 1) * 900);
                offset_Y   = -65;
            }
            if (nMesh == 5)
            { //Edificio alto blanco finito espejado
                offset_row = 1020 + ((i - 1) * 900);
                offset_Col = -400 + ((j - 1) * 900);
            }
            if (nMesh == 6)
            { //Edificio gris U
                offset_row = -130 + ((i - 1) * 900);
                offset_Col = -380 + ((j - 1) * 900);
            }
            if (nMesh == 7)
            { //Edificio alto blanco finito espejado - Rascacielos blanco
                offset_row = 1065 + ((i - 1) * 900);
                offset_Col = 200 + ((j - 1) * 900);
            }

            edificio = scene.Meshes[nMesh];

            var instance = edificio.createMeshInstance(edificio.Name + i + "_" + j);

            //No recomendamos utilizar AutoTransform, en juegos complejos se pierde el control. mejor utilizar Transformaciones con matrices.
            instance.AutoTransformEnable = true; //AS
                                                 //Desplazarlo
                                                 //  Vector3 scale3 = new Vector3(1f, 1f, 1f);
                                                 // var m = Matrix.Scaling(scale3) * Matrix.RotationY(0.001f) * Matrix.Translation(new Vector3(100, 5, 3000));

            //  instance.Transform = m;
            // instance.Position = new Vector3(100, 5, 3000);

            //Matrix m=new Matrix();
            //Vector3 pos = new Vector3(offset_row + fix_posX, offset_Y, offset_Col + fix_posZ);
            instance.move(offset_row + fix_posX, offset_Y, offset_Col + fix_posZ);

            //m = Matrix.Scaling(new Vector3(1f, 1f, 1f)) * Matrix.RotationY(0.001f) * Matrix.Translation(pos);
            if (nMesh == 0)
            {
                instance.Scale = new Vector3(0.70f, 1f, 1f);
                //m = Matrix.Scaling(new Vector3(0.70f, 1f, 1f)) * Matrix.RotationY(0.0001f) * Matrix.Translation(pos);
            }
            if (nMesh == 4)
            {
                instance.Scale = new Vector3(0.40f, 1f, 1f);
                //  m = Matrix.Scaling(new Vector3(0.40f, 1f, 1f)) * Matrix.RotationY(0.001f) * Matrix.Translation(pos);
            }
            //  instance.Transform = m;
            // instance.Position = pos;

            edificios.Add(instance);

            var posicionX = instance.BoundingBox.calculateBoxCenter().X - (550 / 2);
            var posicionZ = instance.BoundingBox.calculateBoxCenter().Z - (550 / 2);
            var posicion  = new Vector3(posicionX, 5, posicionZ);

            veredas.Add(new TgcPlane(posicion, new Vector3(550, 0, 550), TgcPlane.Orientations.XZplane, veredaTexture, 60, 60));
            cordones.Add(new TgcPlane(new Vector3(posicion.X, 0, posicion.Z), new Vector3(550, 5, 0), TgcPlane.Orientations.XYplane, cordonTexture, 40, 1));
            cordones.Add(new TgcPlane(new Vector3(posicion.X + 550, 0, posicion.Z), new Vector3(0, 5, 550), TgcPlane.Orientations.YZplane, cordonTexture, 1, 40));
            cordones.Add(new TgcPlane(new Vector3(posicion.X, 0, posicion.Z + 550), new Vector3(550, 5, 0), TgcPlane.Orientations.XYplane, cordonTexture, 40, 1));
            cordones.Add(new TgcPlane(new Vector3(posicion.X, 0, posicion.Z), new Vector3(0, 5, 550), TgcPlane.Orientations.YZplane, cordonTexture, 1, 40));

            return(true);
        }