Esempio n. 1
0
        public void RenderShadowMap()
        {
            // Calculo la matriz de view de la luz
            shadowEffect.SetValue("g_vLightPos", new Vector4(g_LightPos.X, g_LightPos.Y, g_LightPos.Z, 1));
            shadowEffect.SetValue("g_vLightDir", new Vector4(g_LightDir.X, g_LightDir.Y, g_LightDir.Z, 1));
            skeletalShadowEffect.SetValue("g_vLightPos", new Vector4(g_LightPos.X, g_LightPos.Y, g_LightPos.Z, 1));
            skeletalShadowEffect.SetValue("g_vLightDir", new Vector4(g_LightDir.X, g_LightDir.Y, g_LightDir.Z, 1));
            g_LightView = TGCMatrix.LookAtLH(g_LightPos, g_LightPos + g_LightDir, new TGCVector3(0, 0, 1));

            // inicializacion standard:
            shadowEffect.SetValue("g_mProjLight", g_mShadowProj.ToMatrix());
            shadowEffect.SetValue("g_mViewLightProj", (g_LightView * g_mShadowProj).ToMatrix());
            skeletalShadowEffect.SetValue("g_mProjLight", g_mShadowProj.ToMatrix());
            skeletalShadowEffect.SetValue("g_mViewLightProj", (g_LightView * g_mShadowProj).ToMatrix());


            // Primero genero el shadow map, para ello dibujo desde el pto de vista de luz
            // a una textura, con el VS y PS que generan un mapa de profundidades.
            var pOldRT      = D3DDevice.Instance.Device.GetRenderTarget(0);
            var pShadowSurf = g_pShadowMap.GetSurfaceLevel(0);

            D3DDevice.Instance.Device.SetRenderTarget(0, pShadowSurf);
            var pOldDS = D3DDevice.Instance.Device.DepthStencilSurface;

            D3DDevice.Instance.Device.DepthStencilSurface = shadowDepthStencil;
            D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            D3DDevice.Instance.Device.BeginScene();

            // Hago el render de la escena pp dicha
            shadowEffect.SetValue("g_txShadow", g_pShadowMap);
            skeletalShadowEffect.SetValue("g_txShadow", g_pShadowMap);
            // RENDER
            doingShadowRender = true;
            RenderScene();


            // Termino
            D3DDevice.Instance.Device.EndScene();
            //TextureLoader.Save("shadowmap.bmp", ImageFileFormat.Bmp, g_pShadowMap);
            // restuaro el render target y el stencil
            D3DDevice.Instance.Device.DepthStencilSurface = pOldDS;
            D3DDevice.Instance.Device.SetRenderTarget(0, pOldRT);
        }
Esempio n. 2
0
        /// <summary>
        ///     Renderizar la caja
        /// </summary>
        public void Render()
        {
            if (!Enabled)
            {
                return;
            }

            //transformacion
            if (AutoTransformEnable)
            {
                Transform = TGCMatrix.RotationYawPitchRoll(rotation.Y, rotation.X, rotation.Z) *
                            TGCMatrix.Translation(translation);
            }

            //Activar AlphaBlending
            activateAlphaBlend();

            //renderizar
            if (Texture != null)
            {
                TexturesManager.Instance.shaderSet(Effect, "texDiffuseMap", Texture);
            }
            else
            {
                TexturesManager.Instance.clear(0);
            }
            TexturesManager.Instance.clear(1);

            TGCShaders.Instance.SetShaderMatrix(Effect, Transform);
            D3DDevice.Instance.Device.VertexDeclaration = TGCShaders.Instance.VdecPositionColoredTextured;
            Effect.Technique = Technique;
            D3DDevice.Instance.Device.SetStreamSource(0, vertexBuffer, 0);

            //Render con shader
            Effect.Begin(0);
            Effect.BeginPass(0);
            D3DDevice.Instance.Device.DrawPrimitives(PrimitiveType.TriangleList, 0, 12);
            Effect.EndPass();
            Effect.End();

            //Desactivar AlphaBlendEnable
            resetAlphaBlend();
        }
        public override void Update()
        {
            this.PreUpdate();

            // Manejamos la entrada
            this.HandleInput();

            // Actualizamos nuestro tiempo y se lo enviamos al shader
            this.time += ElapsedTime;
            this.effect.SetValue("time", time);

            // Le enviamos al shader la matriz ViewProj
            this.effect.SetValue("matViewProj", D3DDevice.Instance.Device.Transform.View * D3DDevice.Instance.Device.Transform.Projection);

            // Le enviamos al shader la posicion de la camara
            this.effect.SetValue("eyePosition", new[] { this.Camara.Position.X, this.Camara.Position.Y, this.Camara.Position.Z });

            // Actualizamos los modificadores
            this.rotation.Update();
            this.factor.Update();
            this.effectVector.Update();
            this.center.Update();
            this.techniques.Update();
            this.wireframe.Update();
            this.showArrow.Update();

            // Hacemos uso de los valores de los modificadores actualizados
            // (Excepto el Wireframe, eso se usa en el Render)
            this.mesh.Transform = this.scale * TGCMatrix.RotationYawPitchRoll(this.rotation.Value, 0, 0) * TGCMatrix.Translation(this.center.Value);
            this.effect.SetValue("factor", this.factor.Value);
            TGCVector3 realVector = this.center.Value + this.effectVector.Value;

            this.effect.SetValue("effectVector", TGCVector3.Vector3ToFloat4Array(this.effectVector.Value));
            this.effect.SetValue("center", TGCVector3.Vector3ToFloat4Array(this.center.Value));

            this.mesh.Technique            = ((Techniques)this.techniques.Value).ToString();
            this.effectVectorArrow.Enabled = this.showArrow.Value;
            this.effectVectorArrow.PStart  = this.center.Value;
            this.effectVectorArrow.PEnd    = realVector;
            this.effectVectorArrow.updateValues();

            this.PostUpdate();
        }
