//TODO: manejar todos los mesh de cada parcela en una una coleccion public InferiorLeft(TGCVector3 Position, TgcPlane grassPlane, TgcPlane wallPlaneX, TgcPlane wallPlaneZ, TgcPlane columnPlaneX, TgcPlane columnPlaneZ, TgcPlane topPlane, TgcMesh plantModel) { this.Position = Position; //Se define el terrno de la parcela var grassMesh = grassPlane.toMesh("floor"); grassMesh.Position = this.Position; grassMesh.Transform = TGCMatrix.Translation(grassMesh.Position); meshes.Add(grassMesh); //Variable temporal que contiene el modelo var basePlant = plantModel; basePlant.Position = new TGCVector3(Position.X + 5, Position.Y, Position.Z + 45); basePlant.Scale = new TGCVector3(0.5f, 0.5f, 0.5f); var random = new Random(); var ran = random.Next(0, 100); basePlant.RotateY(ran); basePlant.Enabled = true; basePlant.UpdateMeshTransform(); plantas.Add(basePlant); basePlant = basePlant.clone("plantaizquierda2"); basePlant.Position = new TGCVector3(Position.X + 5, Position.Y, Position.Z + 25); ran = random.Next(0, 100); basePlant.RotateY(ran); basePlant.UpdateMeshTransform(); plantas.Add(basePlant); basePlant = basePlant.clone("plantaizquierda4"); basePlant.Position = new TGCVector3(Position.X + 5, Position.Y, Position.Z + 5); ran = random.Next(0, 100); basePlant.RotateY(ran); basePlant.UpdateMeshTransform(); plantas.Add(basePlant); basePlant = basePlant.clone("plantaabajo0"); basePlant.Position = new TGCVector3(Position.X + 40, Position.Y, Position.Z + 5); ran = random.Next(0, 100); basePlant.RotateY(ran); basePlant.UpdateMeshTransform(); plantas.Add(basePlant); basePlant = basePlant.clone("plantaabajo2"); basePlant.Position = new TGCVector3(Position.X + 20, Position.Y, Position.Z + 5); ran = random.Next(0, 100); basePlant.RotateY(ran); basePlant.UpdateMeshTransform(); plantas.Add(basePlant); basePlant = basePlant.clone("plantaabajo4"); basePlant.Position = new TGCVector3(Position.X, Position.Y, Position.Z + 5); ran = random.Next(0, 100); basePlant.RotateY(ran); basePlant.UpdateMeshTransform(); plantas.Add(basePlant); var baseWall = wallPlaneX; var wallMesh = baseWall.toMesh("WallVA"); wallMesh.RotateZ(FastMath.ToRad(2 * 7.125f)); wallMesh.Position = new TGCVector3(Position.X + 5, Position.Y, Position.Z); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); baseWall = wallPlaneZ; wallMesh = baseWall.toMesh("WallB"); wallMesh.RotateX(-FastMath.ToRad(2 * 7.125f)); wallMesh.Position = new TGCVector3(Position.X, Position.Y, Position.Z + 5); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); //Columnas var column = new Column { Position = this.Position }; meshes.AddRange(column.CreateColumn(columnPlaneX, columnPlaneZ, TGCVector3.Empty)); meshes.AddRange(column.CreateColumn(columnPlaneX, columnPlaneZ, new TGCVector3(0, 0, 45))); meshes.AddRange(column.CreateColumn(columnPlaneX, columnPlaneZ, new TGCVector3(45, 0, 0))); meshes.AddRange(column.CreateColumn(columnPlaneX, columnPlaneZ, new TGCVector3(45, 0, 45))); //Tapas de columnas baseWall = topPlane; wallMesh = baseWall.toMesh("TopColumn1"); wallMesh.Position = new TGCVector3(Position.X, Position.Y + 20, Position.Z); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); wallMesh = wallMesh.clone("TopColumn2"); wallMesh.Position = new TGCVector3(Position.X + 45, Position.Y + 20, Position.Z); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); wallMesh = wallMesh.clone("TopColumn3"); wallMesh.Position = new TGCVector3(Position.X + 45, Position.Y + 20, Position.Z + 45); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); wallMesh = wallMesh.clone("TopColumn4"); wallMesh.Position = new TGCVector3(Position.X, Position.Y + 20, Position.Z + 45); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); }
/// <summary> /// Convierte el box en un TgcMesh /// </summary> /// <param name="meshName">Nombre de la malla que se va a crear</param> public TgcMesh ToMesh(string meshName) { //Obtener matriz para transformar vertices if (AutoTransform) { Transform = TGCMatrix.RotationYawPitchRoll(rotation.Y, rotation.X, rotation.Z) * TGCMatrix.Translation(translation); } return(TgcMesh.FromTGCBox(meshName, this.Texture, this.vertices, this.Transform, this.AlphaBlendEnable)); }
/// <summary> /// Genera la proxima matriz de view, sin actualizar aun los valores internos /// </summary> /// <param name="pos">Futura posicion de camara generada</param> /// <param name="targetCenter">Futuro centro de camara a generada</param> public void CalculatePositionTarget(out TGCVector3 pos, out TGCVector3 targetCenter) { //alejarse, luego rotar y lueg ubicar camara en el centro deseado targetCenter = TGCVector3.Add(Target, TargetDisplacement); var m = TGCMatrix.Translation(0, OffsetHeight, OffsetForward) * TGCMatrix.RotationY(RotationY) * TGCMatrix.Translation(targetCenter); //Extraer la posicion final de la matriz de transformacion pos = new TGCVector3(m.M41, m.M42, m.M43); }
public override void Update() { PreUpdate(); // Los movimientos de teclado no validan que la mesh se atraviecen, solo modifican el angulo o traslacion. if (Input.keyDown(Key.A)) { pinzaDang += VELOCIDAD_ANGULAR * ElapsedTime; } else if (Input.keyDown(Key.S)) { pinzaDang -= VELOCIDAD_ANGULAR * ElapsedTime; } if (Input.keyDown(Key.Q)) { pinzaTraslacion += VELOCIDAD_ANGULAR * ElapsedTime; } else if (Input.keyDown(Key.W)) { pinzaTraslacion -= VELOCIDAD_ANGULAR * ElapsedTime; } if (Input.keyDown(Key.Left)) { antebrazoDAng += VELOCIDAD_ANGULAR * ElapsedTime; } else if (Input.keyDown(Key.Right)) { antebrazoDAng -= VELOCIDAD_ANGULAR * ElapsedTime; } if (Input.keyDown(Key.Up)) { brazoDAng += VELOCIDAD_ANGULAR * ElapsedTime; } else if (Input.keyDown(Key.Down)) { brazoDAng -= VELOCIDAD_ANGULAR * ElapsedTime; } // 1- Base del brazo // ajusto a la medida fija // Estas medidas fijas de escalas podrian calcularse en Init, a fines didacticos se hacen en cada update. escalaBase = TGCMatrix.Scaling(baseDX, baseDY, baseDZ); // 2- Brazo // ajusto a la medida fija escalaBrazo = TGCMatrix.Scaling(brazoDx, brazoDY, brazoDZ); // y lo traslado un poco para arriba, para que quede ubicado arriba de la base var T = TGCMatrix.Translation(0, brazoDY / 2.0f + baseDY / 2.0f, 0); // Guardo el punto donde tiene que girar el brazo = en la parte de abajo del brazo // le aplico la misma transformacion que al brazo (sin tener en cuenta el escalado) var pivoteBrazo = TGCVector3.TransformCoordinate(new TGCVector3(0, -brazoDY / 2.0f, 0.0f), T); // Ahora giro el brazo sobre el pivote, para ello, primero traslado el centro del mesh al pivote, // ahi aplico la rotacion, y luego vuelvo a trasladar a la posicion original var Rot = TGCMatrix.RotationZ(brazoDAng); var A = TGCMatrix.Translation(-pivoteBrazo.X, -pivoteBrazo.Y, -pivoteBrazo.Z); var B = TGCMatrix.Translation(pivoteBrazo.X, pivoteBrazo.Y, pivoteBrazo.Z); // Se calcula la matriz resultante, para utilizarse en render. transformacionBrazo = T * A * Rot * B; // 3- ante brazo // ajusto a la medida fija escalaAntebrazo = TGCMatrix.Scaling(antebrazoDX, antebrazoDY, antebrazoDZ); T = TGCMatrix.Translation(0, brazoDY / 2 + antebrazoDY / 2.0f, 0) * transformacionBrazo; // Guardo el punto donde tiene que girar el antebrazo var pivoteAntebrazo = TGCVector3.TransformCoordinate(new TGCVector3(0, -antebrazoDY / 2.0f, 0.0f), T); // orientacion del antebrazo Rot = TGCMatrix.RotationZ(antebrazoDAng); A = TGCMatrix.Translation(-pivoteAntebrazo.X, -pivoteAntebrazo.Y, -pivoteAntebrazo.Z); B = TGCMatrix.Translation(pivoteAntebrazo.X, pivoteAntebrazo.Y, pivoteAntebrazo.Z); // Se calcula la matriz resultante, para utilizarse en render. transformacionAntebrazo = T * A * Rot * B; // 4- pinza izquierda escalaPinza = TGCMatrix.Scaling(pinzaDX, pinzaDY, pinzaDZ); var C = TGCMatrix.Translation(pinzaTraslacion, 0f, 0f); T = C * TGCMatrix.Translation(pinzaDX / 2 - antebrazoDX / 2, antebrazoDY / 2.0f + pinzaDY / 2.0f, 0) * transformacionAntebrazo; // Guardo el punto donde tiene que girar la pinza var pivotePinzaIzquierda = TGCVector3.TransformCoordinate(new TGCVector3(0, -pinzaDY / 2.0f, 0.0f), T); // orientacion de la pinza Rot = TGCMatrix.RotationZ(pinzaDang); A = TGCMatrix.Translation(-pivotePinzaIzquierda.X, -pivotePinzaIzquierda.Y, -pivotePinzaIzquierda.Z); B = TGCMatrix.Translation(pivotePinzaIzquierda.X, pivotePinzaIzquierda.Y, pivotePinzaIzquierda.Z); // Se calcula la matriz resultante, para utilizarse en render. transformacionPinzaIzquierda = T * A * Rot * B; // mano derecha escalaPinza = TGCMatrix.Scaling(pinzaDX, pinzaDY, pinzaDZ); C = TGCMatrix.Translation(-pinzaTraslacion, 0f, 0f); T = C * TGCMatrix.Translation(antebrazoDX / 2 - pinzaDX / 2, antebrazoDY / 2 + pinzaDY / 2.0f, 0) * transformacionAntebrazo; // Guardo el punto donde tiene que girar la pinza var pivotePinzaDerecha = TGCVector3.TransformCoordinate(new TGCVector3(0, -pinzaDY / 2.0f, 0.0f), T); // orientacion de la pinza Rot = TGCMatrix.RotationZ(-pinzaDang); A = TGCMatrix.Translation(-pivotePinzaDerecha.X, -pivotePinzaDerecha.Y, -pivotePinzaDerecha.Z); B = TGCMatrix.Translation(pivotePinzaDerecha.X, pivotePinzaDerecha.Y, pivotePinzaDerecha.Z); // Se calcula la matriz resultante, para utilizarse en render. transformacionPinzaDerecha = T * A * Rot * B; PostUpdate(); }
public override void Update() { var velocidadCaminar = 400f; var velocidadRotacion = 120f; //Calcular proxima posicion de personaje segun Input var moveForward = 0f; float rotate = 0; var moving = false; var rotating = false; //Adelante if (Input.keyDown(Key.W)) { moveForward = -velocidadCaminar; moving = true; } //Atras if (Input.keyDown(Key.S)) { moveForward = velocidadCaminar; moving = true; } //Derecha if (Input.keyDown(Key.D)) { rotate = velocidadRotacion; rotating = true; } //Izquierda if (Input.keyDown(Key.A)) { rotate = -velocidadRotacion; rotating = true; } //Si hubo rotacion if (rotating) { //Rotar personaje y la camara, hay que multiplicarlo por el tiempo transcurrido para no atarse a la velocidad el hardware var rotAngle = Geometry.DegreeToRadian(rotate * ElapsedTime); personaje.Rotation += new TGCVector3(0, rotAngle, 0); camaraInterna.rotateY(rotAngle); } //Si hubo desplazamiento if (moving) { //Activar animacion de caminando personaje.playAnimation("Caminando", true); //Aplicar movimiento hacia adelante o atras segun la orientacion actual del Mesh var lastPos = personaje.Position; //La velocidad de movimiento tiene que multiplicarse por el elapsedTime para hacerse independiente de la velocida de CPU //Ver Unidad 2: Ciclo acoplado vs ciclo desacoplado var moveF = moveForward * ElapsedTime; var z = (float)Math.Cos(personaje.Rotation.Y) * moveF; var x = (float)Math.Sin(personaje.Rotation.Y) * moveF; personaje.Position += new TGCVector3(x, 0, z); //Detectar colisiones var collide = false; foreach (var obstaculo in obstaculos) { var result = TgcCollisionUtils.classifyBoxBox(personaje.BoundingBox, obstaculo.BoundingBox); if (result == TgcCollisionUtils.BoxBoxResult.Adentro || result == TgcCollisionUtils.BoxBoxResult.Atravesando) { collide = true; break; } } //Si hubo colision, restaurar la posicion anterior if (collide) { personaje.Position = lastPos; } personaje.Transform = TGCMatrix.Scaling(personaje.Scale) * TGCMatrix.RotationYawPitchRoll(personaje.Rotation.Y, personaje.Rotation.X, personaje.Rotation.Z) * TGCMatrix.Translation(personaje.Position); //Hacer que la camara siga al personaje en su nueva posicion camaraInterna.Target = personaje.Position; } //Si no se esta moviendo, activar animacion de Parado else { personaje.playAnimation("Parado", true); } //Ajustar la posicion de la camara segun la colision con los objetos del escenario ajustarPosicionDeCamara(); }
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); Camera = new TgcFpsCamera(new TGCVector3(147.2558f, 8.0f, 262.2509f), 100f, 10f, Input); Camera.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); TgcSkeletalMesh enemigo = skeletalLoader.loadMeshAndAnimationsFromFile(MediaDir + "SkeletalAnimations\\BasicHuman\\" + "CombineSoldier-TgcSkeletalMesh.xml", MediaDir + "SkeletalAnimations\\BasicHuman\\", new string[] { MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Walk-TgcSkeletalAnim.xml", }); enemigos.Add(enemigo); //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); enemigos[cant_enemigos].Transform = TGCMatrix.Scaling(enemigos[cant_enemigos].Scale) * TGCMatrix.RotationYawPitchRoll(enemigos[cant_enemigos].Rotation.Y, enemigos[cant_enemigos].Rotation.X, enemigos[cant_enemigos].Rotation.Z) * TGCMatrix.Translation(enemigos[cant_enemigos].Position); 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); }
/// <summary> /// Genera la proxima matriz de view, sin actualizar aun los valores internos /// </summary> /// <param name="pos">Futura posicion de camara generada</param> /// <param name="targetCenter">Futuro centro de camara a generada</param> public void CalculatePositionTarget(out TGCVector3 pos, out TGCVector3 targetCenter) { //alejarse, luego rotar y lueg ubicar camara en el centro deseado targetCenter = Target; var m = TGCMatrix.Translation(0, DesplazarAltura, DesplazarAdelante) * TGCMatrix.RotationY(RotationY) * TGCMatrix.Translation(targetCenter); //Extraer la posicion final de la matriz de transformacion pos = new TGCVector3(m.M41, m.M42, m.M43); }
public void CalculatePositionTarget(out TGCVector3 pos, out TGCVector3 targetCenter) { targetCenter = TGCVector3.Add(Target, TargetDisplacement); var m = TGCMatrix.Translation(0, OffsetHeight, OffsetForward) * TGCMatrix.RotationY(RotationY) * TGCMatrix.Translation(targetCenter); pos = new TGCVector3(m.M41, m.M42, m.M43); }
public void Update() { TGCQuaternion camRot = cam.GetRotation(); TGCMatrix plrTransform = TGCMatrix.Translation(Player.Instance().Position()); mesh.Transform = TGCMatrix.Scaling(mesh.Scale) * TGCMatrix.RotationTGCQuaternion(rotOffset) * TGCMatrix.Translation(posOffset) * TGCMatrix.RotationTGCQuaternion(camRot) * plrTransform; }
/// <summary> /// Prepara una nueva animacion para ser ejecutada /// </summary> protected void initAnimationSettings(string animationName, bool playLoop, float userFrameRate) { isAnimating = true; currentAnimation = animations[animationName]; this.playLoop = playLoop; currentTime = 0; currentFrame = 0; //Cambiar BoundingBox boundingBox = currentAnimation.BoundingBox; updateBoundingBox(); //Si el usuario no especifico un FrameRate, tomar el default de la animacion if (userFrameRate == -1f) { frameRate = currentAnimation.FrameRate; } else { frameRate = userFrameRate; } //La duracion de la animacion. animationTimeLenght = ((float)currentAnimation.FramesCount - 1) / frameRate; //Configurar postura inicial de los huesos for (var i = 0; i < bones.Length; i++) { var bone = bones[i]; if (!currentAnimation.hasFrames(i)) { throw new Exception("El hueso " + bone.Name + " no posee KeyFrames"); } //Determinar matriz local inicial var firstFrame = currentAnimation.BoneFrames[i][0]; bone.MatLocal = TGCMatrix.RotationTGCQuaternion(firstFrame.Rotation) * TGCMatrix.Translation(firstFrame.Position); //Multiplicar por matriz del padre, si tiene if (bone.ParentBone != null) { bone.MatFinal = bone.MatLocal * bone.ParentBone.MatFinal; } else { bone.MatFinal = bone.MatLocal; } } //Ajustar vertices a posicion inicial del esqueleto updateMeshVertices(); }
/// <summary> /// Actualiza la posicion de cada hueso del esqueleto segun sus KeyFrames de la animacion /// </summary> protected void updateSkeleton() { for (var i = 0; i < bones.Length; i++) { var bone = bones[i]; //Tomar el frame actual para este hueso var boneFrames = currentAnimation.BoneFrames[i]; //Solo hay un frame, no hacer nada, ya se hizo en el Init de la animacion if (boneFrames.Count == 1) { continue; } //Obtener cuadro actual segun el tiempo transcurrido var currentFrameF = currentTime * frameRate; //Ve a que KeyFrame le corresponde var keyFrameIdx = getCurrentFrameBone(boneFrames, currentFrameF); currentFrame = keyFrameIdx; //Armar un intervalo entre el proximo KeyFrame y el anterior var frame1 = boneFrames[keyFrameIdx - 1]; var frame2 = boneFrames[keyFrameIdx]; //Calcular la cantidad que hay interpolar en base al la diferencia entre cuadros float framesDiff = frame2.Frame - frame1.Frame; var interpolationValue = (currentFrameF - frame1.Frame) / framesDiff; //Interpolar traslacion var frameTranslation = (frame2.Position - frame1.Position) * interpolationValue + frame1.Position; //Interpolar rotacion con SLERP var quatFrameRotation = TGCQuaternion.Slerp(frame1.Rotation, frame2.Rotation, interpolationValue); //Unir ambas transformaciones de este frame var frameMatrix = TGCMatrix.RotationTGCQuaternion(quatFrameRotation) * TGCMatrix.Translation(frameTranslation); //Multiplicar por la matriz del padre, si tiene if (bone.ParentBone != null) { bone.MatFinal = frameMatrix * bone.ParentBone.MatFinal; } else { bone.MatFinal = frameMatrix; } } }
public Inicio(TGCVector3 Position, TgcPlane grassPlane, TgcTexture wallTexture, TgcPlane columnPlaneX, TgcPlane columnPlaneZ, TgcPlane topPlane) { this.Position = Position; //Se define el terrno de la parcela var grassMesh = grassPlane.toMesh("floor"); grassMesh.Position = this.Position; grassMesh.Transform = TGCMatrix.Translation(grassMesh.Position); meshes.Add(grassMesh); #region Paredes var baseWall = new TgcPlane(new TGCVector3(), new TGCVector3(0, 20f, 50), TgcPlane.Orientations.YZplane, wallTexture, 2, 1); var wallMesh = baseWall.toMesh("WallVA"); wallMesh.Position = new TGCVector3(Position.X, Position.Y, Position.Z); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); wallMesh = wallMesh.clone("WallVB"); wallMesh.Position = new TGCVector3(Position.X + 50, Position.Y, Position.Z); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); var baseTriangleWallH = new TgcPlane(new TGCVector3(), new TGCVector3(50, 20f, 0), TgcPlane.Orientations.XYplane, wallTexture, 2, 1); wallMesh = baseTriangleWallH.toMesh("WallHA"); wallMesh.Position = new TGCVector3(Position.X, Position.Y, Position.Z + 12.5f); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); wallMesh = wallMesh.clone("Wall45"); wallMesh.RotateY(FastMath.ToRad(45)); wallMesh.Position = new TGCVector3(Position.X, Position.Y, Position.Z + 25); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); wallMesh = wallMesh.clone("Wall135"); wallMesh.RotateY(FastMath.ToRad(90)); wallMesh.Position = new TGCVector3(Position.X + 50, Position.Y, Position.Z + 25); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); #endregion #region Columnas //Columnas var column = new Column { Position = this.Position }; meshes.AddRange(column.CreateColumn(columnPlaneX, columnPlaneZ, TGCVector3.Empty)); meshes.AddRange(column.CreateColumn(columnPlaneX, columnPlaneZ, new TGCVector3(0, 0, 45))); meshes.AddRange(column.CreateColumn(columnPlaneX, columnPlaneZ, new TGCVector3(45, 0, 0))); meshes.AddRange(column.CreateColumn(columnPlaneX, columnPlaneZ, new TGCVector3(45, 0, 45))); #endregion //Tapas de columnas baseWall = topPlane; wallMesh = baseWall.toMesh("TopColumn3"); wallMesh.Position = new TGCVector3(Position.X + 45, Position.Y + 20, Position.Z + 45); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); wallMesh = wallMesh.clone("TopColumn4"); wallMesh.Position = new TGCVector3(Position.X, Position.Y + 20, Position.Z + 45); wallMesh.UpdateMeshTransform(); meshes.Add(wallMesh); }
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(); }
public TGCMatrix MovementMatrix() { return(TGCMatrix.Translation(MovementVector)); }
public override void Render() { PreRender(); //Bounding volumes. //Los bounding volumes realizan un update de los vertices en momento de render, por ello pueden ser mas lentos que utilizar transformadas. if (fixedYModifier.Value) { colliderCylinderFixedY.Render(); } else { colliderCylinder.Render(); } //Render personaje personaje.Transform = TGCMatrix.Scaling(personaje.Scale) * TGCMatrix.RotationYawPitchRoll(personaje.Rotation.Y, personaje.Rotation.X, personaje.Rotation.Z) * TGCMatrix.Translation(personaje.Position); personaje.animateAndRender(ElapsedTime); if (fixedYModifier.Value) { personaje.BoundingBox.Render(); } //Render de objetos estaticos collisionableSphere.Render(); collisionableMeshAABB.BoundingBox.Render(); collisionableCylinder.Render(); //Dibujar todo mallas. //Una vez actualizadas las diferentes posiciones internas solo debemos asignar la matriz de world. collisionableMeshAABB.Transform = TGCMatrix.Scaling(collisionableMeshAABB.Scale) * TGCMatrix.Translation(collisionableMeshAABB.Position); collisionableMeshAABB.Render(); PostRender(); }
/// <summary> /// Actualiza la matriz de transformacion con los datos internos del mesh (scale. rotation, traslation) para casos complejos es mejor no utilizar este metodo. /// </summary> public void UpdateMeshTransform() { transform = TGCMatrix.Scaling(scale) * TGCMatrix.RotationYawPitchRoll(rotation.Y, rotation.X, rotation.Z) * TGCMatrix.Translation(translation); }
public override void Update() { Random rnd = new Random(); float speed = 20f * ElapsedTime; for (int t = 0; t < cant_enemigos; ++t) { float an = enemigo_an[t]; TGCVector3 vel = new TGCVector3((float)Math.Sin(an), 0, (float)Math.Cos(an)); //Mover personaje TGCVector3 lastPos = enemigos[t].Position; enemigos[t].Position += (vel * speed); enemigos[t].Rotation += new TGCVector3(0, (float)Math.PI / 2 + an, 0); //Detectar colisiones de BoundingBox utilizando herramienta TgcCollisionUtils bool collide = false; foreach (TgcMesh obstaculo in scene.Meshes) { TgcCollisionUtils.BoxBoxResult result = TgcCollisionUtils.classifyBoxBox(enemigos[t].BoundingBox, obstaculo.BoundingBox); if (result == TgcCollisionUtils.BoxBoxResult.Adentro || result == TgcCollisionUtils.BoxBoxResult.Atravesando) { collide = true; break; } } //Si hubo colision, restaurar la posicion anterior if (collide) { enemigos[t].Position = lastPos; enemigo_an[t] += rnd.Next(0, 100) / 100.0f; } enemigos[t].Transform = TGCMatrix.Scaling(enemigos[t].Scale) * TGCMatrix.RotationY(enemigos[t].Rotation.Y) * TGCMatrix.Translation(enemigos[t].Position); enemigos[t].updateAnimation(ElapsedTime); } }
public override void Render() { PreRender(); //Si hacen clic con el mouse, ver si hay colision con el suelo if (Input.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT)) { //Actualizar Ray de colisión en base a posición del mouse pickingRay.updateRay(); //Detectar colisión Ray-AABB if (TgcCollisionUtils.intersectRayAABB(pickingRay.Ray, suelo.BoundingBox, out newPosition)) { //Fijar nueva posición destino applyMovement = true; collisionPointMesh.Position = newPosition; directionArrow.PEnd = new TGCVector3(newPosition.X, 30f, newPosition.Z); //Rotar modelo en base a la nueva dirección a la que apunta var direction = TGCVector3.Normalize(newPosition - mesh.Position); var angle = FastMath.Acos(TGCVector3.Dot(originalMeshRot, direction)); var axisRotation = TGCVector3.Cross(originalMeshRot, direction); meshRotationMatrix = TGCMatrix.RotationAxis(axisRotation, angle); } } var speed = speedModifier.Value; //Interporlar movimiento, si hay que mover if (applyMovement) { //Ver si queda algo de distancia para mover var posDiff = newPosition - mesh.Position; var posDiffLength = posDiff.LengthSq(); if (posDiffLength > float.Epsilon) { //Movemos el mesh interpolando por la velocidad var currentVelocity = speed * ElapsedTime; posDiff.Normalize(); posDiff.Multiply(currentVelocity); //Ajustar cuando llegamos al final del recorrido var newPos = mesh.Position + posDiff; if (posDiff.LengthSq() > posDiffLength) { newPos = newPosition; } //Actualizar flecha de movimiento directionArrow.PStart = new TGCVector3(mesh.Position.X, 30f, mesh.Position.Z); directionArrow.updateValues(); //Actualizar posicion del mesh mesh.Position = newPos; //Como desactivamos la transformacion automatica, tenemos que armar nosotros la matriz de transformacion mesh.Transform = meshRotationMatrix * TGCMatrix.Translation(mesh.Position); //Actualizar camara camaraInterna.Target = mesh.Position; } //Se acabo el movimiento else { applyMovement = false; } } //Mostrar caja con lugar en el que se hizo click, solo si hay movimiento if (applyMovement) { collisionPointMesh.Render(); directionArrow.Render(); } suelo.Render(); mesh.Render(); PostRender(); }
private void PerformNormalMove(float elapsedTime, float speed, TGCVector3 headPosition) { CharacterOnSight = false; var XRotation = 0f; var YRotation = 0f; ChangeDirectionTimeCounter -= elapsedTime; Terrain.world.InterpoledHeight(headPosition.X, headPosition.Z, out float floorHeight); var distanceToFloor = Body.CenterOfMassPosition.Y - floorHeight; var XRotationStep = FastMath.PI * 0.1f * elapsedTime; var YRotationStep = FastMath.PI * 0.4f * elapsedTime; var distanceToWater = Constants.WATER_HEIGHT - floorHeight - 200; TGCVector2 sharkRangePosition = new TGCVector2(Constants.SHARK_HEIGHT.X, FastMath.Min(distanceToWater, Constants.SHARK_HEIGHT.Y)); if (distanceToFloor < sharkRangePosition.X - 150 && AcumulatedXRotation < Constants.MaxAxisRotation) { XRotation = XRotationStep; } else if (FastUtils.IsNumberBetweenInterval(distanceToFloor, sharkRangePosition) && AcumulatedXRotation > 0.0012) { XRotation = -XRotationStep; } else if (distanceToFloor > sharkRangePosition.Y + 150 && AcumulatedXRotation > -Constants.MaxAxisRotation) { XRotation = -XRotationStep; } else if (FastUtils.IsNumberBetweenInterval(distanceToFloor, sharkRangePosition) && AcumulatedXRotation < -0.0012) { XRotation = XRotationStep; } if (ChangeDirectionTimeCounter <= 0) { if (FastMath.Abs(AcumulatedYRotation) < Constants.MaxYRotation) { YRotation = YRotationStep * RotationYSign(); } else { ChangeDirectionTimeCounter = Constants.CHANGE_DIRECTION_TIME; } } else { AcumulatedYRotation = 0; } AcumulatedXRotation += XRotation; AcumulatedYRotation += YRotation; Body.ActivationState = ActivationState.ActiveTag; TGCMatrix rotation = TGCMatrix.Identity; if (XRotation != 0 || FastMath.Abs(AcumulatedXRotation) > 0.0012) { var rotationAxis = TGCVector3.Cross(TGCVector3.Up, director); director.TransformCoordinate(TGCMatrix.RotationAxis(rotationAxis, XRotation)); rotation = TGCMatrix.RotationAxis(rotationAxis, XRotation); speed /= 1.5f; } else if (YRotation != 0) { director.TransformCoordinate(TGCMatrix.RotationY(YRotation)); rotation = TGCMatrix.RotationY(YRotation); } TotalRotation *= rotation; Mesh.Transform = TotalRotation * TGCMatrix.Translation(new TGCVector3(Body.CenterOfMassPosition)); Body.WorldTransform = Mesh.Transform.ToBulletMatrix(); Body.LinearVelocity = director.ToBulletVector3() * -speed; }
public override void Update() { PreUpdate(); this.handleInput(); this.time += ElapsedTime; this.sphere.Transform = TGCMatrix.Scaling(this.scale) * TGCMatrix.RotationYawPitchRoll(this.rotation, 0, 0) * TGCMatrix.Translation(this.center); this.updateEffectVector(); this.effect.SetValue("time", this.time); TGCVector3 centeredEffectVector = this.effectVector - this.center; this.effect.SetValue("effectVector", new[] { centeredEffectVector.X, centeredEffectVector.Y, centeredEffectVector.Z }); this.effect.SetValue("factor", (float)Math.Round(sumValue, 2)); this.effect.SetValue("matViewProj", D3DDevice.Instance.Device.Transform.View * D3DDevice.Instance.Device.Transform.Projection); this.effect.SetValue("eyePosition", new[] { this.Camara.Position.X, this.Camara.Position.Y, this.Camara.Position.Z }); PostUpdate(); }
public override void Init() { //Cargar textura de CubeMap para Environment Map cubeMap = TextureLoader.FromCubeFile(D3DDevice.Instance.Device, MediaDir + "CubeMap.dds"); //Crear 3 paredes y un piso con textura comun y textura de normalMap var diffuseMap = TgcTexture.createTexture(MediaDir + "Texturas//BM_DiffuseMap_pared.jpg"); var normalMap = TgcTexture.createTexture(MediaDir + "Texturas//BM_NormalMap.jpg"); TgcTexture[] normalMapArray = { normalMap }; var paredSur = TGCBox.fromExtremes(new TGCVector3(-200, 0, -210), new TGCVector3(200, 100, -200), diffuseMap); paredSur.Transform = TGCMatrix.Translation(paredSur.Position); var paredOeste = TGCBox.fromExtremes(new TGCVector3(-210, 0, -200), new TGCVector3(-200, 100, 200), diffuseMap); paredOeste.Transform = TGCMatrix.Translation(paredOeste.Position); var paredEste = TGCBox.fromExtremes(new TGCVector3(200, 0, -200), new TGCVector3(210, 100, 200), diffuseMap); paredEste.Transform = TGCMatrix.Translation(paredEste.Position); var piso = TGCBox.fromExtremes(new TGCVector3(-200, -1, -200), new TGCVector3(200, 0, 200), diffuseMap); piso.Transform = TGCMatrix.Translation(piso.Position); //Convertir TgcBox a TgcMesh var m1 = paredSur.ToMesh("paredSur"); var m2 = paredOeste.ToMesh("paredOeste"); var m3 = paredEste.ToMesh("paredEste"); var m4 = piso.ToMesh("piso"); //Convertir TgcMesh a TgcMeshBumpMapping meshes = new List <TgcMeshBumpMapping>(); meshes.Add(TgcMeshBumpMapping.fromTgcMesh(m1, normalMapArray)); meshes.Add(TgcMeshBumpMapping.fromTgcMesh(m2, normalMapArray)); meshes.Add(TgcMeshBumpMapping.fromTgcMesh(m3, normalMapArray)); meshes.Add(TgcMeshBumpMapping.fromTgcMesh(m4, normalMapArray)); //Borrar TgcMesh y TgcBox, ya no se usan paredSur.Dispose(); paredOeste.Dispose(); paredEste.Dispose(); piso.Dispose(); m1.Dispose(); m2.Dispose(); m3.Dispose(); m4.Dispose(); //Camara en 1ra persona Camera = new TgcFpsCamera(new TGCVector3(200, 60, 50), Input); //Cargar Shader personalizado para EnviromentMap effect = TGCShaders.Instance.LoadEffect(ShadersDir + "EnvironmentMap.fx"); //Cargar shader en meshes foreach (var m in meshes) { m.Effect = effect; m.Technique = "EnvironmentMapTechnique"; } //Mesh para la luz lightMesh = TGCBox.fromSize(new TGCVector3(10, 10, 10), Color.Red); reflectionModifier = AddFloat("reflection", 0, 1, 0.35f); bumpinessModifier = AddFloat("bumpiness", 0, 1, 1f); lightPosModifier = AddVertex3f("lightPos", new TGCVector3(-200, 0, -200), new TGCVector3(200, 100, 200), new TGCVector3(0, 80, 0)); lightColorModifier = AddColor("lightColor", Color.White); lightIntensityModifier = AddFloat("lightIntensity", 0, 150, 20); lightAttenuationModifier = AddFloat("lightAttenuation", 0.1f, 2, 0.3f); specularExModifier = AddFloat("specularEx", 0, 20, 9f); mEmissiveModifier = AddColor("mEmissive", Color.Black); mAmbientModifier = AddColor("mAmbient", Color.White); mDiffuseModifier = AddColor("mDiffuse", Color.White); mSpecularModifier = AddColor("mSpecular", Color.White); }
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 Update() { var velocidadCaminar = VELOCIDAD_DESPLAZAMIENTO * ElapsedTime; //Calcular proxima posicion de personaje segun Input var moving = false; var movement = TGCVector3.Empty; //Adelante if (Input.keyDown(Key.W)) { movement.Z = velocidadCaminar; moving = true; } //Atras if (Input.keyDown(Key.S)) { movement.Z = -velocidadCaminar; moving = true; } //Derecha if (Input.keyDown(Key.D)) { movement.X = velocidadCaminar; moving = true; } //Izquierda if (Input.keyDown(Key.A)) { movement.X = -velocidadCaminar; moving = true; } //Salto if (Input.keyDown(Key.Space)) { movement.Y = velocidadCaminar; moving = true; } //Agachar if (Input.keyDown(Key.LeftControl)) { movement.Y = -velocidadCaminar; moving = true; } //Si hubo desplazamiento if (moving) { //Aplicar movimiento, internamente suma valores a la posicion actual del mesh. mesh.Position = mesh.Position + movement; mesh.Transform = TGCMatrix.Translation(mesh.Position); mesh.updateBoundingBox(); } //Hacer que la camara siga al personaje en su nueva posicion camaraInterna.Target = mesh.Position; //Detectar colision con triangulo if (TgcCollisionUtils.testTriangleAABB(new TGCVector3(triangle[0].Position), new TGCVector3(triangle[1].Position), new TGCVector3(triangle[2].Position), mesh.BoundingBox)) { triangle[0].Color = Color.Red.ToArgb(); triangle[1].Color = Color.Red.ToArgb(); triangle[2].Color = Color.Red.ToArgb(); } else { triangle[0].Color = Color.Green.ToArgb(); triangle[1].Color = Color.Green.ToArgb(); triangle[2].Color = Color.Green.ToArgb(); } //Detectar colision con el otro AABB if (TgcCollisionUtils.testAABBAABB(mesh.BoundingBox, box2.BoundingBox)) { box2.Color = Color.Red; box2.updateValues(); } else { box2.Color = Color.Violet; box2.updateValues(); } //Detectar colision con la esfera if (TgcCollisionUtils.testSphereAABB(boundingSphere, mesh.BoundingBox)) { boundingSphere.setRenderColor(Color.Red); } else { boundingSphere.setRenderColor(Color.Yellow); } //Detectar colision con la obb if (TgcCollisionUtils.testObbAABB(obb, mesh.BoundingBox)) { obb.setRenderColor(Color.Red); } else { obb.setRenderColor(Color.Yellow); } }
public void Render(float time) { character.Transform = TGCMatrix.Scaling(new TGCVector3(0.1f, 0.1f, 0.1f)) * new TGCMatrix(capsuleRigidBody.InterpolationWorldTransform) * TGCMatrix.Translation(0, -20, 0); character.animateAndRender(time); }
public override void Init() { //Crear piso var pisoTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\tierra.jpg"); piso = new TgcPlane(TGCVector3.Empty, new TGCVector3(2000, 0, 2000), TgcPlane.Orientations.XZplane, pisoTexture, 50f, 50f); //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(TGCVector3.Empty, new TGCVector3(wallSize, wallHeight, 10), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\baldosaFacultad.jpg")); obstaculo.Transform = TGCMatrix.Translation(obstaculo.Position); obstaculos.Add(obstaculo); //Obstaculo 2 obstaculo = TGCBox.fromExtremes(TGCVector3.Empty, new TGCVector3(10, wallHeight, wallSize), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\madera.jpg")); obstaculo.Transform = TGCMatrix.Translation(obstaculo.Position); obstaculos.Add(obstaculo); //Obstaculo 3 obstaculo = TGCBox.fromExtremes(new TGCVector3(0, 0, wallSize), new TGCVector3(wallSize, wallHeight, wallSize + 10), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\granito.jpg")); obstaculo.Transform = TGCMatrix.Translation(obstaculo.Position); obstaculos.Add(obstaculo); //Obstaculo 4 obstaculo = TGCBox.fromExtremes(new TGCVector3(wallSize, 0, 0), new TGCVector3(wallSize + 10, wallHeight, wallSize), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\granito.jpg")); obstaculo.Transform = TGCMatrix.Translation(obstaculo.Position); obstaculos.Add(obstaculo); //Obstaculo 5 obstaculo = TGCBox.fromExtremes(new TGCVector3(wallSize / 2, 0, wallSize - 400), new TGCVector3(wallSize + 10, wallHeight, wallSize - 400 + 10), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\granito.jpg")); obstaculo.Transform = TGCMatrix.Translation(obstaculo.Position); 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 TGCVector3(100, 0, 100); personaje.Scale = new TGCVector3(0.75f, 0.75f, 0.75f); //Rotarlo 180° porque esta mirando para el otro lado personaje.Rotation += new TGCVector3(0, Geometry.DegreeToRadian(180f), 0); personaje.Transform = TGCMatrix.RotationY(personaje.Rotation.Y) * TGCMatrix.Translation(personaje.Position); //Configurar camara en Tercera Persona y la asigno al TGC. camaraInterna = new TgcThirdPersonCamera(personaje.Position, 200, -300); Camera = camaraInterna; //Modifiers para modificar propiedades de la camara offsetHeightModifier = AddFloat("offsetHeight", 0, 300, 100); offsetForwardModifier = AddFloat("offsetForward", -400, 0, -220); displacementModifier = AddVertex2f("displacement", TGCVector2.Zero, new TGCVector2(100, 200), new TGCVector2(0, 100)); }
public override void Init() { MyMediaDir = MediaDir; //Crear loader var loader = new TgcSceneLoader(); // ------------------------------------------------------------ // Creo el Heightmap para el terreno: var PosTerrain = TGCVector3.Empty; currentHeightmap = MyMediaDir + "Heighmaps\\Heightmap2.jpg"; currentScaleXZ = 100f; currentScaleY = 2f; currentTexture = MyMediaDir + "Heighmaps\\TerrainTexture3.jpg"; terrain = new TgcSimpleTerrain(); terrain.loadHeightmap(currentHeightmap, currentScaleXZ, currentScaleY, PosTerrain); terrain.loadTexture(currentTexture); // ------------------------------------------------------------ // Crear SkyBox: skyBox = new TgcSkyBox(); skyBox.Center = TGCVector3.Empty; skyBox.Size = new TGCVector3(8000, 8000, 8000); var texturesPath = MediaDir + "Texturas\\Quake\\SkyBox1\\"; skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "phobos_up.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "phobos_dn.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "phobos_lf.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "phobos_rt.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "phobos_bk.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "phobos_ft.jpg"); skyBox.SkyEpsilon = 50f; skyBox.Init(); // ------------------------------------------------------------ //Cargar los mesh: scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\TanqueFuturistaRuedas\\TanqueFuturistaRuedas-TgcScene.xml"); mesh = scene.Meshes[0]; sceneX = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Sphere\\Sphere-TgcScene.xml"); meshX = sceneX.Meshes[0]; scene2 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera\\Palmera-TgcScene.xml"); palmera = scene2.Meshes[0]; scene3 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\AvionCaza\\AvionCaza-TgcScene.xml"); avion = scene3.Meshes[0]; mesh.Scale = new TGCVector3(0.5f, 0.5f, 0.5f); mesh.Position = new TGCVector3(0f, 0f, 0f); var size = mesh.BoundingBox.calculateSize(); largo_tanque = Math.Abs(size.Z); alto_tanque = Math.Abs(size.Y) * mesh.Scale.Y; avion.Scale = new TGCVector3(1f, 1f, 1f); avion.Position = new TGCVector3(3000f, 550f, 0f); dir_avion = new TGCVector3(0, 0, 1); size = palmera.BoundingBox.calculateSize(); var alto_palmera = Math.Abs(size.Y); int i; bosque = new List <TgcMesh>(); float[] r = { 1900f, 2100f, 2300f, 1800f }; for (i = 0; i < 4; i++) { for (var j = 0; j < 15; j++) { var instance = palmera.createMeshInstance(palmera.Name + i); instance.Scale = new TGCVector3(0.5f, 1.5f, 0.5f); var x = r[i] * (float)Math.Cos(Geometry.DegreeToRadian(180 + 10.0f * j)); var z = r[i] * (float)Math.Sin(Geometry.DegreeToRadian(180 + 10.0f * j)); instance.Position = new TGCVector3(x, CalcularAltura(x, z) /*+ alto_palmera / 2 * instance.Scale.Y*/, z); instance.Transform = TGCMatrix.Translation(instance.Position); bosque.Add(instance); } } // Arreglo las normales del tanque /*int[] adj = new int[mesh.D3dMesh.NumberFaces * 3]; * mesh.D3dMesh.GenerateAdjacency(0, adj); * mesh.D3dMesh.ComputeNormals(adj); */ // Arreglo las normales de la esfera { var adj = new int[meshX.D3dMesh.NumberFaces * 3]; meshX.D3dMesh.GenerateAdjacency(0, adj); meshX.D3dMesh.ComputeNormals(adj); } //Cargar Shader personalizado effect = TGCShaders.Instance.LoadEffect(ShadersDir + "WorkshopShaders\\EnvMap.fx"); // le asigno el efecto a la malla mesh.Effect = effect; meshX.Effect = effect; vel_tanque = 10; //Centrar camara rotacional respecto a este mesh CamaraRot = new TgcRotationalCamera(mesh.BoundingBox.calculateBoxCenter(), mesh.BoundingBox.calculateBoxRadius() * 2, Input); CamaraRot.CameraDistance = 300; CamaraRot.RotationSpeed = 1.5f; Camara = CamaraRot; kx = kc = 0.5f; reflexionModifier = AddFloat("Reflexion", 0, 1, kx); refraccionModifier = AddFloat("Refraccion", 0, 1, kc); fresnelModifier = AddBoolean("Fresnel", "fresnel", true); }
public void MoverPersonaje(char key, float elapsedTime, TgcD3dInput input, Escenario escenario, Monster monster) { MovementSpeed = 800.0f; var movimiento = TGCVector3.Empty; var posicionOriginal = this.Position; var moving = false; var estoyFlotando = false; if (key == key_forward) { movimiento.Z = -1; moving = true; } if (key == key_left) { movimiento.X = 1; moving = true; } if (key == key_back) { movimiento.Z = 1; moving = true; } if (key == key_right) { movimiento.X = -1; moving = true; } if (key == ' ') { movimiento.Y = 1; moving = true; } if (moving) { this.posicionAnterior = this.Position; var lastPos = meshPersonaje.Position; movimiento *= MovementSpeed * elapsedTime; meshPersonaje.Position = meshPersonaje.Position + movimiento; meshPersonaje.updateBoundingBox(); //COLISIONES bool chocaron = escenario.tgcScene.Meshes.Any(mesh => TgcCollisionUtils.testAABBAABB(mesh.BoundingBox, meshPersonaje.BoundingBox)); if (chocaron) { meshPersonaje.Position = lastPos; } bool chocoConMonster = TgcCollisionUtils.testAABBAABB(monster.ghost.BoundingBox, meshPersonaje.BoundingBox); if (chocoConMonster) { meshPersonaje.Position = lastPos; } meshPersonaje.Transform = TGCMatrix.Scaling(meshPersonaje.Scale) * TGCMatrix.RotationYawPitchRoll(meshPersonaje.Rotation.Y, meshPersonaje.Rotation.X, meshPersonaje.Rotation.Z) * TGCMatrix.Translation(meshPersonaje.Position); this.Position = meshPersonaje.Position; //Hacer que la camara siga al personaje en su nueva posicion //camaraInterna.Target = this.Position; } float rotY = input.XposRelative * rotationSpeed; float rotX = input.YposRelative * rotationSpeed; eye = this.Position; target += movimiento; if (lockMouse) { if (rotY != 0.0f || rotX != 0.0f) { look(rotX, rotY); } Cursor.Position = windowCenter; } this.SetCamera(eye, target); }
public override void Render() { PreRender(); //Habilitar luz var lightEnable = lightEnableModifier.Value; Effect currentShader; string currentTechnique; if (lightEnable) { //Shader personalizado de iluminacion currentShader = effect; currentTechnique = "MultiDiffuseLightsTechnique"; } else { //Sin luz: Restaurar shader default currentShader = TGCShaders.Instance.TgcMeshShader; currentTechnique = TGCShaders.Instance.GetTGCMeshTechnique(TgcMesh.MeshRenderType.DIFFUSE_MAP); } //Aplicar a cada mesh el shader actual foreach (var mesh in scene.Meshes) { mesh.Effect = currentShader; mesh.Technique = currentTechnique; } //Configurar los valores de cada luz var move = new TGCVector3(0, 0, lightMoveModifier.Value ? interp.update(ElapsedTime) : 0); var lightColors = new ColorValue[lightMeshes.Length]; var pointLightPositions = new Vector4[lightMeshes.Length]; var pointLightIntensity = new float[lightMeshes.Length]; var pointLightAttenuation = new float[lightMeshes.Length]; for (var i = 0; i < lightMeshes.Length; i++) { var lightMesh = lightMeshes[i]; lightMesh.Position = origLightPos[i] + TGCVector3.Scale(move, i + 1); lightMesh.Transform = TGCMatrix.Translation(lightMesh.Position); lightColors[i] = ColorValue.FromColor(lightMesh.Color); pointLightPositions[i] = TGCVector3.Vector3ToVector4(lightMesh.Position); pointLightIntensity[i] = lightIntensityModifier.Value; pointLightAttenuation[i] = lightAttenuationModifier.Value; } //Renderizar meshes foreach (var mesh in scene.Meshes) { mesh.UpdateMeshTransform(); if (lightEnable) { //Cargar variables de shader 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(mEmissiveModifier.Value)); mesh.Effect.SetValue("materialDiffuseColor", ColorValue.FromColor(mDiffuseModifier.Value)); } //Renderizar modelo mesh.Render(); } //Renderizar meshes de luz for (var i = 0; i < lightMeshes.Length; i++) { var lightMesh = lightMeshes[i]; lightMesh.Render(); } PostRender(); }
private void ChangeFishWay() { TGCMatrix Rotation = TGCMatrix.RotationY(-RotationYSign() * FastMath.PI_HALF); director.TransformCoordinate(Rotation); TotalRotation *= Rotation; Mesh.Mesh.Transform = TGCMatrix.Scaling(Constants.Scale) * TotalRotation * TGCMatrix.Translation(GetMeshPosition()); time = Constants.ScapeFromPlayerCooldown; }
public override void Init() { //Crear loader var loader = new TgcSceneLoader(); //Cargar mesh scene = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Teapot\\Teapot-TgcScene.xml"); mesh = scene.Meshes[0]; mesh.Scale = new TGCVector3(1f, 1f, 1f); mesh.Position = new TGCVector3(-100f, -5f, 0f); // Arreglo las normales var adj = new int[mesh.D3dMesh.NumberFaces * 3]; mesh.D3dMesh.GenerateAdjacency(0, adj); mesh.D3dMesh.ComputeNormals(adj); //Cargar Shader personalizado effect = TGCShaders.Instance.LoadEffect(ShadersDir + "WorkshopShaders\\ToonShading.fx"); // le asigno el efecto a la malla mesh.Effect = effect; mesh.Technique = "DefaultTechnique"; // Creo las instancias de malla instances = new List <TgcMesh>(); for (var i = -5; i < 5; i++) { for (var j = -5; j < 5; j++) { var instance = mesh.createMeshInstance(mesh.Name + i); instance.Position = new TGCVector3(i * 50, (i + j) * 5, j * 50); instance.Transform = TGCMatrix.Scaling(instance.Scale) * TGCMatrix.RotationYawPitchRoll(instance.Rotation.X, instance.Rotation.Y, instance.Rotation.Z) * TGCMatrix.Translation(instance.Position); instances.Add(instance); } } blurActivatedModifier = AddBoolean("blurActivated", "activar blur", false); lightPositionModifier = AddVertex3f("LightPosition", new TGCVector3(-100, -100, -100), new TGCVector3(100, 100, 100), new TGCVector3(0, 40, 0)); ambientModifier = AddFloat("Ambient", 0, 1, 0.5f); diffuseModifier = AddFloat("Diffuse", 0, 1, 0.6f); specularModifier = AddFloat("Specular", 0, 1, 0.5f); specularPowerModifier = AddFloat("SpecularPower", 1, 100, 16); Camara = new TgcRotationalCamera(new TGCVector3(20, 20, 0), 300, TgcRotationalCamera.DEFAULT_ZOOM_FACTOR, 1.5f, Input); // Creo un depthbuffer sin multisampling, para que sea compatible con el render to texture // Nota: // El render to Texture no es compatible con el multisampling en dx9 // Por otra parte la mayor parte de las placas de ultima generacion no soportan // mutisampling para texturas de punto flotante con lo cual // hay que suponer con generalidad que no se puede usar multisampling y render to texture // Para resolverlo hay que crear un depth buffer que no tenga multisampling, // (de lo contrario falla el zbuffer y se producen artifacts tipicos de que no tiene zbuffer) // Si uno quisiera usar el multisampling, la tecnica habitual es usar un RenderTarget // en lugar de una textura. // Por ejemplo en c++: // // Render Target formato color buffer con multisampling // // g_pd3dDevice->CreateRenderTarget(Ancho,Alto, // D3DFMT_A8R8G8B8, D3DMULTISAMPLE_2_SAMPLES, 0, // FALSE, &g_pRenderTarget, NULL); // // Luego, ese RenderTarget NO ES una textura, y nosotros necesitamos acceder a esos // pixeles, ahi lo que se hace es COPIAR del rendertartet a una textura, // para poder trabajar con esos datos en el contexto del Pixel shader: // // Eso se hace con la funcion StretchRect: // copia de rendertarget ---> sceneSurface (que es la superficie asociada a una textura) // g_pd3dDevice->StretchRect(g_pRenderTarget, NULL, g_pSceneSurface, NULL, D3DTEXF_NONE); // // Esta tecnica se llama downsampling // Y tiene el costo adicional de la transferencia de memoria entre el rendertarget y la // textura, pero que no traspasa los limites de la GPU. (es decir es muy performante) // no es lo mismo que lockear una textura para acceder desde la CPU, que tiene el problema // de transferencia via AGP. g_pDepthStencil = D3DDevice.Instance.Device.CreateDepthStencilSurface(D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth, D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true); // inicializo el render target g_pRenderTarget = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth, D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); effect.SetValue("g_RenderTarget", g_pRenderTarget); // inicializo el mapa de normales g_pNormals = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth, D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default); effect.SetValue("g_Normals", g_pNormals); // Resolucion de pantalla effect.SetValue("screen_dx", D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth); effect.SetValue("screen_dy", D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight); //Se crean 2 triangulos con las dimensiones de la pantalla con sus posiciones ya transformadas // x = -1 es el extremo izquiedo de la pantalla, x=1 es el extremo derecho // Lo mismo para la Y con arriba y abajo // la Z en 1 simpre CustomVertex.PositionTextured[] vertices = { new CustomVertex.PositionTextured(-1, 1, 1, 0, 0), new CustomVertex.PositionTextured(1, 1, 1, 1, 0), new CustomVertex.PositionTextured(-1, -1, 1, 0, 1), new CustomVertex.PositionTextured(1, -1, 1, 1, 1) }; //vertex buffer de los triangulos g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, D3DDevice.Instance.Device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); g_pVBV3D.SetData(vertices, 0, LockFlags.None); }