예제 #1
0
        public override void Init()
        {
            //Paths para archivo XML de la malla
            var pathMesh = MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml";

            //Path para carpeta de texturas de la malla
            var mediaPath = MediaDir + "SkeletalAnimations\\Robot\\";

            //Lista de animaciones disponibles
            string[] animationList =
            {
                "Parado",
                "Caminando",
                "Correr",
                "PasoDerecho",
                "PasoIzquierdo",
                "Empujar",
                "Patear",
                "Pegar",
                "Arrojar"
            };

            //Crear rutas con cada animacion
            var animationsPath = new string[animationList.Length];

            for (var i = 0; i < animationList.Length; i++)
            {
                animationsPath[i] = mediaPath + animationList[i] + "-TgcSkeletalAnim.xml";
            }

            //Cargar mesh y animaciones
            var loader = new TgcSkeletalLoader();

            mesh = loader.loadMeshAndAnimationsFromFile(pathMesh, mediaPath, animationsPath);

            //Crear esqueleto a modo Debug
            mesh.buildSkletonMesh();

            //Agregar combo para elegir animacion
            selectedAnim      = animationList[0];
            animationModifier = AddInterval("animation", animationList, 0);

            //Modifier para especificar si la animacion se anima con loop
            var animateWithLoop = true;

            loopModifier = AddBoolean("loop", "Loop anim:", animateWithLoop);

            //Modifier para renderizar el esqueleto
            var renderSkeleton = false;

            renderSkeletonModifier = AddBoolean("renderSkeleton", "Show skeleton:", renderSkeleton);

            //Modifier para FrameRate
            frameRateModifier = AddFloat("frameRate", 0, 100, 30);

            //Modifier para color
            currentColor  = Color.White;
            colorModifier = AddColor("Color", currentColor);

            //Modifier para BoundingBox
            boundingBoxModifier = AddBoolean("BoundingBox", "BoundingBox:", false);

            //Modifier para habilitar attachment
            showAttachment     = false;
            attachmentModifier = AddBoolean("Attachment", "Attachment:", showAttachment);

            //Elegir animacion Caminando
            mesh.playAnimation(selectedAnim, true);

            //Crear caja como modelo de Attachment del hueso "Bip01 L Hand"
            attachment = new TgcSkeletalBoneAttach();
            var attachmentBox = TGCBox.fromSize(new TGCVector3(5, 100, 5), Color.Blue);

            attachment.Mesh   = attachmentBox.ToMesh("attachment");
            attachment.Bone   = mesh.getBoneByName("Bip01 L Hand");
            attachment.Offset = TGCMatrix.Translation(10, -40, 0);
            attachment.updateValues();

            //Configurar camara
            Camera = new TgcRotationalCamera(new TGCVector3(0, 70, 0), 200, Input);
        }
        public override void Init()
        {
            //Crear piso
            var pisoTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\tierra.jpg");

            piso = new TgcPlane(new Vector3(-500, -60, -500), new Vector3(1000, 0, 1000), TgcPlane.Orientations.XZplane, pisoTexture);

            //Cargar obstaculos y posicionarlos. Los obstáculos se crean con TgcBox en lugar de cargar un modelo.
            obstaculos = new List <TgcBox>();
            TgcBox obstaculo;

            //Obstaculo 1
            obstaculo = TgcBox.fromSize(new Vector3(-100, 0, 0), new Vector3(80, 150, 80),
                                        TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\baldosaFacultad.jpg"));
            //No es recomendado utilizar autotransform en casos mas complicados, se pierde el control.
            obstaculo.AutoTransformEnable = true;
            obstaculos.Add(obstaculo);

            //Obstaculo 2
            obstaculo = TgcBox.fromSize(new Vector3(50, 0, 200), new Vector3(80, 300, 80),
                                        TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\madera.jpg"));
            //No es recomendado utilizar autotransform en casos mas complicados, se pierde el control.
            obstaculo.AutoTransformEnable = true;
            obstaculos.Add(obstaculo);

            //Obstaculo 3
            obstaculo = TgcBox.fromSize(new Vector3(300, 0, 100), new Vector3(80, 100, 150),
                                        TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\granito.jpg"));
            //No es recomendado utilizar autotransform en casos mas complicados, se pierde el control.
            obstaculo.AutoTransformEnable = true;
            obstaculos.Add(obstaculo);

            //Cargar personaje con animaciones
            var skeletalLoader = new TgcSkeletalLoader();

            personaje =
                skeletalLoader.loadMeshAndAnimationsFromFile(
                    MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml",
                    MediaDir + "SkeletalAnimations\\Robot\\",
                    new[]
            {
                MediaDir + "SkeletalAnimations\\Robot\\Caminando-TgcSkeletalAnim.xml",
                MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml"
            });

            //Le cambiamos la textura para diferenciarlo un poco
            personaje.changeDiffuseMaps(new[]
            {
                TgcTexture.createTexture(D3DDevice.Instance.Device,
                                         MediaDir + "SkeletalAnimations\\Robot\\Textures\\uvwGreen.jpg")
            });

            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);
            //No es recomendado utilizar autotransform en casos mas complicados, se pierde el control.
            personaje.AutoTransformEnable = true;

            //Escalarlo porque es muy grande
            personaje.Position = new Vector3(0, -45, 0);
            personaje.Scale    = new Vector3(0.75f, 0.75f, 0.75f);
            //Rotarlo 180° porque esta mirando para el otro lado
            personaje.rotateY(Geometry.DegreeToRadian(180f));

            //Configurar camara en Tercer Persona
            camaraInterna = new TgcThirdPersonCamera(personaje.Position, 200, -300);
            Camara        = camaraInterna;

            //Modifier para ver BoundingBox
            Modifiers.addBoolean("showBoundingBox", "Bouding Box", false);
            Modifiers.addBoolean("activateSliding", "Activate Sliding", false);

            //Modifiers para desplazamiento del personaje
            Modifiers.addFloat("VelocidadCaminar", 1f, 400f, 250f);
            Modifiers.addFloat("VelocidadRotacion", 1f, 360f, 120f);
        }
        public override void Init()
        {
            //Cargar escenario específico para este ejemplo. Este escenario tiene dos layers: objetos normales y objetos con colisión a nivel de triángulo.
            //La colisión a nivel de triángulos es costosa. Solo debe utilizarse para objetos puntuales (como el piso). Y es recomendable dividirlo en varios
            //meshes (y no hacer un único piso que ocupe todo el escenario)
            var loader = new TgcSceneLoader();

            escenario = loader.loadSceneFromFile(MediaDir + "\\MeshCreator\\Scenes\\Mountains\\Mountains-TgcScene.xml");

            //Cargar personaje con animaciones
            var skeletalLoader = new TgcSkeletalLoader();

            personaje =
                skeletalLoader.loadMeshAndAnimationsFromFile(
                    MediaDir + "SkeletalAnimations\\BasicHuman\\BasicHuman-TgcSkeletalMesh.xml",
                    new[]
            {
                MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\Walk-TgcSkeletalAnim.xml",
                MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\StandBy-TgcSkeletalAnim.xml",
                MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\Jump-TgcSkeletalAnim.xml"
            });

            //Se utiliza autotransform, aunque este es un claro ejemplo de que no se debe usar autotransform,
            //hay muchas operaciones y la mayoria las maneja el manager de colisiones, con lo cual se esta
            //perdiendo el control de las transformaciones del personaje.
            personaje.AutoTransformEnable = true;
            //Configurar animacion inicial
            personaje.playAnimation("StandBy", true);
            //Escalarlo porque es muy grande
            personaje.Position = new Vector3(0, 1000, -150);
            //Rotarlo 180° porque esta mirando para el otro lado
            personaje.rotateY(Geometry.DegreeToRadian(180f));
            //escalamos un poco el personaje.
            personaje.Scale = new Vector3(0.75f, 0.75f, 0.75f);
            //BoundingSphere que va a usar el personaje
            personaje.AutoUpdateBoundingBox = false;
            characterElipsoid = new TgcBoundingElipsoid(personaje.BoundingBox.calculateBoxCenter() + new Vector3(0, 0, 0),
                                                        new Vector3(12, 28, 12));
            jumping = false;

            //Almacenar volumenes de colision del escenario
            objetosColisionables.Clear();
            foreach (var mesh in escenario.Meshes)
            {
                //Los objetos del layer "TriangleCollision" son colisiones a nivel de triangulo
                if (mesh.Layer == "TriangleCollision")
                {
                    objetosColisionables.Add(TriangleMeshCollider.fromMesh(mesh));
                }
                //El resto de los objetos son colisiones de BoundingBox. Las colisiones a nivel de triangulo son muy costosas asi que deben utilizarse solo
                //donde es extremadamente necesario (por ejemplo en el piso). El resto se simplifica con un BoundingBox
                else
                {
                    objetosColisionables.Add(BoundingBoxCollider.fromBoundingBox(mesh.BoundingBox));
                }
            }

            //Crear manejador de colisiones
            collisionManager = new ElipsoidCollisionManager();
            collisionManager.GravityEnabled = true;

            //Crear linea para mostrar la direccion del movimiento del personaje
            directionArrow           = new TgcArrow();
            directionArrow.BodyColor = Color.Red;
            directionArrow.HeadColor = Color.Green;
            directionArrow.Thickness = 0.4f;
            directionArrow.HeadSize  = new Vector2(5, 10);

            //Linea para normal de colision
            collisionNormalArrow           = new TgcArrow();
            collisionNormalArrow.BodyColor = Color.Blue;
            collisionNormalArrow.HeadColor = Color.Yellow;
            collisionNormalArrow.Thickness = 0.4f;
            collisionNormalArrow.HeadSize  = new Vector2(2, 5);

            //Caja para marcar punto de colision
            collisionPoint = TgcBox.fromSize(new Vector3(4, 4, 4), Color.Red);

            //Configurar camara en Tercer Persona
            camaraInterna = new TgcThirdPersonCamera(personaje.Position, new Vector3(0, 45, 0), 20, -120);
            Camara        = camaraInterna;

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

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

            //Modifier para ver BoundingBox
            Modifiers.addBoolean("Collisions", "Collisions", true);
            Modifiers.addBoolean("showBoundingBox", "Bouding Box", true);

            //Modifiers para desplazamiento del personaje
            Modifiers.addFloat("VelocidadCaminar", 0, 20, 2);
            Modifiers.addFloat("VelocidadRotacion", 1f, 360f, 150f);
            Modifiers.addBoolean("HabilitarGravedad", "Habilitar Gravedad", true);
            Modifiers.addVertex3f("Gravedad", new Vector3(-5, -5, -5), new Vector3(5, 5, 5),
                                  new Vector3(0, -4, 0));
            Modifiers.addFloat("SlideFactor", 0f, 2f, 1f);
            Modifiers.addFloat("Pendiente", 0f, 1f, 0.72f);
            Modifiers.addFloat("VelocidadSalto", 0f, 50f, 10f);
            Modifiers.addFloat("TiempoSalto", 0f, 2f, 0.5f);

            UserVars.addVar("Movement");
        }
예제 #4
0
        public void Init(String MediaDir)
        {
            #region Configuracion Basica de World

            //Creamos el mundo fisico por defecto.
            collisionConfiguration = new DefaultCollisionConfiguration();
            dispatcher             = new CollisionDispatcher(collisionConfiguration);
            GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher);
            constraintSolver      = new SequentialImpulseConstraintSolver();
            overlappingPairCache  = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192);
            dynamicsWorld         = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration);
            dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBsVector;

            #endregion Configuracion Basica de World

            #region Capsula

            //Cuerpo rigido de una capsula basica
            capsuleRigidBody = BulletRigidBodyConstructor.CreateCapsule(10, 50, new TGCVector3(200, 500, 200), 10, false);

            //Valores que podemos modificar a partir del RigidBody base
            capsuleRigidBody.SetDamping(0.1f, 0f);
            capsuleRigidBody.Restitution = 0.1f;
            capsuleRigidBody.Friction    = 1;

            //Agregamos el RidigBody al World
            dynamicsWorld.AddRigidBody(capsuleRigidBody);

            #endregion Capsula

            #region Terreno

            //Creamos el RigidBody basico del Terreno
            var meshRigidBody = BulletRigidBodyConstructor.CreateSurfaceFromHeighMap(triangleDataVB);

            //Agregamos algo de friccion al RigidBody ya que este va a interactuar con objetos moviles
            //del World
            meshRigidBody.Friction = 0.5f;

            //Agregamos el RigidBody del terreno al World
            dynamicsWorld.AddRigidBody(meshRigidBody);

            #endregion Terreno

            #region Esfera

            //Creamos una esfera para interactuar
            pokeball = BulletRigidBodyConstructor.CreateBall(10f, 0.5f, new TGCVector3(100f, 500f, 100f));
            pokeball.SetDamping(0.1f, 0.5f);
            pokeball.Restitution = 1f;
            //Agregamos la pokebola al World
            dynamicsWorld.AddRigidBody(pokeball);

            //Textura de pokebola
            var texturePokeball = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\pokeball.jpg");

            //Se crea una esfera de tamaño 1 para escalarla luego (en render)
            sphereMesh = new TGCSphere(1, texturePokeball, TGCVector3.Empty);

            //Tgc no crea el vertex buffer hasta invocar a update values.
            sphereMesh.updateValues();

            #endregion Esfera

            #region Personaje

            //Cargamos personaje
            var skeletalLoader = new TgcSkeletalLoader();
            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml",
                MediaDir + "SkeletalAnimations\\Robot\\",
                new[]
            {
                MediaDir + "SkeletalAnimations\\Robot\\Caminando-TgcSkeletalAnim.xml",
                MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml"
            });

            //Le cambiamos la textura para diferenciarlo un poco
            personaje.changeDiffuseMaps(new[]
            {
                TgcTexture.createTexture(D3DDevice.Instance.Device,
                                         MediaDir + "SkeletalAnimations\\Robot\\Textures\\uvwGreen.jpg")
            });

            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);

            #endregion Personaje

            #region Cajas

            var sizeBox = 20f;

            //Textura de caja
            var textureBox = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"MeshCreator\Textures\Madera\cajaMadera2.jpg");

            box = BulletRigidBodyConstructor.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(0, 12, 0), 0, 0, 0, 0.5f);
            dynamicsWorld.AddRigidBody(box);
            boxMesh = TGCBox.fromSize(new TGCVector3(40f, 40f, 40f), textureBox);
            boxMesh.updateValues();

            sizeBox = 40f;
            boxB    = BulletRigidBodyConstructor.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(100, 40, 0), 0, 0, 0, 0.5f);
            dynamicsWorld.AddRigidBody(boxB);
            boxMeshB = TGCBox.fromSize(new TGCVector3(80f, 80f, 80f), textureBox);
            boxMeshB.updateValues();

            box45 = BulletRigidBodyConstructor.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(200, 40, 0), BulletSharp.MathUtil.SIMD_QUARTER_PI, 0, 0, 0.5f);
            dynamicsWorld.AddRigidBody(box45);

            boxPush = BulletRigidBodyConstructor.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0.5f, new TGCVector3(-200, 60, 0), BulletSharp.MathUtil.SIMD_QUARTER_PI, 0, 0, 0.25f);
            dynamicsWorld.AddRigidBody(boxPush);

            boxMeshPush = TGCBox.fromSize(new TGCVector3(80f, 80f, 80f), textureBox);
            boxMeshPush.updateValues();

            #endregion Cajas

            #region Escalera

            var a             = 0;
            var textureStones = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\stones.bmp");

            //la altura de cualquier cubo que quiera subir una capsula debe ser menor a la mitad del radio
            var size = new TGCVector3(50, 4, 20);
            escalon = TGCBox.fromSize(size, textureStones);

            //Se crean 10 escalonescd d
            while (a < 10)
            {
                escalonRigidBody = BulletRigidBodyConstructor.CreateBox(size, 0, new TGCVector3(200, a * 4 + 10, a * 20 + 100), 0, 0, 0, 0.1f);

                escalonesRigidBodies.Add(escalonRigidBody);

                dynamicsWorld.AddRigidBody(escalonRigidBody);

                a++;
            }

            #endregion Escalera

            #region Plataforma

            textureStones       = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\cobblestone_quad.jpg");
            rigidBodyPlataforma = BulletRigidBodyConstructor.CreateBox(new TGCVector3(50f, 15f, 50f), 0, new TGCVector3(200, 42.5f, 315), 0, 0, 0, 0.5f);
            dynamicsWorld.AddRigidBody(rigidBodyPlataforma);
            plataforma = TGCBox.fromSize(new TGCVector3(50f, 15f, 50f), textureStones);
            plataforma.updateValues();

            #endregion Plataforma

            #region Columna

            columnaRigidBody = BulletRigidBodyConstructor.CreateCylinder(new TGCVector3(10, 50, 10), new TGCVector3(100, 50, 100), 0);
            dynamicsWorld.AddRigidBody(columnaRigidBody);
            var columnaLoader = new TgcSceneLoader();
            columnaMesh          = columnaLoader.loadSceneFromFile(MediaDir + @"MeshCreator\Meshes\Cimientos\PilarEgipcio\PilarEgipcio-TgcScene.xml", MediaDir + @"MeshCreator\Meshes\Cimientos\PilarEgipcio\").Meshes[0];
            columnaMesh.Position = new TGCVector3(100, 7.5f, 100);
            columnaMesh.UpdateMeshTransform();

            #endregion Columna

            director = new TGCVector3(0, 0, 1);
        }