Esempio n. 4
0
        // helper
        public TGCMatrix CalcularMatriz(TGCVector3 Pos, TGCVector3 Scale, TGCVector3 Dir, TGCVector3 VUP)
        {
            var matWorld = TGCMatrix.Scaling(Scale);

            // xxx
            matWorld = matWorld * TGCMatrix.RotationY(-(float)Math.PI / 2.0f)
                       * TGCMatrix.RotationYawPitchRoll(yaw, pitch, roll);


            // determino la orientacion
            var U = TGCVector3.Cross(VUP, Dir);

            U.Normalize();
            var V = TGCVector3.Cross(Dir, U);

            V.Normalize();
            TGCMatrix Orientacion = new TGCMatrix();

            Orientacion.M11 = U.X;
            Orientacion.M12 = U.Y;
            Orientacion.M13 = U.Z;
            Orientacion.M14 = 0;

            Orientacion.M21 = V.X;
            Orientacion.M22 = V.Y;
            Orientacion.M23 = V.Z;
            Orientacion.M24 = 0;

            Orientacion.M31 = Dir.X;
            Orientacion.M32 = Dir.Y;
            Orientacion.M33 = Dir.Z;
            Orientacion.M34 = 0;

            Orientacion.M41 = 0;
            Orientacion.M42 = 0;
            Orientacion.M43 = 0;
            Orientacion.M44 = 1;
            matWorld        = matWorld * Orientacion;

            // traslado
            matWorld = matWorld * TGCMatrix.Translation(Pos);
            return(matWorld);
        }
Esempio n. 5
0
        private RigidBody BuildRigidBodyFromTriangleMeshShape(BvhTriangleMeshShape triangleMeshShape, int mass, TGCVector3 position, TGCVector3 scale)
        {
            var transformationMatrix = TGCMatrix.RotationYawPitchRoll(0, 0, 0);

            transformationMatrix.Origin = position;
            DefaultMotionState motionState = new DefaultMotionState(transformationMatrix.ToBsMatrix);

            var bulletShape     = new ScaledBvhTriangleMeshShape(triangleMeshShape, scale.ToBulletVector3());
            var boxLocalInertia = bulletShape.CalculateLocalInertia(0);

            var bodyInfo  = new RigidBodyConstructionInfo(mass, motionState, bulletShape, boxLocalInertia);
            var rigidBody = new RigidBody(bodyInfo);

            rigidBody.Friction        = 0.4f;
            rigidBody.RollingFriction = 1;
            rigidBody.Restitution     = 1f;

            return(rigidBody);
        }
Esempio n. 6
0
        private void LoadHammer()
        {
            string pathHammer = MediaDir + "\\Meshes\\hammer\\hammer-TgcScene.xml";

            var loader         = new TgcSceneLoader();
            var originalMeshes = loader.loadSceneFromFile(pathHammer).Meshes;

            int i = 0;

            foreach (var mesh in originalMeshes)
            {
                var hammer = mesh.createMeshInstance($"hammer_{i++}");

                var position = new TGCVector3(6643, 4105, 7041);
                var scale    = new TGCVector3(.5f, .5f, .5f);

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

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

                //hammer.createBoundingBox();

                collectModel.CollisionMeshes.Add(new ItemModel {
                    Mesh = hammer, IsCollectable = true, CollectablePosition = position
                });
            }

            //int i = 0;
            //foreach (var mesh in originalMeshes)
            //{
            //    mesh.Position = new TGCVector3(6188, 4105, 6879);
            //    mesh.Scale = new TGCVector3(1f, 1f, 1f);

            //    mesh.Effect = recoltableItemEffect;
            //    mesh.Technique = "RecolectableItemTechnique";

            //    mesh.Name = "hammer_" + i.ToString();
            //    i++;

            //    collectModel.CollisionMeshes.Add(new ItemModel { Mesh = mesh, IsCollectable = true });
            //}
        }
Esempio n. 7
0
        public override void Init()
        {
            //Primero creamos una lista de mesh con la misma esena.
            meshes = new List <TgcMesh>();
            var loader = new TgcSceneLoader();
            var scene  =
                loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera\\Palmera-TgcScene.xml");
            var baseMesh = scene.Meshes[0];

            for (var i = 0; i < 50; i++)
            {
                for (var j = 0; j < 50; j++)
                {
                    var mesh = baseMesh.clone(i + " - " + j);
                    mesh.Transform = TGCMatrix.Scaling(mesh.Scale)
                                     * TGCMatrix.RotationYawPitchRoll(mesh.Rotation.Y, mesh.Rotation.X, mesh.Rotation.Z)
                                     * TGCMatrix.Translation(i * 100, 0, j * 100);

                    meshes.Add(mesh);
                    //Se agrega un callback function para informar cuando se realiza el dispose.
                    mesh.D3dMesh.Disposing += D3dMesh_Disposing;
                }
            }
            //Una vez clonamos todas las mesh que queriamos eliminamos la esena.
            scene.DisposeAll();

            //Se crea una box y se convierte en mesh.
            var box = TGCBox.fromSize(new TGCVector3(10, 10, 10), Color.Red);

            boxMesh = box.ToMesh("box");
            //Liberamos la caja pero nos quedamos con el mesh.
            box.Dispose();

            //Creamos una esena
            var loader1 = new TgcSceneLoader();

            scene1 =
                loader1.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera\\Palmera-TgcScene.xml");

            time = 0;

            Camera = new TgcRotationalCamera(new TGCVector3(100f, 300f, 100f), 1500f, Input);
        }
        /// <summary>
        /// Metodo que se invoca todo el tiempo. Es el render-loop de una aplicacion grafica.
        /// En este metodo se deben dibujar todos los objetos que se desean mostrar.
        /// Antes de llamar a este metodo el framework limpia toda la pantalla.
        /// Por lo tanto para que un objeto se vea hay volver a dibujarlo siempre.
        /// La variable elapsedTime indica la cantidad de segundos que pasaron entre esta invocacion
        /// y la anterior de render(). Es util para animar e interpolar valores.
        /// </summary>
        public override void Render()
        {
            foreach (RigidBody boxBody in boxBodys)
            {
                //Obtenemos la matrix de directx con la transformacion que corresponde a la caja.
                boxMesh.Transform = new TGCMatrix(boxBody.InterpolationWorldTransform);
                //Dibujar las cajas en pantalla
                boxMesh.Render();
            }

            foreach (RigidBody ballBody in ballBodys)
            {
                //Obtenemos la transformacion de la pelota, en este caso se ve como se puede escalar esa transformacion.
                sphereMesh.Transform = TGCMatrix.Scaling(10, 10, 10) * new TGCMatrix(ballBody.InterpolationWorldTransform);
                sphereMesh.Render();
            }

            floorMesh.Render();
        }
Esempio n. 9
0
        public void RenderShadowMap()
        {
            // Calculo la matriz de view de la luz
            effect.SetValue("g_vLightPos", new TGCVector4(g_LightPos.X, g_LightPos.Y, g_LightPos.Z, 1));
            effect.SetValue("g_vLightDir", new TGCVector4(g_LightDir.X, g_LightDir.Y, g_LightDir.Z, 1));
            g_LightView = TGCMatrix.LookAtLH(g_LightPos, g_LightPos + g_LightDir, new TGCVector3(0, 0, 1));

            arrow.PStart = g_LightPos;
            arrow.PEnd   = g_LightPos + g_LightDir * 20f;
            arrow.updateValues();

            // inicializacion standard:
            effect.SetValue("g_mProjLight", g_mShadowProj.ToMatrix());
            effect.SetValue("g_mViewLightProj", (g_LightView * g_mShadowProj).ToMatrix());

            //frustumShadow.updateVolume(TGCMatrix.FromMatrix(D3DDevice.Instance.Device.Transform.View),
            //  TGCMatrix.FromMatrix(D3DDevice.Instance.Device.Transform.Projection));

            // Primero genero el shadow map, para ello dibujo desde el pto de vista de luz
            // a una textura, con el VS y PS que generan un mapa de profundidades.
            var pOldRT      = D3DDevice.Instance.Device.GetRenderTarget(0);
            var pShadowSurf = g_pShadowMap.GetSurfaceLevel(0);

            D3DDevice.Instance.Device.SetRenderTarget(0, pShadowSurf);
            var pOldDS = D3DDevice.Instance.Device.DepthStencilSurface;

            D3DDevice.Instance.Device.DepthStencilSurface = g_pDSShadow;
            D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Gray, 1.0f, 0);
            //D3DDevice.Instance.Device.BeginScene();

            // Hago el render de la escena pp dicha
            effect.SetValue("g_txShadow", g_pShadowMap);
            //RenderScene(true,g_LightView, g_mShadowProj);
            RenderScene2(true);
            //Termino
            //D3DDevice.Instance.Device.EndScene();
            TextureLoader.Save("shadowmap.bmp", ImageFileFormat.Bmp, g_pShadowMap);

            // restuaro el render target y el stencil
            D3DDevice.Instance.Device.DepthStencilSurface = pOldDS;
            D3DDevice.Instance.Device.SetRenderTarget(0, pOldRT);
        }