예제 #5
0
        public override void Init()
        {
            time = 0f;
            Device d3dDevice = D3DDevice.Instance.Device;

            MyShaderDir = ShadersDir + "WorkshopShaders\\";

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

            scene = loader.loadSceneFromFile(MediaDir + "WorkshopShaders\\comborata\\comborata-TgcScene.xml");

            g_pBaseTexture = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\rocks.jpg");
            g_pHeightmap   = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\NM_height_rocks.tga");

            g_pBaseTexture2 = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\stones.bmp");
            g_pHeightmap2   = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\NM_height_stones.tga");

            g_pBaseTexture3 = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\granito.jpg");
            g_pHeightmap3   = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\NM_height_saint.tga");

            g_pBaseTexture4 = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\granito.jpg");
            g_pHeightmap4   = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\NM_four_height.tga");

            foreach (TgcMesh mesh in scene.Meshes)
            {
                if (mesh.Name.Contains("Floor"))
                {
                    rooms.Add(mesh.BoundingBox);
                }
            }

            //Cargar Shader
            string compilationErrors;

            effect = Effect.FromFile(d3dDevice, MyShaderDir + "Parallax.fx", null, null, ShaderFlags.None, null, out compilationErrors);
            if (effect == null)
            {
                throw new Exception("Error al cargar shader. Errores: " + compilationErrors);
            }

            lightDirModifier       = AddVertex3f("LightDir", new TGCVector3(-1, -1, -1), new TGCVector3(1, 1, 1), TGCVector3.Down);
            minSampleModifier      = AddFloat("minSample", 1f, 10f, 10f);
            maxSampleModifier      = AddFloat("maxSample", 11f, 50f, 50f);
            heightMapScaleModifier = AddFloat("HeightMapScale", 0.001f, 0.5f, 0.1f);

            Camara = new TgcFpsCamera(new TGCVector3(147.2558f, 8.0f, 262.2509f), 100f, 10f, Input);
            Camara.SetCamera(new TGCVector3(147.2558f, 8.0f, 262.2509f), new TGCVector3(148.2558f, 8.0f, 263.2509f));

            //Cargar personaje con animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();
            Random            rnd            = new Random();

            // meto un enemigo por cada cuarto
            cant_enemigos = 0;
            foreach (TgcMesh mesh in scene.Meshes)
            {
                if (mesh.Name.Contains("Floor"))
                {
                    float kx    = rnd.Next(25, 75) / 100.0f;
                    float kz    = rnd.Next(25, 75) / 100.0f;
                    float pos_x = mesh.BoundingBox.PMin.X * kx + mesh.BoundingBox.PMax.X * (1 - kx);
                    float pos_z = mesh.BoundingBox.PMin.Z * kz + mesh.BoundingBox.PMax.Z * (1 - kz);

                    enemigos.Add(skeletalLoader.loadMeshAndAnimationsFromFile(MediaDir + "SkeletalAnimations\\BasicHuman\\" + "CombineSoldier-TgcSkeletalMesh.xml", MediaDir + "SkeletalAnimations\\BasicHuman\\", new string[] { MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Walk-TgcSkeletalAnim.xml", }));

                    //Configurar animacion inicial
                    enemigos[cant_enemigos].playAnimation("Walk", true);
                    enemigos[cant_enemigos].Position = new TGCVector3(pos_x, 1f, pos_z);
                    enemigos[cant_enemigos].Scale    = new TGCVector3(0.3f, 0.3f, 0.3f);
                    enemigo_an[cant_enemigos]        = 0;
                    cant_enemigos++;
                }
            }

            // levanto el GUI
            float W = D3DDevice.Instance.Width;
            float H = D3DDevice.Instance.Height;

            gui.Create(MediaDir);
            gui.InitDialog(false);
            gui.InsertFrame("Combo Rata", 10, 10, 200, 200, Color.FromArgb(32, 120, 255, 132), frameBorder.sin_borde);
            gui.InsertFrame("", 10, (int)H - 150, 200, 140, Color.FromArgb(62, 120, 132, 255), frameBorder.sin_borde);
            gui.cursor_izq = gui.cursor_der = tipoCursor.sin_cursor;

            // le cambio el font
            gui.font.Dispose();
            // Fonts
            gui.font = new Microsoft.DirectX.Direct3D.Font(d3dDevice, 12, 0, FontWeight.Bold, 0, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "Lucida Console");
            gui.font.PreloadGlyphs('0', '9');
            gui.font.PreloadGlyphs('a', 'z');
            gui.font.PreloadGlyphs('A', 'Z');

            gui.RTQ = gui.rectToQuad(0, 0, W, H, 0, 0, W - 150, 160, W - 200, H - 150, 0, H);
        }
예제 #6
0
        public override void init()
        {
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;

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

            piso = TgcBox.fromSize(new Vector3(0, -60, 0), new Vector3(1000, 5, 1000), pisoTexture);


            //Cargar obstaculos y posicionarlos. Los obstáculos se crean con TgcBox en lugar de cargar un modelo.
            obstaculos = new List <TgcBox>();
            TgcBox obstaculo;


            //Obstaculo 1
            obstaculo = TgcBox.fromSize(
                new Vector3(-100, 0, 0),
                new Vector3(80, 150, 80),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\baldosaFacultad.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 2
            obstaculo = TgcBox.fromSize(
                new Vector3(50, 0, 200),
                new Vector3(80, 300, 80),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\madera.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 3
            obstaculo = TgcBox.fromSize(
                new Vector3(300, 0, 100),
                new Vector3(80, 100, 150),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\granito.jpg"));
            obstaculos.Add(obstaculo);


            //Cargar personaje con animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();

            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Robot-TgcSkeletalMesh.xml",
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\",
                new string[] {
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Caminando-TgcSkeletalAnim.xml",
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Parado-TgcSkeletalAnim.xml",
            });

            //Le cambiamos la textura para diferenciarlo un poco
            personaje.changeDiffuseMaps(new TgcTexture[] { TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\Textures\\" + "uvwGreen.jpg") });

            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);
            //Escalarlo porque es muy grande
            personaje.Position = new Vector3(0, -45, 0);
            personaje.Scale    = new Vector3(0.75f, 0.75f, 0.75f);
            //Rotarlo 180° porque esta mirando para el otro lado
            personaje.rotateY(Geometry.DegreeToRadian(180f));



            //Configurar camara en Tercer Persona
            GuiController.Instance.ThirdPersonCamera.Enable = true;
            GuiController.Instance.ThirdPersonCamera.setCamera(personaje.Position, 200, -300);


            //Modifier para ver BoundingBox
            GuiController.Instance.Modifiers.addBoolean("showBoundingBox", "Bouding Box", false);

            //Modifiers para desplazamiento del personaje
            GuiController.Instance.Modifiers.addFloat("VelocidadCaminar", 1f, 400f, 250f);
            GuiController.Instance.Modifiers.addFloat("VelocidadRotacion", 1f, 360f, 120f);
        }
예제 #7
0
        public override void init()
        {
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;

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

            piso = TgcBox.fromSize(new Vector3(1000, 1, 1000), pisoTexture);

            //Cargar obstaculos y posicionarlos
            TgcSceneLoader loader = new TgcSceneLoader();

            obstaculos = new List <TgcMesh>();
            TgcScene scene;
            TgcMesh  obstaculo;

            //Obstaculo 1: Malla estatática de Box de formato TGC
            scene = loader.loadSceneFromFile(
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\" + "Box-TgcScene.xml",
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\");
            //Escalarlo, posicionarlo y agregar a array de obstáculos
            obstaculo       = scene.Meshes[0];
            obstaculo.Scale = new Vector3(1, 2, 1);
            obstaculo.move(-100, 20, 0);
            obstaculos.Add(obstaculo);

            //Obstaculo 2: Malla estatática de Box de formato TGC
            scene = loader.loadSceneFromFile(
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\" + "Box-TgcScene.xml",
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\");
            //Escalarlo, posicionarlo y agregar a array de obstáculos
            obstaculo       = scene.Meshes[0];
            obstaculo.Scale = new Vector3(1, 2, 1);
            obstaculo.move(0, 20, 100);
            //Le cambiamos la textura a este modelo particular
            obstaculo.changeDiffuseMaps(new TgcTexture[] { TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\madera.jpg") });
            obstaculos.Add(obstaculo);

            //Obstaculo 2: Malla estatática de Box de formato TGC
            scene = loader.loadSceneFromFile(
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\" + "Box-TgcScene.xml",
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\");
            //Escalarlo, posicionarlo y agregar a array de obstáculos
            obstaculo       = scene.Meshes[0];
            obstaculo.Scale = new Vector3(1, 2, 1);
            obstaculo.move(100, 20, 100);
            obstaculos.Add(obstaculo);


            //Cargar personaje con animaciones con herramienta TgcKeyFrameLoader
            TgcSkeletalLoader keyFrameLoader = new TgcSkeletalLoader();

            personaje = keyFrameLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Robot-TgcSkeletalMesh.xml",
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\",
                new string[] { GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Caminando-TgcSkeletalAnim.xml" });

            //Configurar animacion inicial
            personaje.playAnimation("Caminando", true);

            //Escalar y posicionar
            personaje.Scale    = new Vector3(0.5f, 0.5f, 0.5f);
            personaje.Position = new Vector3(0, 0, 0);


            //Hacer que la cámara mire hacia un determinado lugar del escenario
            GuiController.Instance.setCamera(new Vector3(-80, 165, 230), new Vector3(0, 0, 0));

            //Deshabilitar camara para que no interfiera con los controles de nuestro ejemplo
            GuiController.Instance.RotCamera.Enable = false;


            //Modifier para habilitar o no el renderizado del BoundingBox del personaje
            GuiController.Instance.Modifiers.addBoolean("showBoundingBox", "Bouding Box", false);
        }
예제 #8
0
        /////////////////////////////////////////////////////////////////////////
        ////////////////////////////////INIT/////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////


        public void init(string MediaDir, string shaderDir, TgcCamera camara)
        {
            var d3dDevice = D3DDevice.Instance.Device;

            resolucionX = d3dDevice.PresentationParameters.BackBufferWidth;
            resolucionY = d3dDevice.PresentationParameters.BackBufferHeight;

            D3DDevice.Instance.ParticlesEnabled = true;
            D3DDevice.Instance.EnableParticles();

            var loader = new TgcSceneLoader();

            scene = loader.loadSceneFromFile(MediaDir + "NivelFisica1\\EscenaSceneEditorFisica1-TgcScene.xml");

            SetearAguas();

            pathDeLaCancion = MediaDir + "Musica\\FeverTime.mp3";


            meshesDeLaEscena = new List <TgcMesh>();

            HUD       = new Sprite(D3DDevice.Instance.Device);
            vida      = TgcTexture.createTexture(MediaDir + "Textures\\vida.png");
            fisicaLib = TgcTexture.createTexture(MediaDir + "NivelFisica1\\Textures\\TexturaTapaLibro.jpg");

            var skeletalLoader = new TgcSkeletalLoader();

            personajePrincipal =
                skeletalLoader.loadMeshAndAnimationsFromFile(
                    MediaDir + "Robot\\Robot-TgcSkeletalMesh.xml",
                    MediaDir + "Robot\\",
                    new[]
            {
                MediaDir + "Robot\\Caminando-TgcSkeletalAnim.xml",
                MediaDir + "Robot\\Parado-TgcSkeletalAnim.xml",
                MediaDir + "Robot\\Empujar-TgcSkeletalAnim.xml",
            });
            //Configurar animacion inicial
            personajePrincipal.playAnimation("Parado", true);

            personajePrincipal.Position = puntoCheckpointActual;
            personajePrincipal.RotateY(Geometry.DegreeToRadian(180));


            camaraInterna = new TgcThirdPersonCamera(personajePrincipal.Position, 250, 500);
            // camara = camaraInterna;
            camaraInterna.rotateY(Geometry.DegreeToRadian(180));

            librosAdquiridos = new Boton(cantidadLibrosAdquiridos.ToString(), resolucionX - (resolucionX / 9), resolucionY - (resolucionY / 7), null);

            plataforma1 = scene.Meshes[164];
            plataforma2 = scene.Meshes[165];

            plataformasMovibles.Add(plataforma1);
            plataformasMovibles.Add(plataforma2);

            bolaDeCanion1 = scene.Meshes[172];
            bolaDeCanion2 = scene.Meshes[173];
            bolaDeCanion3 = scene.Meshes[174];

            posicionInicialBolaDeCanion1 = scene.Meshes[172].Position;
            posicionInicialBolaDeCanion2 = scene.Meshes[173].Position;
            posicionInicialBolaDeCanion3 = scene.Meshes[174].Position;

            bolasDeCanion.Add(bolaDeCanion1);
            bolasDeCanion.Add(bolaDeCanion2);
            bolasDeCanion.Add(bolaDeCanion3);

            pathTexturaEmisorDeParticulas = MediaDir + "Textures\\fuego.png";
            cantidadDeParticulas          = 10;

            emisorDeParticulas1 = new ParticleEmitter(pathTexturaEmisorDeParticulas, cantidadDeParticulas);
            emisorDeParticulas1.MinSizeParticle    = 30f;
            emisorDeParticulas1.MaxSizeParticle    = 30f;
            emisorDeParticulas1.ParticleTimeToLive = 1f;
            emisorDeParticulas1.CreationFrecuency  = 1f; //0.25
            emisorDeParticulas1.Dispersion         = 500;
            emisorDeParticulas1.Speed          = new TGCVector3(-25, 40, 50);
            posicionInicialEmisorDeParticulas1 = new TGCVector3(1935, 200, 4345);
            emisorDeParticulas1.Position       = posicionInicialEmisorDeParticulas1;

            emisorDeParticulas2 = new ParticleEmitter(pathTexturaEmisorDeParticulas, cantidadDeParticulas);
            emisorDeParticulas2 = new ParticleEmitter(pathTexturaEmisorDeParticulas, cantidadDeParticulas);
            emisorDeParticulas2.MinSizeParticle    = 30f;
            emisorDeParticulas2.MaxSizeParticle    = 30f;
            emisorDeParticulas2.ParticleTimeToLive = 1f;
            emisorDeParticulas2.CreationFrecuency  = 1f;
            emisorDeParticulas2.Dispersion         = 500;
            emisorDeParticulas2.Speed          = new TGCVector3(-25, 40, 50);
            posicionInicialEmisorDeParticulas2 = new TGCVector3(2205, 200, 4345);
            emisorDeParticulas2.Position       = posicionInicialEmisorDeParticulas2;

            emisorDeParticulas3 = new ParticleEmitter(pathTexturaEmisorDeParticulas, cantidadDeParticulas);
            emisorDeParticulas3 = new ParticleEmitter(pathTexturaEmisorDeParticulas, cantidadDeParticulas);
            emisorDeParticulas3.MinSizeParticle    = 30f;
            emisorDeParticulas3.MaxSizeParticle    = 30f;
            emisorDeParticulas3.ParticleTimeToLive = 1f;
            emisorDeParticulas3.CreationFrecuency  = 1f;
            emisorDeParticulas3.Dispersion         = 500;
            emisorDeParticulas3.Speed          = new TGCVector3(-25, 40, 50);
            posicionInicialEmisorDeParticulas3 = new TGCVector3(2495, 200, 4345);
            emisorDeParticulas3.Position       = posicionInicialEmisorDeParticulas3;

            reproductorMp3.FileName = pathDeLaCancion;
            reproductorMp3.play(true);

            AdministradorDeEscenarios.getSingleton().SetCamara(camaraInterna);

            cantVidas = 3;
            effect    = TgcShaders.loadEffect(shaderDir + "MultiDiffuseLights.fx");
            for (var i = 224; i < 250; ++i)
            {
                lights.Add(scene.Meshes[i]);
            }

            scene.Meshes[4].D3dMesh.ComputeNormals();
            scene.Meshes[48].D3dMesh.ComputeNormals();
            var lightColors           = new ColorValue[lights.Count];
            var pointLightPositions   = new Vector4[lights.Count];
            var pointLightIntensity   = new float[lights.Count];
            var pointLightAttenuation = new float[lights.Count];

            for (var i = 0; i < lights.Count; i++)
            {
                var lightMesh = lights[i];

                lightColors[i]           = ColorValue.FromColor(Color.White);
                pointLightPositions[i]   = TGCVector3.Vector3ToVector4(lightMesh.BoundingBox.Position);
                pointLightIntensity[i]   = 20;
                pointLightAttenuation[i] = 0.07f;
            }
            tecnicaNormal = scene.Meshes[0].Technique;
            sinEfectos    = scene.Meshes[0].Effect;
            foreach (var mesh in scene.Meshes)
            {
                //if (mesh.Name.Contains("Box") || mesh.Name.Contains("Madera") || mesh.Name.Contains("East") || mesh.Name.Contains("South") || mesh.Name.Contains("North") || mesh.Name.Contains("West"))
                if (!mesh.Name.Contains("Floor"))
                {
                    continue;
                }
                mesh.Effect = effect;

                mesh.Effect.SetValue("lightColor", lightColors);
                mesh.Effect.SetValue("lightPosition", pointLightPositions);
                mesh.Effect.SetValue("lightIntensity", pointLightIntensity);
                mesh.Effect.SetValue("lightAttenuation", pointLightAttenuation);
                mesh.Effect.SetValue("materialEmissiveColor", ColorValue.FromColor(Color.Black));
                mesh.Effect.SetValue("materialDiffuseColor", ColorValue.FromColor(Color.White));
                mesh.Technique = "MultiDiffuseLightsTechnique";
                if (mesh.Name.Contains("Box") || mesh.Name.Contains("Madera"))
                {
                    mesh.Effect.SetValue("lightAttenuation", pointLightAttenuation);
                    mesh.D3dMesh.ComputeNormals();
                }
            }

            AplicarShaders(shaderDir);
        }
예제 #9
0
        public override void Init()
        {
            var d3dDevice = D3DDevice.Instance.Device;

            MyShaderDir = ShadersDir + "WorkshopShaders\\";

            //Cargamos un escenario
            var loader = new TgcSceneLoader();

            //TgcScene scene = loader.loadSceneFromFile(this.MediaDir + "MeshCreator\\Scenes\\Deposito\\Deposito-TgcScene.xml");
            var scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Scenes\\Selva\\Selva-TgcScene.xml");

            meshes = scene.Meshes;
            var scene2 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Pasto\\Pasto-TgcScene.xml");

            pasto = scene2.Meshes[0];
            var scene3 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\ArbolSelvatico\\ArbolSelvatico-TgcScene.xml");

            arbol = scene3.Meshes[0];
            var scene4 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Arbusto2\\Arbusto2-TgcScene.xml");

            arbusto = scene4.Meshes[0];

            //Cargar personaje con animaciones
            var skeletalLoader = new TgcSkeletalLoader();
            var rnd            = new Random();

            for (var t = 0; t < 25; ++t)
            {
                enemigos.Add(skeletalLoader.loadMeshAndAnimationsFromFile(
                                 MediaDir + "SkeletalAnimations\\BasicHuman\\" + "CombineSoldier-TgcSkeletalMesh.xml",
                                 MediaDir + "SkeletalAnimations\\BasicHuman\\",
                                 new[]
                {
                    MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "StandBy-TgcSkeletalAnim.xml",
                    MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Run-TgcSkeletalAnim.xml"
                }));

                //Configurar animacion inicial
                enemigos[t].playAnimation("StandBy", true);
                enemigos[t].Position  = new TGCVector3(-rnd.Next(0, 1500) - 250, 0, -rnd.Next(0, 1500) - 250);
                enemigos[t].Scale     = new TGCVector3(2f, 2f, 2f);
                enemigos[t].Transform = TGCMatrix.Scaling(enemigos[t].Scale) * TGCMatrix.Translation(enemigos[t].Position);
                //enemigos[t].UpdateMeshTransform();
                bot_status[t] = 0;
            }

            //Cargar Shader personalizado
            string compilationErrors;

            effect = Effect.FromFile(D3DDevice.Instance.Device, MyShaderDir + "GaussianBlur.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors);
            if (effect == null)
            {
                throw new Exception("Error al cargar shader. Errores: " + compilationErrors);
            }
            //Configurar Technique dentro del shader
            effect.Technique = "DefaultTechnique";

            //Camara en primera personas
            Camara = new TgcFpsCamera(new TGCVector3(-1000, 250, -1000), 1000f, 600f, Input);

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

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

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

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

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

            effect.SetValue("g_RenderTarget", g_pRenderTarget);

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

            CustomVertex.PositionTextured[] vertices =
            {
                new CustomVertex.PositionTextured(-1,  1, 1, 0, 0),
                new CustomVertex.PositionTextured(1,   1, 1, 1, 0),
                new CustomVertex.PositionTextured(-1, -1, 1, 0, 1),
                new CustomVertex.PositionTextured(1,  -1, 1, 1, 1)
            };
            //vertex buffer de los triangulos
            g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default);
            g_pVBV3D.SetData(vertices, 0, LockFlags.None);

            activarEfectoModifier = AddBoolean("activar_efecto", "Activar efecto", true);

            timer_firing = new float[100];
            pos_bala     = new TGCVector3[100];
            dir_bala     = new TGCVector3[100];

            for (var i = 0; i < cant_balas; ++i)
            {
                timer_firing[i] = i / (float)cant_balas * total_timer_firing;
            }
        }
예제 #10
0
        public override void Init()
        {
            //Crear piso
            var pisoTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\tierra.jpg");

            piso = TgcBox.fromExtremes(new Vector3(-1000, -2, -1000), new Vector3(1000, 0, 1000), pisoTexture);

            //Cargar obstaculos y posicionarlos. Los obstáculos se crean con TgcBox en lugar de cargar un modelo.
            obstaculos = new List <TgcBox>();
            TgcBox obstaculo;

            float wallSize   = 1000;
            float wallHeight = 500;

            //Obstaculo 1
            obstaculo = TgcBox.fromExtremes(new Vector3(0, 0, 0), new Vector3(wallSize, wallHeight, 10),
                                            TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\baldosaFacultad.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 2
            obstaculo = TgcBox.fromExtremes(new Vector3(0, 0, 0), new Vector3(10, wallHeight, wallSize),
                                            TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\madera.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 3
            obstaculo = TgcBox.fromExtremes(new Vector3(0, 0, wallSize),
                                            new Vector3(wallSize, wallHeight, wallSize + 10),
                                            TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\granito.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 4
            obstaculo = TgcBox.fromExtremes(new Vector3(wallSize, 0, 0),
                                            new Vector3(wallSize + 10, wallHeight, wallSize),
                                            TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\granito.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 5
            obstaculo = TgcBox.fromExtremes(new Vector3(wallSize / 2, 0, wallSize - 400),
                                            new Vector3(wallSize + 10, wallHeight, wallSize - 400 + 10),
                                            TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\granito.jpg"));
            obstaculos.Add(obstaculo);

            //Cargar personaje con animaciones
            var skeletalLoader = new TgcSkeletalLoader();

            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml",
                MediaDir + "SkeletalAnimations\\Robot\\",
                new[]
            {
                MediaDir + "SkeletalAnimations\\Robot\\Caminando-TgcSkeletalAnim.xml",
                MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml"
            });

            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);
            //Escalarlo porque es muy grande
            personaje.Position = new Vector3(100, 0, 100);
            personaje.Scale    = new Vector3(0.75f, 0.75f, 0.75f);
            //Rotarlo 180° porque esta mirando para el otro lado
            personaje.rotateY(Geometry.DegreeToRadian(180f));

            //Configurar camara en Tercera Persona y la asigno al TGC.
            camaraInterna = new TgcThirdPersonCamera(personaje.Position, 200, -300);
            Camara        = camaraInterna;

            //Modifiers para modificar propiedades de la camara
            Modifiers.addFloat("offsetHeight", 0, 300, 100);
            Modifiers.addFloat("offsetForward", -400, 0, -220);
            Modifiers.addVertex2f("displacement", new Vector2(0, 0), new Vector2(100, 200), new Vector2(0, 100));
        }
예제 #11
0
        public void Init()
        {
            //seteamos atributos particulares del robot
            health = 100;
            score  = 1;
            Device d3dDevice = GuiController.Instance.D3dDevice;

            MESH_SCALE   = 0.5f;
            tiempoMuerte = 5f;
            attackDamage = 25;
            //cargamos el mesh
            //Despues de agregar el skeletalMesh dejamos de renderizar este mesh, pero igual lo utilizamos para calcular muchas cosas
            this.mesh = GameManager.Instance.ModeloRobot.clone("robot");

            giroInicial = Matrix.RotationY(-(float)Math.PI / 2);


            //carga de animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();

            skeletalMesh = skeletalLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Robot-TgcSkeletalMesh.xml",
                new string[] {
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Caminando-TgcSkeletalAnim.xml",
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Patear-TgcSkeletalAnim.xml",
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Arrojar-TgcSkeletalAnim.xml",
            });

            skeletalMesh.playAnimation("Caminando", true);
            skeletalMesh.AnimationEnds += this.onAnimationEnds;

            skeletalMesh.Effect = GameManager.Instance.skeletalEnvMap;
            //skeletalMesh.Technique = "SkeletalEnvMap";

            skeletalMesh.Effect.SetValue("lightColor", ColorValue.FromColor(Color.White));
            skeletalMesh.Effect.SetValue("lightPosition", TgcParserUtils.vector3ToFloat4Array(new Vector3(0, 1400, 0)));
            skeletalMesh.Effect.SetValue("eyePosition", TgcParserUtils.vector3ToFloat4Array(CustomFpsCamera.Instance.getPosition()));
            skeletalMesh.Effect.SetValue("lightIntensity", 0.3f);
            skeletalMesh.Effect.SetValue("lightAttenuation", 0.3f);
            skeletalMesh.Effect.SetValue("reflection", 0.65f);

            //Cargar variables de shader de Material. El Material en realidad deberia ser propio de cada mesh. Pero en este ejemplo se simplifica con uno comun para todos
            skeletalMesh.Effect.SetValue("materialEmissiveColor", ColorValue.FromColor(Color.Black));
            skeletalMesh.Effect.SetValue("materialAmbientColor", ColorValue.FromColor(Color.White));
            skeletalMesh.Effect.SetValue("materialDiffuseColor", ColorValue.FromColor(Color.White));
            skeletalMesh.Effect.SetValue("materialSpecularColor", ColorValue.FromColor(Color.White));
            skeletalMesh.Effect.SetValue("materialSpecularExp", 7);

            skeletalMesh.Effect.SetValue("texCubeMap", GameManager.Instance.cubeMap);

            skeletalMesh.setColor(Color.Peru);

            //realizamos el init() comun a todos los enemigos
            base.Init();
            //Creamos boundingBox nuevas para la cabeza, pecho y piernas del robot
            HEADSHOT_BOUNDINGBOX = this.mesh.BoundingBox.clone();
            CHEST_BOUNDINGBOX    = this.mesh.BoundingBox.clone();
            LEGS_BOUNDINGBOX     = this.mesh.BoundingBox.clone();
            Matrix escalabox     = Matrix.Scaling(new Vector3(0.43f, 0.3f, 0.43f));
            Matrix traslationbox = Matrix.Translation(new Vector3(0, 90f, 0));

            HEADSHOT_BOUNDINGBOX.transform(escalabox * traslationbox);
            posicionActualHeadshot = escalabox * traslationbox * posicionActual;
            Matrix escalabox2     = Matrix.Scaling(new Vector3(0.6f, 0.3f, 0.6f));
            Matrix traslationbox2 = Matrix.Translation(new Vector3(0, 50f, 0));

            CHEST_BOUNDINGBOX.transform(escalabox2 * traslationbox2);
            posicionActualChest = escalabox2 * traslationbox2 * posicionActual;
            Matrix escalabox3     = Matrix.Scaling(new Vector3(0.4f, 0.38f, 0.4f));
            Matrix traslationbox3 = Matrix.Translation(new Vector3(0, 0f, 0));

            LEGS_BOUNDINGBOX.transform(escalabox3 * traslationbox3);
            posicionActualLegs = escalabox3 * traslationbox3 * posicionActual;


            skeletalMesh.AutoTransformEnable = false;

            //carga de sonido
            SonidoMovimiento             = new Tgc3dSound(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Audio\\Robot\\servomotor.wav", getPosicionActual());
            SonidoMovimiento.MinDistance = 70f;
            SonidoMovimiento.play(true);

            //setBaseEffect();
            skeletalMesh.computeNormals();
        }
예제 #12
0
        public override void Init()
        {
            //Cargar escenario específico para este ejemplo
            var loader = new TgcSceneLoader();

            escenario = loader.loadSceneFromFile(MediaDir + "\\MeshCreator\\Scenes\\Mountains\\Mountains-TgcScene.xml");

            //Cargar personaje con animaciones
            var skeletalLoader = new TgcSkeletalLoader();

            personaje =
                skeletalLoader.loadMeshAndAnimationsFromFile(
                    MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml",
                    MediaDir + "SkeletalAnimations\\Robot\\",
                    new[]
            {
                MediaDir + "SkeletalAnimations\\Robot\\Caminando-TgcSkeletalAnim.xml",
                MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml"
            });

            //Le cambiamos la textura para diferenciarlo un poco
            personaje.changeDiffuseMaps(new[]
            {
                TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "SkeletalAnimations\\Robot\\Textures\\uvwGreen.jpg")
            });

            //Se utiliza autotransform, aunque este es un claro ejemplo de que no se debe usar autotransform,
            //hay muchas operaciones y la mayoria las maneja el manager de colisiones, con lo cual se esta
            //perdiendo el control de las transformaciones del personaje.
            personaje.AutoTransform = true;
            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);
            //Escalarlo porque es muy grande
            personaje.Position = new TGCVector3(0, 2500, -150);
            //Rotarlo 180° porque esta mirando para el otro lado
            personaje.RotateY(Geometry.DegreeToRadian(180f));
            //escalamos el personaje porque es muy grande.
            personaje.Scale = new TGCVector3(0.5f, 0.5f, 0.5f);

            //BoundingSphere que va a usar el personaje
            personaje.AutoUpdateBoundingBox = false;
            characterSphere = new TgcBoundingSphere(personaje.BoundingBox.calculateBoxCenter(), personaje.BoundingBox.calculateBoxRadius());
            jumping         = false;

            //Almacenar volumenes de colision del escenario
            objetosColisionables.Clear();
            foreach (var mesh in escenario.Meshes)
            {
                //Los objetos del layer "TriangleCollision" son colisiones a nivel de triangulo
                if (mesh.Layer == "TriangleCollision")
                {
                    objetosColisionables.Add(TriangleMeshCollider.fromMesh(mesh));
                }
                //El resto de los objetos son colisiones de BoundingBox
                else
                {
                    objetosColisionables.Add(BoundingBoxCollider.fromBoundingBox(mesh.BoundingBox));
                }
            }

            //Crear linea para mostrar la direccion del movimiento del personaje
            directionArrow           = new TgcArrow();
            directionArrow.BodyColor = Color.Red;
            directionArrow.HeadColor = Color.Green;
            directionArrow.Thickness = 0.4f;
            directionArrow.HeadSize  = new TGCVector2(5, 10);

            //Linea para normal de colision
            collisionNormalArrow           = new TgcArrow();
            collisionNormalArrow.BodyColor = Color.Blue;
            collisionNormalArrow.HeadColor = Color.Yellow;
            collisionNormalArrow.Thickness = 0.4f;
            collisionNormalArrow.HeadSize  = new TGCVector2(2, 5);

            //Caja para marcar punto de colision
            collisionPoint = TGCBox.fromSize(new TGCVector3(4, 4, 4), Color.Red);
            collisionPoint.AutoTransform = true;

            //Crear manejador de colisiones
            collisionManager = new SphereTriangleCollisionManager();
            collisionManager.GravityEnabled = true;

            //Configurar camara en Tercer Persona
            camaraInterna = new TgcThirdPersonCamera(personaje.Position, new TGCVector3(0, 45, 0), 35, -150);
            Camara        = camaraInterna;

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

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

            //Modifier para ver BoundingBox
            collisionsModifier      = AddBoolean("Collisions", "Collisions", true);
            showBoundingBoxModifier = AddBoolean("showBoundingBox", "Bouding Box", true);

            //Modifiers para desplazamiento del personaje
            velocidadCaminarModifier  = AddFloat("VelocidadCaminar", 0, 10, 2);
            velocidadRotacionModifier = AddFloat("VelocidadRotacion", 1f, 360f, 150f);
            habilitarGravedadModifier = AddBoolean("HabilitarGravedad", "Habilitar Gravedad", true);
            gravedadModifier          = AddVertex3f("Gravedad", new TGCVector3(-5, -10, -5), new TGCVector3(5, 5, 5), new TGCVector3(0, -6, 0));
            slideFactorModifier       = AddFloat("SlideFactor", 0f, 2f, 1f);
            pendienteModifier         = AddFloat("Pendiente", 0f, 1f, 0.7f);
            velocidadSaltoModifier    = AddFloat("VelocidadSalto", 0f, 10f, 2f);
            tiempoSaltoModifier       = AddFloat("TiempoSalto", 0f, 2f, 0.5f);

            UserVars.addVar("Movement");
            UserVars.addVar("ySign");
        }
예제 #13
0
        public override void Init()
        {
            Cursor.Hide();

            Device d3dDevice = D3DDevice.Instance.Device;

            //Cargar Shader personalizado
            string compilationErrors;

            effect = Effect.FromFile(d3dDevice, TGCShaders.Instance.CommonShadersPath + "TgcSkeletalMeshShader.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors);
            if (effect == null)
            {
                throw new Exception("Error al cargar shader. Errores: " + compilationErrors);
            }
            //Configurar Technique dentro del shader
            effect.Technique = "DIFFUSE_MAP";

            //Camara en primera persona
            Camara.SetCamera(new TGCVector3(0, 60, 200), new TGCVector3(0, 0, 0));

            //Cargar personaje con animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();

            mesh = skeletalLoader.loadMeshAndAnimationsFromFile(MediaDir + "SkeletalAnimations\\BasicHuman\\" + "CombineSoldier-TgcSkeletalMesh.xml", MediaDir + "SkeletalAnimations\\BasicHuman\\", new string[] { MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "StandBy-TgcSkeletalAnim.xml", MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Run-TgcSkeletalAnim.xml", });

            //Configurar animacion inicial
            mesh.playAnimation("StandBy", true);
            mesh.Position  = new TGCVector3(0, -50, 0);
            mesh.Scale     = new TGCVector3(2f, 2f, 2f);
            mesh.Effect    = effect;
            mesh.Technique = "DIFFUSE_MAP";
            mesh.Transform = TGCMatrix.Scaling(mesh.Scale)
                             * TGCMatrix.RotationYawPitchRoll(mesh.Rotation.Y, mesh.Rotation.X, mesh.Rotation.Z)
                             * TGCMatrix.Translation(mesh.Position);

            // levanto el GUI
            gui.Create(MediaDir);

            // menu principal
            gui.InitDialog(true);
            int W   = D3DDevice.Instance.Width;
            int H   = D3DDevice.Instance.Height;
            int x0  = 70;
            int y0  = 10;
            int dy  = 120;
            int dy2 = dy;
            int dx  = 400;

            gui.InsertMenuItem(ID_ABRIR_MISION, "Abrir Mision", "open.png", x0, y0, MediaDir, dx, dy);
            gui.InsertMenuItem(ID_NUEVA_MISION, "Play", "Play.png", x0, y0        += dy2, MediaDir, dx, dy);
            gui.InsertMenuItem(ID_CONFIGURAR, "Configurar", "navegar.png", x0, y0 += dy2, MediaDir, dx, dy);
            gui.InsertMenuItem(ID_APP_EXIT, "Salir", "salir.png", x0, y0          += dy2, MediaDir, dx, dy);

            // lista de colores
            lst_colores[0]  = Color.FromArgb(100, 220, 255);
            lst_colores[1]  = Color.FromArgb(100, 255, 220);
            lst_colores[2]  = Color.FromArgb(220, 100, 255);
            lst_colores[3]  = Color.FromArgb(220, 255, 100);
            lst_colores[4]  = Color.FromArgb(255, 100, 220);
            lst_colores[5]  = Color.FromArgb(255, 220, 100);
            lst_colores[6]  = Color.FromArgb(128, 128, 128);
            lst_colores[7]  = Color.FromArgb(64, 255, 64);
            lst_colores[8]  = Color.FromArgb(64, 64, 255);
            lst_colores[9]  = Color.FromArgb(255, 0, 255);
            lst_colores[10] = Color.FromArgb(255, 255, 0);
            lst_colores[11] = Color.FromArgb(0, 255, 255);
        }
예제 #14
0
        public override void Init()
        {
            //Cargar escenario específico para este ejemplo
            var loader = new TgcSceneLoader();

            escenario = loader.loadSceneFromFile(MediaDir + "PatioDeJuegos\\PatioDeJuegos-TgcScene.xml");

            //Cargar personaje con animaciones
            var skeletalLoader = new TgcSkeletalLoader();

            personaje =
                skeletalLoader.loadMeshAndAnimationsFromFile(
                    MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml",
                    MediaDir + "SkeletalAnimations\\Robot\\",
                    new[]
            {
                MediaDir + "SkeletalAnimations\\Robot\\Caminando-TgcSkeletalAnim.xml",
                MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml"
            });

            //Le cambiamos la textura para diferenciarlo un poco
            personaje.changeDiffuseMaps(new[]
            {
                TgcTexture.createTexture(D3DDevice.Instance.Device,
                                         MediaDir + "SkeletalAnimations\\Robot\\Textures\\uvwGreen.jpg")
            });

            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);
            //Escalarlo porque es muy grande
            personaje.Position = new Vector3(0, 500, -100);
            //Rotarlo 180° porque esta mirando para el otro lado
            personaje.rotateY(Geometry.DegreeToRadian(180f));

            //BoundingSphere que va a usar el personaje
            personaje.AutoUpdateBoundingBox = false;
            characterSphere = new TgcBoundingSphere(personaje.BoundingBox.calculateBoxCenter(),
                                                    personaje.BoundingBox.calculateBoxRadius());

            //Almacenar volumenes de colision del escenario
            objetosColisionables.Clear();
            foreach (var mesh in escenario.Meshes)
            {
                objetosColisionables.Add(mesh.BoundingBox);
            }

            //Crear linea para mostrar la direccion del movimiento del personaje
            directionArrow           = new TgcArrow();
            directionArrow.BodyColor = Color.Red;
            directionArrow.HeadColor = Color.Green;
            directionArrow.Thickness = 1;
            directionArrow.HeadSize  = new Vector2(10, 20);

            //Crear manejador de colisiones
            collisionManager = new SphereCollisionManager();
            collisionManager.GravityEnabled = true;

            //Configurar camara en Tercer Persona
            camaraInterna = new TgcThirdPersonCamera(personaje.Position, new Vector3(0, 100, 0), 100, -400);
            Camara        = camaraInterna;

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

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

            //Modifier para ver BoundingBox
            Modifiers.addBoolean("showBoundingBox", "Bouding Box", true);

            //Modifiers para desplazamiento del personaje
            Modifiers.addFloat("VelocidadCaminar", 0, 100, 16);
            Modifiers.addFloat("VelocidadRotacion", 1f, 360f, 150f);
            Modifiers.addBoolean("HabilitarGravedad", "Habilitar Gravedad", true);
            Modifiers.addVertex3f("Gravedad", new Vector3(-50, -50, -50), new Vector3(50, 50, 50),
                                  new Vector3(0, -10, 0));
            Modifiers.addFloat("SlideFactor", 1f, 2f, 1.3f);

            UserVars.addVar("Movement");
        }