Esempio n. 10
0
        public override void Init()
        {
            drawer2D = new Drawer2D();

            //Crear Sprite
            sprite        = new CustomSprite();
            sprite.Bitmap = new CustomBitmap(MediaDir + "\\Texturas\\LogoTGC.png", D3DDevice.Instance.Device);

            //Ubicarlo centrado en la pantalla
            var textureSize = sprite.Bitmap.Size;

            sprite.Position = new TGCVector2(FastMath.Max(D3DDevice.Instance.Width / 2 - textureSize.Width / 2, 0), FastMath.Max(D3DDevice.Instance.Height / 2 - textureSize.Height / 2, 0));

            //Crear Sprite animado
            animatedSprite = new AnimatedSprite(MediaDir + "\\Texturas\\Sprites\\Explosion.png", //Textura de 256x256
                                                new Size(64, 64),                                //Tamaño de un frame (64x64px en este caso)
                                                16,                                              //Cantidad de frames, (son 16 de 64x64px)
                                                10);                                             //Velocidad de animacion, en cuadros x segundo,

            //Ubicarlo centrado en la pantalla
            var textureSizeAnimado = animatedSprite.Bitmap.Size;

            animatedSprite.Position = new TGCVector2(D3DDevice.Instance.Width / 2 - textureSizeAnimado.Width / 2, D3DDevice.Instance.Height / 2 - textureSizeAnimado.Height / 2);

            //Modifiers para variar parametros del sprite
            positionModifier = AddVertex2f("position", TGCVector2.Zero, new TGCVector2(D3DDevice.Instance.Width, D3DDevice.Instance.Height), sprite.Position);
            scalingModifier  = AddVertex2f("scaling", TGCVector2.Zero, new TGCVector2(4, 4), sprite.Scaling);
            rotationModifier = AddFloat("rotation", 0, 360, 0);

            //Modifiers para variar parametros del sprite
            frameRateAnimatedModifier = AddFloat("frameRateAnimated", 1, 30, 10);
            positionAnimatedModifier  = AddVertex2f("positionAnimated", TGCVector2.Zero, new TGCVector2(D3DDevice.Instance.Width, D3DDevice.Instance.Height), animatedSprite.Position);
            scalingAnimatedModifier   = AddVertex2f("scalingAnimated", TGCVector2.Zero, new TGCVector2(4, 4), animatedSprite.Scaling);
            rotationAnimatedModifier  = AddFloat("rotationAnimated", 0, 360, 0);

            //Creamos un Box3D para que se vea como el Sprite es en 2D y se dibuja siempre arriba de la escena 3D
            box           = TGCBox.fromSize(new TGCVector3(10, 10, 10), TgcTexture.createTexture(MediaDir + "\\Texturas\\pasto.jpg"));
            box.Transform = TGCMatrix.RotationX(FastMath.QUARTER_PI);

            //Hacer que la camara se centre en el box3D
            Camara = new TgcRotationalCamera(box.BoundingBox.calculateBoxCenter(), box.BoundingBox.calculateBoxRadius() * 2, Input);
        }
        /// <summary>
        ///     Se llama una sola vez, al principio cuando se ejecuta el ejemplo.
        ///     Escribir aquí todo el código de inicialización: cargar modelos, texturas, estructuras de optimización, todo
        ///     procesamiento que podemos pre calcular para nuestro juego.
        ///     Borrar el codigo ejemplo no utilizado.
        /// </summary>
        public override void Init()
        {
            //Device de DirectX para crear primitivas.
            var d3dDevice = D3DDevice.Instance.Device;

            var loader = new TgcSceneLoader();

            scene = loader.loadSceneFromFile(MediaDir + "primer-nivel\\pozo-plataformas\\tgc-scene\\plataformas\\plataformas-TgcScene.xml");


            var skeletalLoader = new TgcSkeletalLoader();

            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                MediaDir + "primer-nivel\\pozo-plataformas\\tgc-scene\\Robot\\Robot-TgcSkeletalMesh.xml",
                MediaDir + "primer-nivel\\pozo-plataformas\\tgc-scene\\Robot\\",
                new[]
            {
                MediaDir + "primer-nivel\\pozo-plataformas\\tgc-scene\\Robot\\Caminando-TgcSkeletalAnim.xml",
                MediaDir + "primer-nivel\\pozo-plataformas\\tgc-scene\\Robot\\Parado-TgcSkeletalAnim.xml"
            });


            personaje.AutoTransform = false;
            personaje.Transform     = TGCMatrix.Identity;

            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);
            //Escalarlo porque es muy grande
            personaje.Position = new TGCVector3(0, 0, 100);
            personaje.Scale    = new TGCVector3(0.15f, 0.15f, 0.15f);
            ultimaPos          = TGCMatrix.Translation(personaje.Position);

            camara = new GameCamera(personaje.Position, 100, 200);
            //var cameraPosition = new TGCVector3(0, 0, 200);
            //Quiero que la camara mire hacia el origen (0,0,0).
            //var lookAt = TGCVector3.Empty;
            //Configuro donde esta la posicion de la camara y hacia donde mira.
            //Camara.SetCamera(cameraPosition, lookAt);
            Camara = camara;

            BoundingBox = true;
        }
Esempio n. 12
0
        /// <summary>
        ///     Método en el que se deben crear todas las cosas que luego se van a querer usar.
        ///     Es invocado solo una vez al inicio del ejemplo.
        /// </summary>
        public override void Init()
        {
            //Todos los recursos que se van a necesitar (objetos 3D, meshes, texturas, etc) se deben cargar en el metodo init().
            //Crearlos cada vez en el metodo render() es un error grave. Destruye la performance y suele provocar memory leaks.

            //Creamos una caja 3D de color rojo, ubicada en el origen y lado 10
            var center = TGCVector3.Empty;
            var size   = new TGCVector3(10, 10, 10);
            var color  = Color.Red;

            box1           = TGCBox.fromSize(size, color);
            box1.Transform = TGCMatrix.Translation(center);

            //Cargamos una textura una textura es una imágen 2D que puede dibujarse arriba de un polígono 3D para darle color.
            //Es muy útil para generar efectos de relieves y superficies.
            //Puede ser cualquier imágen 2D (jpg, png, gif, etc.) y puede ser editada con cualquier editor
            //normal (photoshop, paint, descargada de goole images, etc).
            //El framework viene con un montón de texturas incluidas y organizadas en categorias (texturas de
            //madera, cemento, ladrillo, pasto, etc). Se encuentran en la carpeta del framework: Media\MeshCreator\Textures
            //Podemos acceder al path de la carpeta "Media" utilizando la variable "this.MediaDir".
            //Esto evita que tengamos que hardcodear el path de instalación del framework.
            var texture = TgcTexture.createTexture(MediaDir + "MeshCreator\\Textures\\Madera\\cajaMadera3.jpg");

            //Creamos una caja 3D ubicada en (10, 0, 0) y la textura como color.
            center         = new TGCVector3(15, 0, 0);
            box2           = TGCBox.fromSize(size, texture);
            box2.Transform = TGCMatrix.Translation(center);

            //Creamos una caja 3D con textura
            center             = new TGCVector3(-15, 0, 0);
            texture            = TgcTexture.createTexture(MediaDir + "MeshCreator\\Textures\\Metal\\cajaMetal.jpg");
            box3               = TGCBox.fromSize(center, size, texture);
            box3.AutoTransform = true;

            //Ubicar la camara del framework mirando al centro de este objeto.
            //La camara por default del framework es RotCamera, cuyo comportamiento es
            //centrarse sobre un objeto y permitir rotar y hacer zoom con el mouse.
            //Con clic izquierdo del mouse se rota la cámara, con el derecho se traslada y con la rueda se hace zoom.
            //Otras cámaras disponibles (a modo de ejemplo) son: FpsCamera (1ra persona) y ThirdPersonCamera (3ra persona).
            Camara = new TgcRotationalCamera(box1.BoundingBox.calculateBoxCenter(),
                                             box1.BoundingBox.calculateBoxRadius() * 5, Input);
        }
Esempio n. 13
0
        private void InitializeSphere()
        {
            // Got to set a texture, else the translation to mesh does not map UV
            var texture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\white.bmp");

            var sphere = new TGCSphere();

            sphere.Radius        = 40.0f;
            sphere.LevelOfDetail = 3;
            sphere.setTexture(texture);
            sphere.updateValues();

            sphereMesh             = sphere.toMesh("sphere");
            sphereMesh.Transform   = TGCMatrix.Scaling(TGCVector3.One * 30f);
            sphereMesh.Effect      = effect;
            sphereMesh.Technique   = "PBR";
            sphereMesh.DiffuseMaps = new TgcTexture[0];
            sphereMesh.RenderType  = TgcMesh.MeshRenderType.VERTEX_COLOR;
            sphere.Dispose();
        }
Esempio n. 14
0
        protected void SimulateAndSetTransformation(TGCVector3 newPosition, TGCVector3 newRotation, TGCVector3 newScale, TGCMatrix newTransform)
        {
            TGCVector3 oldPosition  = Position;
            TGCVector3 oldRotation  = rotation;
            TGCVector3 oldScale     = scale;
            TGCMatrix  oldTransform = newTransform;

            Position  = newPosition;
            rotation  = newRotation;
            scale     = newScale;
            Transform = newTransform;

            if (CollisionDetected() || OutOfBoundaries())
            {
                Position  = oldPosition;
                rotation  = oldRotation;
                scale     = oldScale;
                Transform = oldTransform;
            }
        }
Esempio n. 15
0
        public Arco(TgcMesh mesh, float meshRotationAngle) : base(mesh)
        {
            this.meshRotationAngle = meshRotationAngle;

            cuerpo = BulletRigidBodyFactory.Instance.CreateRigidBodyFromTgcMesh(mesh);
            TGCQuaternion rot = new TGCQuaternion();

            rot.RotateAxis(new TGCVector3(0, 1, 0), meshRotationAngle);
            cuerpo.WorldTransform = TGCMatrix.RotationTGCQuaternion(rot).ToBulletMatrix();

            UpdateAABB();
            AABBGol = new TgcBoundingAxisAlignBox(AABB.PMin + new TGCVector3(10, 10, 10), AABB.PMax - new TGCVector3(10, 10, 10));
            AABBGol.transform(Mesh.Transform);

            Ka         = 0.4f;
            Kd         = 0.55f;
            Ks         = 0.05f;
            shininess  = 0;
            reflection = 0;
        }
Esempio n. 16
0
        /// <summary>
        ///     Actualiza la matriz de transformacion
        /// </summary>
        public void updateValues()
        {
            var rotationMatrix = TGCMatrix.RotationYawPitchRoll(rotation.Y, rotation.X, rotation.Z);

            //la matriz Transformation se usa para ubicar los vertices y calcular el vector HalfHeight
            Transform =
                TGCMatrix.Scaling(Radius, HalfLength, Radius) *
                rotationMatrix *
                TGCMatrix.Translation(center);

            //la matriz AntiTransformation convierte el cilindro a uno generico de radio 1 y altura 2
            AntiTransformationMatrix =
                TGCMatrix.Invert(Transform);

            //la matriz AntiRotation sirve para alinear el cilindro con los ejes
            AntiRotationMatrix =
                TGCMatrix.Translation(-center) *
                TGCMatrix.Invert(rotationMatrix) *
                TGCMatrix.Translation(center);
        }
Esempio n. 17
0
            public PBRTexturedMesh(string name, string texturePath, TGCMatrix transform, TgcMesh mesh)
            {
                var basePBR = texturePath + "PBR\\" + name + "\\";
                var device  = D3DDevice.Instance.Device;

                albedo = TgcTexture.createTexture(device, basePBR + "Color.jpg");
                normal = TgcTexture.createTexture(device, basePBR + "Normal.jpg");
                if (File.Exists(basePBR + "Metalness.jpg"))
                {
                    metallic = TgcTexture.createTexture(device, basePBR + "Metalness.jpg");
                }
                else
                {
                    metallic = TgcTexture.createTexture(device, texturePath + "green.bmp");
                }
                roughness = TgcTexture.createTexture(device, basePBR + "Roughness.jpg");

                this.mesh      = mesh;
                this.transform = transform;
            }
Esempio n. 18
0
        private void RenderPrefilterMap(Device device)
        {
            device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(90.0f), 1f, 0.01f, 5f).ToMatrix();

            unitCube.Technique = "Prefilter";
            effect.SetValue("cubeMap", cubeMap);
            int mipLevels = 5;

            for (int lod = 0; lod < mipLevels; lod++)
            {
                float roughness = (float)lod / (float)(mipLevels - 1);
                effect.SetValue("passRoughness", roughness);
                RenderToPrefilterMapFace(CubeMapFace.PositiveX, lod);
                RenderToPrefilterMapFace(CubeMapFace.PositiveY, lod);
                RenderToPrefilterMapFace(CubeMapFace.PositiveZ, lod);
                RenderToPrefilterMapFace(CubeMapFace.NegativeX, lod);
                RenderToPrefilterMapFace(CubeMapFace.NegativeY, lod);
                RenderToPrefilterMapFace(CubeMapFace.NegativeZ, lod);
            }
        }
Esempio n. 19
0
        public override void Update()
        {
            //En cada cuadro de render rotamos la caja con cierta velocidad (en radianes)
            //Siempre tenemos que multiplicar las velocidades por el elapsedTime.
            //De esta forma la velocidad de rotacion es independiente de la potencia del CPU.
            //Sino en computadoras con CPU más rápido la caja giraría mas rápido que en computadoras mas lentas.
            box3.Rotation += new TGCVector3(0, ROTATION_SPEED * ElapsedTime, 0);

            //Aplicamos una traslación en Y. Hacemos que la caja se mueva en forma intermitente en el intervalo [0, 3] de Y.
            //Cuando llega a uno de los límites del intervalo invertimos la dirección del movimiento.
            //Tambien tenemos que multiplicar la velocidad por el elapsedTime
            box3.Position += new TGCVector3(0, MOVEMENT_SPEED * currentMoveDir * ElapsedTime, 0);

            if (FastMath.Abs(box3.Position.Y) > 3f)
            {
                currentMoveDir *= -1;
            }

            box3.Transform = TGCMatrix.RotationYawPitchRoll(box3.Rotation.Y, box3.Rotation.X, box3.Rotation.Z) * TGCMatrix.Translation(box3.Position);
        }
        /// <summary>
        ///     Transforma el BondingBox en base a una matriz de transformación.
        ///     Esto implica escalar, rotar y trasladar.
        ///     El procedimiento es mas costoso que solo hacer scaleTranslate().
        ///     Se construye un nuevo BoundingBox en base a los puntos extremos del original
        ///     más la transformación pedida.
        ///     Si el BoundingBox se transformó y luego se llama a scaleTranslate(), se respeta
        ///     la traslación y la escala, pero la rotación se va a perder.
        /// </summary>
        /// <param name="transform"></param>
        public void transform(TGCMatrix transform)
        {
            //Transformar vertices extremos originales
            var corners    = computeCorners(pMinOriginal, pMaxOriginal);
            var newCorners = new TGCVector3[corners.Length];

            for (var i = 0; i < corners.Length; i++)
            {
                newCorners[i] = TGCVector3.transform(corners[i], transform);
            }

            //Calcular nuevo BoundingBox en base a extremos transformados
            var newBB = computeFromPoints(newCorners);

            //actualizar solo pMin y pMax, pMinOriginal y pMaxOriginal quedan sin ser transformados
            pMin = newBB.pMin;
            pMax = newBB.pMax;

            dirtyValues = true;
        }
Esempio n. 21
0
        /// <summary>
        ///     Carga los valores default de la camara y limpia todos los cálculos intermedios
        /// </summary>
        public void resetValues()
        {
            EnableSpringSystem = true;
            Spring             = DEFAULT_SPRING_CONSTANT;
            Damping            = DEFAULT_DAMPING_CONSTANT;

            m_offsetDistance = 0.0f;
            m_headingDegrees = 0.0f;
            m_pitchDegrees   = 0.0f;

            Eye           = new TGCVector3(0.0f, 0.0f, 0.0f);
            Target        = new TGCVector3(0.0f, 0.0f, 0.0f);
            m_targetYAxis = TGCVector3.Up;

            m_velocity = new TGCVector3(0.0f, 0.0f, 0.0f);

            m_viewMatrix  = TGCMatrix.Identity;
            m_orientation = TGCQuaternion.Identity;
            SetCamera(Eye, Target);
        }
Esempio n. 22
0
        public void UpdateAspectRatioAndProjection(int width, int height)
        {
            AspectRatio = (float)width / height;
            Width       = width;
            Height      = height;
            //hay que actualizar tambien la matriz de proyeccion, sino sigue viendo mal.
            Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(FieldOfView, AspectRatio, ZNearPlaneDistance, ZFarPlaneDistance).ToMatrix();
            //FALTA TODO ESTO DE ABAJO....
            //DefaultValues();
            //Device.Reset(d3dpp);

            /*Viewport v = new Viewport();
             * v.MaxZ = Device.Viewport.MaxZ;
             * v.MinZ = Device.Viewport.MinZ;
             * v.X = Device.Viewport.X;
             * v.Y = Device.Viewport.Y;
             * v.Width = Width;
             * v.Height = Height;
             * Device.Viewport = v;*/
        }
Esempio n. 23
0
        public TGCVector3 calulateNextPosition(float headingDegrees, float elapsedTimeSec)
        {
            var heading = FastMath.ToRad(-headingDegrees * elapsedTimeSec);

            var quatOrientation = m_orientation;

            if (heading != 0.0f)
            {
                var rot = TGCQuaternion.RotationAxis(m_targetYAxis, heading);
                quatOrientation = TGCQuaternion.Multiply(rot, quatOrientation);
            }

            quatOrientation.Normalize();
            var viewMatrix = TGCMatrix.RotationTGCQuaternion(quatOrientation);

            var m_zAxis       = new TGCVector3(viewMatrix.M13, viewMatrix.M23, viewMatrix.M33);
            var idealPosition = Target + m_zAxis * -m_offsetDistance;

            return(idealPosition);
        }
Esempio n. 24
0
        public Bug(String MediaDir)
        {
            meshMounstroMiniatura = new TgcSceneLoader().loadSceneFromFile(MediaDir + @"monstruo-TgcScene.xml").Meshes[0];
            mesh = new TgcSceneLoader().loadSceneFromFile(MediaDir + @"Buggy-TgcScene.xml").Meshes[0];

            piezaAsociada = new Pieza(2, "Pieza 2", MediaDir + "\\2D\\windows\\windows_2.png", null);
            pistaAsociada = new Pista(null, MediaDir + "\\2D\\pista_sudo.png", null);

            mesh.Position  = new TGCVector3(-450, 40, 2500);
            mesh.Transform = TGCMatrix.Translation(-450, 40, 2500);
            meshMounstroMiniatura.Position  = new TGCVector3(-440, 40, 2400);
            meshMounstroMiniatura.Transform = TGCMatrix.Translation(-440, 40, 2400);
            meshMounstroMiniatura.RotateY(FastMath.PI);
            meshMounstroMiniatura.Scale = new TGCVector3(0.1f, 0.1f, 0.1f);
            posicionInicial             = mesh.Position;
            posicionInicialMounstro     = meshMounstroMiniatura.Position;

            interactuable = true;
            usado         = false;
        }
Esempio n. 25
0
        public void RotarMesh(Personaje personaje)
        {
            if (!this.lookAt.Equals(personaje.getPosition()))
            {
                float diferenciaEnX = personaje.getPosition().X - ghost.Position.X;
                float diferenciaEnZ = personaje.getPosition().Z - ghost.Position.Z;

                float anguloRotacion = (float)Math.Atan(diferenciaEnX / diferenciaEnZ);

                if (diferenciaEnX < 0 && diferenciaEnZ < 0)
                {
                    //3er Cuadrante
                    anguloRotacion = (float)Math.PI + anguloRotacion;
                }
                else
                {
                    if (diferenciaEnX < 0 && diferenciaEnZ > 0)
                    {
                        //2do Cuadrante
                        anguloRotacion = 2 * (float)Math.PI + anguloRotacion;
                    }
                    else
                    {
                        if (diferenciaEnX > 0 && diferenciaEnZ < 0)
                        {
                            //4to Cuadrante
                            anguloRotacion = (float)Math.PI + anguloRotacion;
                        }
                    }
                }



                ghost.Transform = TGCMatrix.Scaling(ghost.Scale) *
                                  TGCMatrix.RotationYawPitchRoll(anguloRotacion, ghost.Rotation.X, ghost.Rotation.Z)
                                  * TGCMatrix.Translation(ghost.Position);


                this.lookAt = personaje.getPosition();
            }
        }
        public override void Render()
        {
            PreRender();
            //Dibujar todo.
            //Una vez actualizadas las diferentes posiciones internas solo debemos asignar la matriz de world.
            mesh.Transform =
                TGCMatrix.Scaling(mesh.Scale)
                * TGCMatrix.RotationYawPitchRoll(mesh.Rotation.Y, mesh.Rotation.X, mesh.Rotation.Z)
                * TGCMatrix.Translation(mesh.Position);
            mesh.Render();
            //Actualmente los bounding box se actualizan solos en momento de hacer render, esto no es recomendado ya que trae overhead
            //Igualmente aqui podemos tener un objeto debug de nuestro mesh.
            mesh.BoundingBox.Render();

            box2.Transform =
                TGCMatrix.Scaling(box2.Scale)
                * TGCMatrix.RotationYawPitchRoll(box2.Rotation.Y, box2.Rotation.X, box2.Rotation.Z)
                * TGCMatrix.Translation(box2.Position);
            box2.Render();

            //Los bounding volume por la forma actual de framework no realizan transformaciones entonces podemos hacer esto:
            //D3DDevice.Instance.Device.Transform.World =
            //    TGCMatrix.Scaling(new TGCVector3(sphere.Radius, sphere.Radius, sphere.Radius))
            //                * TGCMatrix.Identity //No tienen sentido las rotaciones con la esfera.
            //                * TGCMatrix.Translation(sphere.Position);
            boundingSphere.Render();

            //Las mesh por defecto tienen el metodo UpdateMeshTransform que realiza el set por defecto.
            //Esto es igual que utilizar AutoTransform en true, con lo cual no es recomendado para casos complejos.
            meshObb.UpdateMeshTransform();
            meshObb.Render();
            //La implementacion de Obb por el momento reconstruye el obb debug siempre. Practica no recomendada.
            obb.Render();

            //triangulo
            D3DDevice.Instance.Device.Transform.World = TGCMatrix.Identity.ToMatrix();
            D3DDevice.Instance.Device.VertexFormat    = CustomVertex.PositionColored.Format;
            D3DDevice.Instance.Device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, triangle);

            PostRender();
        }
Esempio n. 27
0
        public override void Init()
        {
            //Cargar suelo
            var texture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\granito.jpg");

            suelo = new TgcPlane(new TGCVector3(-5000, 0, -5000), new TGCVector3(10000, 0f, 10000), TgcPlane.Orientations.XZplane, texture);

            //Iniciarlizar PickingRay
            pickingRay = new TgcPickingRay(Input);

            //Cargar nave
            var loader = new TgcSceneLoader();
            var scene  =
                loader.loadSceneFromFile(MediaDir +
                                         "MeshCreator\\Meshes\\Vehiculos\\NaveEspacial\\NaveEspacial-TgcScene.xml");

            mesh = scene.Meshes[0];

            //Rotación original de la malla, hacia -Z
            originalMeshRot = new TGCVector3(0, 0, -1);

            //Manipulamos los movimientos del mesh a mano
            mesh.AutoTransform = false;
            meshRotationMatrix = TGCMatrix.Identity;

            newPosition   = mesh.Position;
            applyMovement = false;

            //Crear caja para marcar en que lugar hubo colision
            collisionPointMesh = TGCBox.fromSize(new TGCVector3(3, 100, 3), Color.Red);

            //Flecha para marcar la dirección
            directionArrow           = new TgcArrow();
            directionArrow.Thickness = 5;
            directionArrow.HeadSize  = new TGCVector2(10, 10);

            //Camara en tercera persona
            camaraInterna = new TgcThirdPersonCamera(mesh.Position, 800, 1500);
            Camara        = camaraInterna;
            speedModifier = AddFloat("speed", 1000, 5000, 2500);
        }
Esempio n. 28
0
        public void Render(Microsoft.DirectX.Direct3D.Effect effect)
        {
            var device = D3DDevice.Instance.Device;

            mesh.Effect = effect;
            device.RenderState.AlphaBlendEnable = false;
            mesh.Render();


            box.Effect = effect;

            // los mesh importados de skp tienen 100 de tamaño normalizado, primero trabajo en el espacio normalizado
            // del mesh y luego paso al worldspace con la misma matriz de la nave

            float e  = 2.0f;
            float dl = 50.0f + 50.0f * e;

            TGCVector3[] T = new TGCVector3[11];
            T[0] = new TGCVector3(dl, -5.0f, 0.0f);
            T[1] = new TGCVector3(dl, -5.0f, -1.0f);
            T[2] = new TGCVector3(dl, -5.0f, 1.0f);
            T[3] = new TGCVector3(dl, -6.0f, -1.0f);
            T[4] = new TGCVector3(dl, -4.0f, 1.0f);

            T[5] = new TGCVector3(dl, -5.0f, 16.0f);
            T[6] = new TGCVector3(dl, -5.0f, 16.0f - 0.3f);
            T[7] = new TGCVector3(dl, -5.0f, 16.0f + 0.3f);

            T[8]  = new TGCVector3(dl, -5.0f, -16.0f);
            T[9]  = new TGCVector3(dl, -5.0f, -16.0f - 0.3f);
            T[10] = new TGCVector3(dl, -5.0f, -16.0f + 0.3f);


            for (int i = 0; i < 11; ++i)
            {
                box.Transform = TGCMatrix.Scaling(new TGCVector3(e, 0.1f, 0.1f)) *
                                TGCMatrix.Translation(T[i]) * mesh.Transform;
                device.RenderState.AlphaBlendEnable = true;
                box.Render();
            }
        }
Esempio n. 29
0
        /// <summary>
        ///     Cargar datos iniciales
        /// </summary>
        protected void initData(Mesh mesh, string name, MeshRenderType renderType, TgcSkeletalBone[] bones)
        {
            d3dMesh               = mesh;
            this.name             = name;
            this.renderType       = renderType;
            enabled               = false;
            autoUpdateBoundingBox = true;
            this.bones            = bones;
            attachments           = new List <TgcSkeletalBoneAttach>();
            meshInstances         = new List <TgcSkeletalMesh>();
            renderSkeleton        = false;
            AlphaBlendEnable      = false;

            //variables de movimiento
            AutoTransformEnable = false;
            translation         = TGCVector3.Empty;
            rotation            = TGCVector3.Empty;
            scale     = TGCVector3.One;
            transform = TGCMatrix.Identity;

            //variables de animacion
            isAnimating         = false;
            currentAnimation    = null;
            playLoop            = false;
            frameRate           = 0f;
            currentTime         = 0f;
            animationTimeLenght = 0f;
            currentFrame        = 0;
            animations          = new Dictionary <string, TgcSkeletalAnimation>();

            //Matrices de huesos
            boneSpaceFinalTransforms = new TGCMatrix[MAX_BONE_COUNT];

            //Shader
            vertexDeclaration = new VertexDeclaration(mesh.Device, mesh.Declaration);
            effect            = TGCShaders.Instance.TgcSkeletalMeshShader;
            technique         = TGCShaders.Instance.GetTGCSkeletalMeshTechnique(this.renderType);

            //acomodar huesos
            setupSkeleton();
        }
Esempio n. 30
0
        /////////////////////////////////////////////////////////////////////////
        ////////////////////////////////RENDER///////////////////////////////////
        /////////////////////////////////////////////////////////////////////////

        public void render(float deltaTime, TgcFrustum frustum)
        {
            foreach (var mesh in objectsInFront)
            {
                if (!librosAgarrados.Contains(mesh))
                {
                    var resultadoColisionFrustum = TgcCollisionUtils.classifyFrustumAABB(frustum, mesh.BoundingBox);
                    if (resultadoColisionFrustum != TgcCollisionUtils.FrustumResult.OUTSIDE)
                    {
                        mesh.Render();
                    }
                }
            }

            efectoOlas.SetValue("time", tiempoOlas);

            personajePrincipal.animateAndRender(deltaTime);

            HUD.Begin(SpriteFlags.AlphaBlend | SpriteFlags.SortDepthFrontToBack);

            posVidas = D3DDevice.Instance.Device.Viewport.Width - vida.Width;

            for (int i = 0; i < cantVidas; i++)
            {
                HUD.Transform = TGCMatrix.Translation(new TGCVector3(posVidas, 0, 0));
                HUD.Draw(vida.D3dTexture, Rectangle.Empty, Vector3.Empty, Vector3.Empty, Color.OrangeRed);
                posVidas -= vida.Width;
            }

            librosAdquiridos.cambiarTexto(cantidadLibrosAdquiridos.ToString());
            librosAdquiridos.cambiarTamañoLetra(28);
            librosAdquiridos.cambiarColor(Color.BlueViolet);
            librosAdquiridos.Render();

            HUD.Draw2D(fisicaLib.D3dTexture, Rectangle.Empty, new SizeF(90, 90), new PointF(D3DDevice.Instance.Width - 95, D3DDevice.Instance.Height - 145), Color.White);
            HUD.End();

            emisorDeParticulas1.render(deltaTime);
            emisorDeParticulas2.render(deltaTime);
            emisorDeParticulas3.render(deltaTime);
        }