diff --git a/TGC.Core/BoundingVolumes/TgcBoundingAxisAlignBox.cs b/TGC.Core/BoundingVolumes/TgcBoundingAxisAlignBox.cs index e59375c0..0fa2e7c1 100644 --- a/TGC.Core/BoundingVolumes/TgcBoundingAxisAlignBox.cs +++ b/TGC.Core/BoundingVolumes/TgcBoundingAxisAlignBox.cs @@ -37,7 +37,7 @@ public TgcBoundingAxisAlignBox() { RenderColor = Color.Yellow.ToArgb(); dirtyValues = true; - AlphaBlendEnable = false; + AlphaBlend = false; } /// @@ -127,7 +127,7 @@ public TGCVector3 Position /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// Renderizar BoundingBox diff --git a/TGC.Core/BoundingVolumes/TgcBoundingCylinder.cs b/TGC.Core/BoundingVolumes/TgcBoundingCylinder.cs index 71ed36b5..90fa2743 100644 --- a/TGC.Core/BoundingVolumes/TgcBoundingCylinder.cs +++ b/TGC.Core/BoundingVolumes/TgcBoundingCylinder.cs @@ -183,7 +183,7 @@ public void Dispose() vertices = null; } - public bool AlphaBlendEnable { get; set; } //useless? + public bool AlphaBlend { get; set; } //useless? #endregion Rendering diff --git a/TGC.Core/BoundingVolumes/TgcBoundingCylinderFixedY.cs b/TGC.Core/BoundingVolumes/TgcBoundingCylinderFixedY.cs index 61bae75d..3b127ded 100644 --- a/TGC.Core/BoundingVolumes/TgcBoundingCylinderFixedY.cs +++ b/TGC.Core/BoundingVolumes/TgcBoundingCylinderFixedY.cs @@ -163,7 +163,7 @@ public void Dispose() vertices = null; } - public bool AlphaBlendEnable { get; set; } //useless? + public bool AlphaBlend { get; set; } //useless? #endregion Rendering } diff --git a/TGC.Core/BoundingVolumes/TgcBoundingElipsoid.cs b/TGC.Core/BoundingVolumes/TgcBoundingElipsoid.cs index 42bb8b97..3f7dcfb1 100644 --- a/TGC.Core/BoundingVolumes/TgcBoundingElipsoid.cs +++ b/TGC.Core/BoundingVolumes/TgcBoundingElipsoid.cs @@ -32,7 +32,7 @@ public TgcBoundingElipsoid() { RenderColor = Color.Yellow.ToArgb(); dirtyValues = true; - AlphaBlendEnable = false; + AlphaBlend = false; } /// @@ -90,7 +90,7 @@ public TGCVector3 Position /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// Renderizar el Elipsoid diff --git a/TGC.Core/BoundingVolumes/TgcBoundingOrientedBox.cs b/TGC.Core/BoundingVolumes/TgcBoundingOrientedBox.cs index 44152c9c..63524b0a 100644 --- a/TGC.Core/BoundingVolumes/TgcBoundingOrientedBox.cs +++ b/TGC.Core/BoundingVolumes/TgcBoundingOrientedBox.cs @@ -32,7 +32,7 @@ public TgcBoundingOrientedBox() { RenderColor = Color.Yellow.ToArgb(); dirtyValues = true; - AlphaBlendEnable = false; + AlphaBlend = false; } /// @@ -105,7 +105,7 @@ public string Technique /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// Renderizar diff --git a/TGC.Core/BoundingVolumes/TgcBoundingSphere.cs b/TGC.Core/BoundingVolumes/TgcBoundingSphere.cs index c51e329a..071e2d92 100644 --- a/TGC.Core/BoundingVolumes/TgcBoundingSphere.cs +++ b/TGC.Core/BoundingVolumes/TgcBoundingSphere.cs @@ -33,7 +33,7 @@ public TgcBoundingSphere() { RenderColor = Color.Yellow.ToArgb(); dirtyValues = true; - AlphaBlendEnable = false; + AlphaBlend = false; } /// @@ -90,7 +90,7 @@ public TGCVector3 Position /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// Renderizar el BoundingSphere diff --git a/TGC.Core/Geometry/TGCGeometry.cs b/TGC.Core/Geometry/TGCGeometry.cs index c87623fe..6efa5b4c 100644 --- a/TGC.Core/Geometry/TGCGeometry.cs +++ b/TGC.Core/Geometry/TGCGeometry.cs @@ -1,8 +1,12 @@ using TGC.Core.Mathematica; +using TGC.Core.SceneLoader; namespace TGC.Core { - public abstract class TGCGeometry + /// + /// Abstraccion con el comportamiento y estado interno comun de las geometrias. + /// + public abstract class TGCGeometry : IRenderObject { /// /// Habilita el renderizado con AlphaBlending para los modelos @@ -16,10 +20,21 @@ public abstract class TGCGeometry /// public TGCVector3 Position { get; set; } + /// + /// Direccion hacia arriba + /// public TGCVector3 Up { get; set; } + /// + /// Direccion hacia la derecha. + /// public TGCVector3 Right { get; set; } + /// + /// Direccion hacia el frente. + /// + public TGCVector3 Front { get; set; } + /// /// Rotación absoluta del objeto /// @@ -38,6 +53,14 @@ public abstract class TGCGeometry /// public TGCMatrix Transform { get; set; } + /// + /// Iinicializacion del objeto. + /// + public abstract void Init(); + + /// + /// Se debe escribir toda la lógica de computo del modelo. + /// public abstract void Update(); /// diff --git a/TGC.Core/Geometry/TGCSphere.cs b/TGC.Core/Geometry/TGCSphere.cs index 9308c36a..a5dcc6b6 100644 --- a/TGC.Core/Geometry/TGCSphere.cs +++ b/TGC.Core/Geometry/TGCSphere.cs @@ -144,7 +144,7 @@ public Color Color /// En False se respeta lo que el usuario haya cargado a mano en la matriz. /// Por default está en False. /// - public bool AutoTransformEnable { get; set; } + public bool AutoTransform { get; set; } /// /// Posicion absoluta del centro de la esfera @@ -186,7 +186,7 @@ public TgcBoundingSphere BoundingSphere /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// Offset UV de textura @@ -339,13 +339,13 @@ public TGCSphere(float radius, TgcTexture texture, TGCVector3 center) protected void configure(float radius, Color color, TgcTexture texture, TGCVector3 center) { - AutoTransformEnable = false; + AutoTransform = false; Transform = TGCMatrix.Identity; translation = center; Rotation = TGCVector3.Empty; Enabled = true; scale = TGCVector3.One; - AlphaBlendEnable = false; + AlphaBlend = false; uvOffset = TGCVector2.Zero; //BoundingSphere @@ -633,7 +633,7 @@ public virtual void Render() return; //transformacion - if (AutoTransformEnable) + if (AutoTransform) { Transform = TGCMatrix.Scaling(radius, radius, radius) * TGCMatrix.Scaling(Scale) * TGCMatrix.RotationYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) * @@ -693,7 +693,7 @@ protected void renderWithFill(FillMode fillmode) /// protected void activateAlphaBlend() { - if (AlphaBlendEnable) + if (AlphaBlend) { D3DDevice.Instance.Device.RenderState.AlphaTestEnable = true; D3DDevice.Instance.Device.RenderState.AlphaBlendEnable = true; @@ -822,10 +822,10 @@ public virtual TGCSphere clone() if (Texture != null) cloneSphere.setTexture(Texture.Clone()); - cloneSphere.AutoTransformEnable = AutoTransformEnable; + cloneSphere.AutoTransform = AutoTransform; cloneSphere.Transform = Transform; cloneSphere.Rotation = Rotation; - cloneSphere.AlphaBlendEnable = AlphaBlendEnable; + cloneSphere.AlphaBlend = AlphaBlend; cloneSphere.uvOffset = uvOffset; cloneSphere.updateValues(); @@ -840,14 +840,14 @@ public virtual TGCSphere clone() public TgcMesh toMesh(string meshName) { //Obtener matriz para transformar vertices - if (AutoTransformEnable) + if (AutoTransform) { Transform = TGCMatrix.Scaling(radius, radius, radius) * TGCMatrix.Scaling(Scale) * TGCMatrix.RotationYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) * TGCMatrix.Translation(translation); } - return TgcMesh.FromTGCSphere(meshName, Texture, indices, vertices, Transform, AlphaBlendEnable); + return TgcMesh.FromTGCSphere(meshName, Texture, indices, vertices, Transform, AlphaBlend); } /// http://gamedev.stackexchange.com/questions/31308/algorithm-for-creating-spheres David Lively diff --git a/TGC.Core/Geometry/TgcBox.cs b/TGC.Core/Geometry/TgcBox.cs index 22a264c8..27a8e2af 100644 --- a/TGC.Core/Geometry/TgcBox.cs +++ b/TGC.Core/Geometry/TgcBox.cs @@ -35,13 +35,13 @@ public TGCBox() D3DDevice.Instance.Device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColoredTextured.Format, Pool.Default); - AutoTransformEnable = false; + AutoTransform = false; Transform = TGCMatrix.Identity; translation = TGCVector3.Empty; rotation = TGCVector3.Empty; Enabled = true; Color = Color.White; - AlphaBlendEnable = false; + AlphaBlend = false; UVOffset = TGCVector2.Zero; UVTiling = TGCVector2.One; @@ -58,7 +58,7 @@ public TGCBox() /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// En True hace que la matriz de transformacion (Transform) de la malla se actualiza en @@ -66,7 +66,7 @@ public TGCBox() /// En False se respeta lo que el usuario haya cargado a mano en la matriz. /// Por default está en False. /// - public bool AutoTransformEnable { get; set; } + public bool AutoTransform { get; set; } /// /// BoundingBox de la caja @@ -183,7 +183,7 @@ public void Render() return; //transformacion - if (AutoTransformEnable) + if (AutoTransform) { Transform = TGCMatrix.RotationYawPitchRoll(rotation.Y, rotation.X, rotation.Z) * TGCMatrix.Translation(translation); @@ -390,7 +390,7 @@ public void setTexture(TgcTexture texture) /// protected void activateAlphaBlend() { - if (AlphaBlendEnable) + if (AlphaBlend) { D3DDevice.Instance.Device.RenderState.AlphaTestEnable = true; D3DDevice.Instance.Device.RenderState.AlphaBlendEnable = true; @@ -448,12 +448,12 @@ private void updateBoundingBox() public TgcMesh ToMesh(string meshName) { //Obtener matriz para transformar vertices - if (AutoTransformEnable) + 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); + return TgcMesh.FromTGCBox(meshName, this.Texture, this.vertices, this.Transform, this.AlphaBlend); } /// @@ -469,10 +469,10 @@ public TGCBox clone() { cloneBox.setTexture(Texture.Clone()); } - cloneBox.AutoTransformEnable = AutoTransformEnable; + cloneBox.AutoTransform = AutoTransform; cloneBox.Transform = Transform; cloneBox.rotation = rotation; - cloneBox.AlphaBlendEnable = AlphaBlendEnable; + cloneBox.AlphaBlend = AlphaBlend; cloneBox.UVOffset = UVOffset; cloneBox.UVTiling = UVTiling; diff --git a/TGC.Core/Geometry/TgcBoxDebug.cs b/TGC.Core/Geometry/TgcBoxDebug.cs index 81d0db03..00f766a1 100644 --- a/TGC.Core/Geometry/TgcBoxDebug.cs +++ b/TGC.Core/Geometry/TgcBoxDebug.cs @@ -39,7 +39,7 @@ public TgcBoxDebug() Thickness = 1f; Enabled = true; color = Color.White; - AlphaBlendEnable = false; + AlphaBlend = false; //Shader effect = TgcShaders.Instance.VariosShader; @@ -105,7 +105,7 @@ public string Technique /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// Renderizar la caja diff --git a/TGC.Core/Geometry/TgcConvexPolygon.cs b/TGC.Core/Geometry/TgcConvexPolygon.cs index 8a7317e6..9c74bb61 100644 --- a/TGC.Core/Geometry/TgcConvexPolygon.cs +++ b/TGC.Core/Geometry/TgcConvexPolygon.cs @@ -17,7 +17,7 @@ public class TgcConvexPolygon : IRenderObject public TgcConvexPolygon() { Enabled = true; - AlphaBlendEnable = false; + AlphaBlend = false; color = Color.Purple; } @@ -145,7 +145,7 @@ public Color Color /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } # endregion } diff --git a/TGC.Core/Geometry/TgcCylinder.cs b/TGC.Core/Geometry/TgcCylinder.cs index d7712115..67db6d34 100644 --- a/TGC.Core/Geometry/TgcCylinder.cs +++ b/TGC.Core/Geometry/TgcCylinder.cs @@ -30,7 +30,7 @@ public TgcCylinder(TGCVector3 _center, float _topRadius, float _bottomRadius, fl color = Color.Red.ToArgb(); manualTransformation = TGCMatrix.Identity; - AutoTransformEnable = false; + AutoTransform = false; initialize(); } @@ -120,7 +120,7 @@ public TGCVector3 Center public void Render() { - if (AlphaBlendEnable) + if (AlphaBlend) { D3DDevice.Instance.Device.RenderState.AlphaBlendEnable = true; D3DDevice.Instance.Device.RenderState.AlphaTestEnable = true; @@ -156,7 +156,7 @@ public void Dispose() BoundingCylinder.Dispose(); } - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } private void initialize() { @@ -253,13 +253,13 @@ public void updateValues() #region Transformation - public bool AutoTransformEnable { get; set; } + public bool AutoTransform { get; set; } public TGCMatrix Transform { get { - if (AutoTransformEnable) return BoundingCylinder.Transform; + if (AutoTransform) return BoundingCylinder.Transform; return manualTransformation; } set { manualTransformation = value; } diff --git a/TGC.Core/Geometry/TgcLine.cs b/TGC.Core/Geometry/TgcLine.cs index 5ffe2bd1..c4ad3e76 100644 --- a/TGC.Core/Geometry/TgcLine.cs +++ b/TGC.Core/Geometry/TgcLine.cs @@ -25,7 +25,7 @@ public TgcLine() vertices = new CustomVertex.PositionColored[2]; color = Color.White; Enabled = true; - AlphaBlendEnable = false; + AlphaBlend = false; //Shader effect = TgcShaders.Instance.VariosShader; @@ -86,7 +86,7 @@ public string Technique /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// Renderizar la línea diff --git a/TGC.Core/Geometry/TgcPlane.cs b/TGC.Core/Geometry/TgcPlane.cs index 0cb6760e..8cb1cdca 100644 --- a/TGC.Core/Geometry/TgcPlane.cs +++ b/TGC.Core/Geometry/TgcPlane.cs @@ -35,9 +35,6 @@ public enum Orientations } private readonly CustomVertex.PositionTextured[] vertices; - private TGCVector3 origin; - private TGCVector3 size; - private TGCVector2 uvOffset; /// /// Crea una pared vacia. @@ -50,7 +47,7 @@ public TgcPlane() BoundingBox = new TgcBoundingAxisAlignBox(); UTile = 1; VTile = 1; - AlphaBlendEnable = false; + AlphaBlend = false; UVOffset = TGCVector2.Zero; //Shader @@ -68,8 +65,7 @@ public TgcPlane() /// Textura de la pared /// Cantidad de tile de la textura en coordenada U /// Cantidad de tile de la textura en coordenada V - public TgcPlane(TGCVector3 origin, TGCVector3 size, Orientations orientation, TgcTexture texture, float uTile, - float vTile) + public TgcPlane(TGCVector3 origin, TGCVector3 size, Orientations orientation, TgcTexture texture, float uTile, float vTile) : this() { setTexture(texture); @@ -111,20 +107,12 @@ public TgcPlane(TGCVector3 origin, TGCVector3 size, Orientations orientation, Tg /// Origen de coordenadas de la pared. /// Llamar a updateValues() para aplicar cambios. /// - public TGCVector3 Origin - { - get { return origin; } - set { origin = value; } - } + public TGCVector3 Origin { get; set; } /// /// Dimensiones de la pared. /// - public TGCVector3 Size - { - get { return size; } - set { size = value; } - } + public TGCVector3 Size { get; set; } /// /// Orientación de la pared. @@ -169,11 +157,7 @@ public TGCVector3 Size /// /// Offset UV de textura /// - public TGCVector2 UVOffset - { - get { return uvOffset; } - set { uvOffset = value; } - } + public TGCVector2 UVOffset { get; set; } /// /// Indica si la pared esta habilitada para ser renderizada @@ -195,7 +179,12 @@ public TGCVector3 Position /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } + + /// + /// La normal del plano. si no se setea se autocalcula + /// + public TGCVector3? Normal { get; set; } = null; /// /// Renderizar la pared @@ -337,7 +326,7 @@ public void setTexture(TgcTexture texture) /// protected void activateAlphaBlend() { - if (AlphaBlendEnable) + if (AlphaBlend) { D3DDevice.Instance.Device.RenderState.AlphaTestEnable = true; D3DDevice.Instance.Device.RenderState.AlphaBlendEnable = true; @@ -359,7 +348,7 @@ protected void resetAlphaBlend() /// Nombre de la malla que se va a crear public TgcMesh toMesh(string meshName) { - return TgcMesh.FromTGCPlane(meshName, this.vertices, this.Texture); + return TgcMesh.FromTGCPlane(meshName, this.vertices, this.Texture, this.Normal); } /// @@ -375,7 +364,7 @@ public TgcPlane clone() clonePlane.AutoAdjustUv = AutoAdjustUv; clonePlane.UTile = UTile; clonePlane.VTile = VTile; - clonePlane.AlphaBlendEnable = AlphaBlendEnable; + clonePlane.AlphaBlend = AlphaBlend; clonePlane.UVOffset = UVOffset; clonePlane.setTexture(Texture.Clone()); diff --git a/TGC.Core/Geometry/TgcQuad.cs b/TGC.Core/Geometry/TgcQuad.cs index c52ac35e..645bda04 100644 --- a/TGC.Core/Geometry/TgcQuad.cs +++ b/TGC.Core/Geometry/TgcQuad.cs @@ -12,37 +12,12 @@ namespace TGC.Core.Geometry /// Herramienta para crear un Quad 3D, o un plano con ancho y largo acotado, /// en base al centro y una normal. /// - public class TgcQuad : IRenderObject + public class TGCQuad : IRenderObject { private readonly TGCVector3 ORIGINAL_DIR = TGCVector3.Up; private readonly VertexBuffer vertexBuffer; - private Color color; - - protected Effect effect; - - private TGCVector3 normal; - - protected string technique; - - public TgcQuad() - { - vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 6, D3DDevice.Instance.Device, - Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); - - Center = TGCVector3.Empty; - normal = TGCVector3.Up; - Size = new TGCVector2(10, 10); - Enabled = true; - color = Color.Blue; - AlphaBlendEnable = false; - - //Shader - effect = TgcShaders.Instance.VariosShader; - technique = TgcShaders.T_POSITION_COLORED; - } - /// /// Centro del plano /// @@ -51,11 +26,7 @@ public TgcQuad() /// /// Normal del plano /// - public TGCVector3 Normal - { - get { return normal; } - set { normal = value; } - } + public TGCVector3 Normal { get; set; } /// /// Tamaño del plano, en ancho y longitud @@ -65,11 +36,7 @@ public TGCVector3 Normal /// /// Color del plano /// - public Color Color - { - get { return color; } - set { color = value; } - } + public Color Color { get; set; } /// /// Indica si el plano habilitado para ser renderizado @@ -84,28 +51,37 @@ public TGCVector3 Position /// /// Shader del mesh /// - public Effect Effect - { - get { return effect; } - set { effect = value; } - } + public Effect Effect { get; set; } /// /// Technique que se va a utilizar en el effect. /// Cada vez que se llama a Render() se carga este Technique (pisando lo que el shader ya tenia seteado) /// - public string Technique - { - get { return technique; } - set { technique = value; } - } + public string Technique { get; set; } /// /// Habilita el renderizado con AlphaBlending para los modelos /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } + + public TGCQuad() + { + vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 6, D3DDevice.Instance.Device, + Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); + + Center = TGCVector3.Empty; + Normal = TGCVector3.Up; + Size = new TGCVector2(10, 10); + Enabled = true; + Color = Color.Blue; + AlphaBlend = false; + + //Shader + Effect = TgcShaders.Instance.VariosShader; + Technique = TgcShaders.T_POSITION_COLORED; + } /// /// Renderizar el Quad @@ -118,17 +94,17 @@ public void Render() TexturesManager.Instance.clear(0); TexturesManager.Instance.clear(1); - TgcShaders.Instance.setShaderMatrixIdentity(effect); + TgcShaders.Instance.setShaderMatrixIdentity(Effect); D3DDevice.Instance.Device.VertexDeclaration = TgcShaders.Instance.VdecPositionColored; - effect.Technique = technique; + Effect.Technique = Technique; D3DDevice.Instance.Device.SetStreamSource(0, vertexBuffer, 0); //Render con shader - effect.Begin(0); - effect.BeginPass(0); + Effect.Begin(0); + Effect.BeginPass(0); D3DDevice.Instance.Device.DrawPrimitives(PrimitiveType.TriangleList, 0, 2); - effect.EndPass(); - effect.End(); + Effect.EndPass(); + Effect.End(); } /// @@ -152,7 +128,7 @@ public void updateValues() //Crear un Quad con dos triángulos sobre XZ con normal default (0, 1, 0) var min = new TGCVector3(-Size.X / 2, 0, -Size.Y / 2); var max = new TGCVector3(Size.X / 2, 0, Size.Y / 2); - var c = color.ToArgb(); + var c = Color.ToArgb(); vertices[0] = new CustomVertex.PositionColored(min, c); vertices[1] = new CustomVertex.PositionColored(min.X, 0, max.Z, c); @@ -163,9 +139,9 @@ public void updateValues() vertices[5] = new CustomVertex.PositionColored(max.X, 0, min.Z, c); //Obtener matriz de rotacion respecto de la normal del plano - normal.Normalize(); - var angle = FastMath.Acos(TGCVector3.Dot(ORIGINAL_DIR, normal)); - var axisRotation = TGCVector3.Cross(ORIGINAL_DIR, normal); + Normal.Normalize(); + var angle = FastMath.Acos(TGCVector3.Dot(ORIGINAL_DIR, Normal)); + var axisRotation = TGCVector3.Cross(ORIGINAL_DIR, Normal); axisRotation.Normalize(); var t = TGCMatrix.RotationAxis(axisRotation, angle) * TGCMatrix.Translation(Center); diff --git a/TGC.Core/Geometry/TgcTriangle.cs b/TGC.Core/Geometry/TgcTriangle.cs index 36d89b65..3076701c 100644 --- a/TGC.Core/Geometry/TgcTriangle.cs +++ b/TGC.Core/Geometry/TgcTriangle.cs @@ -32,7 +32,7 @@ public TgcTriangle() C = TGCVector3.Empty; Enabled = true; color = Color.Blue; - AlphaBlendEnable = false; + AlphaBlend = false; //Shader effect = TgcShaders.Instance.VariosShader; @@ -98,7 +98,7 @@ public string Technique /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// Renderizar el Triángulo diff --git a/TGC.Core/KeyFrameLoader/TgcKeyFrameMesh.cs b/TGC.Core/KeyFrameLoader/TgcKeyFrameMesh.cs index 84d18641..7e7a2302 100644 --- a/TGC.Core/KeyFrameLoader/TgcKeyFrameMesh.cs +++ b/TGC.Core/KeyFrameLoader/TgcKeyFrameMesh.cs @@ -246,7 +246,7 @@ public int NumberVertices /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// Renderiza la malla, si esta habilitada. @@ -383,7 +383,7 @@ public void Dispose() /// En False se respeta lo que el usuario haya cargado a mano en la matriz. /// Por default está en False. /// - public bool AutoTransformEnable { get; set; } + public bool AutoTransform { get; set; } /// /// Posicion absoluta de la Malla @@ -504,12 +504,12 @@ private void initData(Mesh mesh, string name, MeshRenderType renderType, Origina Enabled = false; AutoUpdateBoundingBox = true; MeshInstances = new List(); - AlphaBlendEnable = false; + AlphaBlend = false; VertexDeclaration = new VertexDeclaration(mesh.Device, mesh.Declaration); //variables de movimiento - AutoTransformEnable = false; + AutoTransform = false; translation = new TGCVector3(0f, 0f, 0f); rotation = new TGCVector3(0f, 0f, 0f); scale = new TGCVector3(1f, 1f, 1f); @@ -796,7 +796,7 @@ protected void setShaderMatrix() protected void updateMeshTransform() { //Aplicar transformacion de malla - if (AutoTransformEnable) + if (AutoTransform) { Transform = TGCMatrix.Identity * TGCMatrix.Scaling(scale) @@ -810,7 +810,7 @@ protected void updateMeshTransform() /// protected void activateAlphaBlend() { - if (AlphaBlendEnable) + if (AlphaBlend) { D3DDevice.Instance.Device.RenderState.AlphaTestEnable = true; D3DDevice.Instance.Device.RenderState.AlphaBlendEnable = true; diff --git a/TGC.Core/SceneLoader/IRenderObject.cs b/TGC.Core/SceneLoader/IRenderObject.cs index 91dab541..b5722cab 100644 --- a/TGC.Core/SceneLoader/IRenderObject.cs +++ b/TGC.Core/SceneLoader/IRenderObject.cs @@ -10,15 +10,20 @@ public interface IRenderObject /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - bool AlphaBlendEnable { get; set; } + bool AlphaBlend { get; set; } /// - /// Renderiza el objeto + /// Iinicializacion del objeto. + /// + //void Init(); + + /// + /// Renderiza el objeto. /// void Render(); /// - /// Libera los recursos del objeto + /// Libera los recursos del objeto. /// void Dispose(); } diff --git a/TGC.Core/SceneLoader/ITransformObject.cs b/TGC.Core/SceneLoader/ITransformObject.cs index e6c2b93d..0c0856d1 100644 --- a/TGC.Core/SceneLoader/ITransformObject.cs +++ b/TGC.Core/SceneLoader/ITransformObject.cs @@ -21,7 +21,7 @@ public interface ITransformObject /// En False se respeta lo que el usuario haya cargado a mano en la matriz. /// Por default está en True. /// - bool AutoTransformEnable { get; set; } + bool AutoTransform { get; set; } /// /// Posicion absoluta del objeto diff --git a/TGC.Core/SceneLoader/TgcMesh.cs b/TGC.Core/SceneLoader/TgcMesh.cs index 3342e705..c3c938b7 100644 --- a/TGC.Core/SceneLoader/TgcMesh.cs +++ b/TGC.Core/SceneLoader/TgcMesh.cs @@ -286,7 +286,7 @@ public int NumberVertices /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable + public bool AlphaBlend { get { return alphaBlendEnable; } set { alphaBlendEnable = value; } @@ -466,7 +466,7 @@ public TGCMatrix Transform /// En False se respeta lo que el usuario haya cargado a mano en la matriz. /// Por default está en True. /// - public bool AutoTransformEnable + public bool AutoTransform { get { return autoTransformEnable; } set { autoTransformEnable = value; } @@ -592,7 +592,7 @@ protected void initData(Mesh mesh, string name, MeshRenderType renderType) meshInstances = new List(); alphaBlendEnable = false; - AutoTransformEnable = false; + AutoTransform = false; AutoUpdateBoundingBox = true; translation = new TGCVector3(0f, 0f, 0f); rotation = new TGCVector3(0f, 0f, 0f); @@ -1171,7 +1171,7 @@ public static TgcMesh ToDiffuseMapMesh(string meshName, CustomVertex.PositionCol tgcMesh.Materials = new[] { D3DDevice.DEFAULT_MATERIAL }; tgcMesh.createBoundingBox(); tgcMesh.Enabled = true; - tgcMesh.AlphaBlendEnable = alphaBlendEnable; + tgcMesh.AlphaBlend = alphaBlendEnable; return tgcMesh; } @@ -1280,12 +1280,12 @@ public static TgcMesh FromTGCSphere(string meshName, TgcTexture texture, List sceneMeshes) meshExport.MeshData.pMin = TGCVector3.Vector3ToFloat3Array(tgcMesh.BoundingBox.PMin); meshExport.MeshData.pMax = TGCVector3.Vector3ToFloat3Array(tgcMesh.BoundingBox.PMax); meshExport.MeshData.userProperties = tgcMesh.UserProperties; - meshExport.MeshData.alphaBlending = tgcMesh.AlphaBlendEnable; + meshExport.MeshData.alphaBlending = tgcMesh.AlphaBlend; //Exportar malla original if (tgcMesh.ParentInstance == null) @@ -537,7 +537,7 @@ private void exportMaterialData(TgcMesh tgcMesh, MeshExport meshExport, TgcMeshD tgcMaterial.SpecularColor.Alpha }; materialData.opacity = 1f; - materialData.alphaBlendEnable = tgcMesh.AlphaBlendEnable; + materialData.alphaBlendEnable = tgcMesh.AlphaBlend; //Texture var tgcTexture = tgcMesh.DiffuseMaps[0]; @@ -587,7 +587,7 @@ private void exportMaterialData(TgcMesh tgcMesh, MeshExport meshExport, TgcMeshD tgcMaterial.SpecularColor.Alpha }; materialData.opacity = 1f; - materialData.alphaBlendEnable = tgcMesh.AlphaBlendEnable; + materialData.alphaBlendEnable = tgcMesh.AlphaBlend; //Texture var tgcTexture = tgcMesh.DiffuseMaps[i]; @@ -1217,7 +1217,7 @@ public TgcMesh mergeTwoMeshes(TgcMesh mesh1, TgcMesh mesh2) tgcMesh.createBoundingBox(); tgcMesh.Materials = materials; tgcMesh.DiffuseMaps = textures; - tgcMesh.AlphaBlendEnable = mesh1.AlphaBlendEnable; + tgcMesh.AlphaBlend = mesh1.AlphaBlend; tgcMesh.Enabled = mesh1.Enabled; //Transformaciones con la identidad (porque ya transformamos los vertices) @@ -1225,7 +1225,7 @@ public TgcMesh mergeTwoMeshes(TgcMesh mesh1, TgcMesh mesh2) tgcMesh.Rotation = TGCVector3.Empty; tgcMesh.Scale = TGCVector3.One; tgcMesh.Transform = TGCMatrix.Identity; - tgcMesh.AutoTransformEnable = mesh1.AutoTransformEnable; + tgcMesh.AutoTransform = mesh1.AutoTransform; //Agregar userProperties de ambos if (mesh1.UserProperties != null || mesh2.UserProperties != null) diff --git a/TGC.Core/SceneLoader/TgcSceneLoader.cs b/TGC.Core/SceneLoader/TgcSceneLoader.cs index 47d9db62..4bb7f2ff 100644 --- a/TGC.Core/SceneLoader/TgcSceneLoader.cs +++ b/TGC.Core/SceneLoader/TgcSceneLoader.cs @@ -158,14 +158,14 @@ public TgcScene loadScene(TgcSceneData sceneData, string mediaPath) } } //Fixloader - tgcMesh.AutoTransformEnable = true; + tgcMesh.AutoTransform = true; } //Crear malla instancia else if (meshData.instanceType.Equals(TgcMeshData.INSTANCE)) { tgcMesh = crearMeshInstance(meshData, tgcScene.Meshes); - tgcMesh.AutoTransformEnable = true; + tgcMesh.AutoTransform = true; } //Crear BoundingBox, aprovechar lo que viene del XML o crear uno por nuestra cuenta @@ -187,7 +187,7 @@ public TgcScene loadScene(TgcSceneData sceneData, string mediaPath) tgcMesh.Layer = meshData.layerName; //Cargar AlphaBlending - tgcMesh.AlphaBlendEnable = meshData.alphaBlending; + tgcMesh.AlphaBlend = meshData.alphaBlending; //agregar mesh a escena tgcMesh.Enabled = true; diff --git a/TGC.Core/SkeletalAnimation/TgcSkeletalBoneAttach.cs b/TGC.Core/SkeletalAnimation/TgcSkeletalBoneAttach.cs index 78ee4761..b47f15d7 100644 --- a/TGC.Core/SkeletalAnimation/TgcSkeletalBoneAttach.cs +++ b/TGC.Core/SkeletalAnimation/TgcSkeletalBoneAttach.cs @@ -53,7 +53,7 @@ public TgcSkeletalBoneAttach(TgcMesh mesh, TgcSkeletalBone bone, TGCMatrix offse private void setMesh(TgcMesh mesh) { Mesh = mesh; - Mesh.AutoTransformEnable = false; + Mesh.AutoTransform = false; Mesh.Transform = Bone.MatFinal; } @@ -63,7 +63,7 @@ private void setMesh(TgcMesh mesh) /// public void updateValues() { - Mesh.AutoTransformEnable = false; + Mesh.AutoTransform = false; updateMeshTransform(TGCMatrix.Identity); } diff --git a/TGC.Core/SkeletalAnimation/TgcSkeletalMesh.cs b/TGC.Core/SkeletalAnimation/TgcSkeletalMesh.cs index 400da5be..35f5ae78 100644 --- a/TGC.Core/SkeletalAnimation/TgcSkeletalMesh.cs +++ b/TGC.Core/SkeletalAnimation/TgcSkeletalMesh.cs @@ -393,7 +393,7 @@ public bool RenderSkeleton /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable + public bool AlphaBlend { get { return alphaBlendEnable; } set { alphaBlendEnable = value; } @@ -587,7 +587,7 @@ public TGCMatrix Transform /// En False se respeta lo que el usuario haya cargado a mano en la matriz. /// Por default está en True. /// - public bool AutoTransformEnable + public bool AutoTransform { get { return autoTransformEnable; } set { autoTransformEnable = value; } @@ -717,7 +717,7 @@ protected void initData(Mesh mesh, string name, MeshRenderType renderType, TgcSk alphaBlendEnable = false; //variables de movimiento - AutoTransformEnable = false; + AutoTransform = false; translation = new TGCVector3(0f, 0f, 0f); rotation = new TGCVector3(0f, 0f, 0f); scale = new TGCVector3(1f, 1f, 1f); @@ -806,7 +806,7 @@ public void buildSkletonMesh() } //Crear malla de Joint para renderizar el esqueleto var jointBox = TGCBox.fromSize(jointsSize, jointsColor); - jointBox.AutoTransformEnable = false; + jointBox.AutoTransform = false; skeletonRenderJoints[i] = jointBox; } } diff --git a/TGC.Core/TGC.Core.csproj b/TGC.Core/TGC.Core.csproj index dd3f81ab..3f5aaf5e 100644 --- a/TGC.Core/TGC.Core.csproj +++ b/TGC.Core/TGC.Core.csproj @@ -92,7 +92,7 @@ - + diff --git a/TGC.Core/Terrain/TgcSimpleTerrain.cs b/TGC.Core/Terrain/TgcSimpleTerrain.cs index a37adf73..392af3b7 100644 --- a/TGC.Core/Terrain/TgcSimpleTerrain.cs +++ b/TGC.Core/Terrain/TgcSimpleTerrain.cs @@ -23,7 +23,7 @@ public class TgcSimpleTerrain : IRenderObject public TgcSimpleTerrain() { Enabled = true; - AlphaBlendEnable = false; + AlphaBlend = false; //Shader effect = TgcShaders.Instance.VariosShader; @@ -74,7 +74,7 @@ public TGCVector3 Position /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable { get; set; } + public bool AlphaBlend { get; set; } /// /// Renderiza el terreno diff --git a/TGC.Core/Terrain/TgcSkyBox.cs b/TGC.Core/Terrain/TgcSkyBox.cs index b540973a..a662373e 100644 --- a/TGC.Core/Terrain/TgcSkyBox.cs +++ b/TGC.Core/Terrain/TgcSkyBox.cs @@ -96,14 +96,14 @@ public TGCVector3 Center /// con textura o colores por vértice de canal Alpha. /// Por default está deshabilitado. /// - public bool AlphaBlendEnable + public bool AlphaBlend { - get { return Faces[0].AlphaBlendEnable; } + get { return Faces[0].AlphaBlend; } set { foreach (var face in Faces) { - face.AlphaBlendEnable = value; + face.AlphaBlend = value; } } } @@ -178,7 +178,7 @@ public void Init() faceMesh.Materials = new[] { D3DDevice.DEFAULT_MATERIAL }; faceMesh.createBoundingBox(); faceMesh.Enabled = true; - faceMesh.AutoTransformEnable = false; + faceMesh.AutoTransform = false; //textura var texture = TgcTexture.createTexture(D3DDevice.Instance.Device, FaceTextures[i]); diff --git a/TGC.Core/UserControls/Modifier/TgcModifiers.cs b/TGC.Core/UserControls/Modifier/TgcModifiers.cs index 9cf68fa1..0b454616 100644 --- a/TGC.Core/UserControls/Modifier/TgcModifiers.cs +++ b/TGC.Core/UserControls/Modifier/TgcModifiers.cs @@ -3,6 +3,7 @@ using System.Drawing; using System.Windows.Forms; using TGC.Core.Mathematica; +using TGC.Core.UserControls.Networking; namespace TGC.Core.UserControls.Modifier { @@ -168,7 +169,6 @@ public void addVertex2f(string varName, TGCVector2 minValue, TGCVector2 maxValue add(new TgcVertex2fModifier(varName, minValue, maxValue, defaultValue)); } - /* /// /// Modifier para Networking. /// Permite crear servidores y conectarse a estos como cliente, mediante conexiones TCP/IP utilizando DirectPlay. @@ -202,7 +202,6 @@ public TgcNetworkingModifier addNetworking(string varName, string serverName, st add(m); return m; } - */ /// /// Modificador que agrega un Boton diff --git a/TGC.Examples/Camara/TgcFpsCamera.cs b/TGC.Examples/Camara/TgcFpsCamera.cs index e6338352..df7e74c0 100644 --- a/TGC.Examples/Camara/TgcFpsCamera.cs +++ b/TGC.Examples/Camara/TgcFpsCamera.cs @@ -35,9 +35,7 @@ public TgcFpsCamera(TgcD3dInput input) { Input = input; positionEye = new TGCVector3(); - mouseCenter = new Point( - D3DDevice.Instance.Device.Viewport.Width / 2, - D3DDevice.Instance.Device.Viewport.Height / 2); + mouseCenter = new Point(D3DDevice.Instance.Device.Viewport.Width / 2, D3DDevice.Instance.Device.Viewport.Height / 2); RotationSpeed = 0.1f; MovementSpeed = 500f; JumpSpeed = 500f; @@ -59,8 +57,7 @@ public TgcFpsCamera(TGCVector3 positionEye, float moveSpeed, float jumpSpeed, Tg JumpSpeed = jumpSpeed; } - public TgcFpsCamera(TGCVector3 positionEye, float moveSpeed, float jumpSpeed, float rotationSpeed, - TgcD3dInput input) + public TgcFpsCamera(TGCVector3 positionEye, float moveSpeed, float jumpSpeed, float rotationSpeed, TgcD3dInput input) : this(positionEye, moveSpeed, jumpSpeed, input) { RotationSpeed = rotationSpeed; diff --git a/TGC.Examples/Collision/EjemploColisionCamara.cs b/TGC.Examples/Collision/EjemploColisionCamara.cs index cd3cbf58..db4fb2f2 100644 --- a/TGC.Examples/Collision/EjemploColisionCamara.cs +++ b/TGC.Examples/Collision/EjemploColisionCamara.cs @@ -54,34 +54,34 @@ public override void Init() //Obstaculo 1 obstaculo = TGCBox.fromExtremes(TGCVector3.Empty, new TGCVector3(wallSize, wallHeight, 10), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\baldosaFacultad.jpg")); - obstaculo.AutoTransformEnable = true; + obstaculo.AutoTransform = true; 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.AutoTransformEnable = true; + obstaculo.AutoTransform = true; 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.AutoTransformEnable = true; + obstaculo.AutoTransform = true; 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.AutoTransformEnable = true; + obstaculo.AutoTransform = true; 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.AutoTransformEnable = true; + obstaculo.AutoTransform = true; obstaculos.Add(obstaculo); //Cargar personaje con animaciones diff --git a/TGC.Examples/Collision/EjemploMoveElipsoidTriangleThirdPerson.cs b/TGC.Examples/Collision/EjemploMoveElipsoidTriangleThirdPerson.cs index bcacb980..36fdf41a 100644 --- a/TGC.Examples/Collision/EjemploMoveElipsoidTriangleThirdPerson.cs +++ b/TGC.Examples/Collision/EjemploMoveElipsoidTriangleThirdPerson.cs @@ -80,7 +80,7 @@ public override void Init() //Se utiliza autotransform, aunque este es un claro ejemplo de que no se debe usar autotransform, //hay muchas operaciones y la mayoria las maneja el manager de colisiones, con lo cual se esta //perdiendo el control de las transformaciones del personaje. - personaje.AutoTransformEnable = true; + personaje.AutoTransform = true; //Configurar animacion inicial personaje.playAnimation("StandBy", true); //Escalarlo porque es muy grande diff --git a/TGC.Examples/Collision/EjemploMovePicking.cs b/TGC.Examples/Collision/EjemploMovePicking.cs index cda40542..b51e92ad 100644 --- a/TGC.Examples/Collision/EjemploMovePicking.cs +++ b/TGC.Examples/Collision/EjemploMovePicking.cs @@ -64,7 +64,7 @@ public override void Init() originalMeshRot = new TGCVector3(0, 0, -1); //Manipulamos los movimientos del mesh a mano - mesh.AutoTransformEnable = false; + mesh.AutoTransform = false; meshRotationMatrix = TGCMatrix.Identity; newPosition = mesh.Position; diff --git a/TGC.Examples/Collision/EjemploMoveSphereThirdPerson.cs b/TGC.Examples/Collision/EjemploMoveSphereThirdPerson.cs index 1f6396bd..ee387e78 100644 --- a/TGC.Examples/Collision/EjemploMoveSphereThirdPerson.cs +++ b/TGC.Examples/Collision/EjemploMoveSphereThirdPerson.cs @@ -85,7 +85,7 @@ public override void Init() //Se utiliza autotransform, aunque este es un claro ejemplo de que no se debe usar autotransform, //hay muchas operaciones y la mayoria las maneja el manager de colisiones, con lo cual se esta //perdiendo el control de las transformaciones del personaje. - personaje.AutoTransformEnable = true; + personaje.AutoTransform = true; //Escalarlo porque es muy grande personaje.Position = new TGCVector3(0, 500, -100); //Rotarlo 180° porque esta mirando para el otro lado diff --git a/TGC.Examples/Collision/EjemploMoveSphereTriangleThirdPerson.cs b/TGC.Examples/Collision/EjemploMoveSphereTriangleThirdPerson.cs index a7a29413..cdcb3c90 100644 --- a/TGC.Examples/Collision/EjemploMoveSphereTriangleThirdPerson.cs +++ b/TGC.Examples/Collision/EjemploMoveSphereTriangleThirdPerson.cs @@ -84,7 +84,7 @@ public override void Init() //Se utiliza autotransform, aunque este es un claro ejemplo de que no se debe usar autotransform, //hay muchas operaciones y la mayoria las maneja el manager de colisiones, con lo cual se esta //perdiendo el control de las transformaciones del personaje. - personaje.AutoTransformEnable = true; + personaje.AutoTransform = true; //Configurar animacion inicial personaje.playAnimation("Parado", true); //Escalarlo porque es muy grande @@ -132,7 +132,7 @@ public override void Init() //Caja para marcar punto de colision collisionPoint = TGCBox.fromSize(new TGCVector3(4, 4, 4), Color.Red); - collisionPoint.AutoTransformEnable = true; + collisionPoint.AutoTransform = true; //Crear manejador de colisiones collisionManager = new SphereTriangleCollisionManager(); diff --git a/TGC.Examples/Collision/EjemploMoveThirdPerson.cs b/TGC.Examples/Collision/EjemploMoveThirdPerson.cs index c8198629..cf25b93b 100644 --- a/TGC.Examples/Collision/EjemploMoveThirdPerson.cs +++ b/TGC.Examples/Collision/EjemploMoveThirdPerson.cs @@ -60,21 +60,21 @@ public override void Init() obstaculo = TGCBox.fromSize(new TGCVector3(-100, 0, 0), new TGCVector3(80, 150, 80), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\baldosaFacultad.jpg")); //No es recomendado utilizar autotransform en casos mas complicados, se pierde el control. - obstaculo.AutoTransformEnable = true; + obstaculo.AutoTransform = true; obstaculos.Add(obstaculo); //Obstaculo 2 obstaculo = TGCBox.fromSize(new TGCVector3(50, 0, 200), new TGCVector3(80, 300, 80), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\madera.jpg")); //No es recomendado utilizar autotransform en casos mas complicados, se pierde el control. - obstaculo.AutoTransformEnable = true; + obstaculo.AutoTransform = true; obstaculos.Add(obstaculo); //Obstaculo 3 obstaculo = TGCBox.fromSize(new TGCVector3(300, 0, 100), new TGCVector3(80, 100, 150), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\granito.jpg")); //No es recomendado utilizar autotransform en casos mas complicados, se pierde el control. - obstaculo.AutoTransformEnable = true; + obstaculo.AutoTransform = true; obstaculos.Add(obstaculo); //Cargar personaje con animaciones @@ -99,7 +99,7 @@ public override void Init() //Configurar animacion inicial personaje.playAnimation("Parado", true); //No es recomendado utilizar autotransform en casos mas complicados, se pierde el control. - personaje.AutoTransformEnable = true; + personaje.AutoTransform = true; //Escalarlo porque es muy grande personaje.Position = new TGCVector3(0, -45, 0); diff --git a/TGC.Examples/Collision/EjemploPicking.cs b/TGC.Examples/Collision/EjemploPicking.cs index 9c5bfb91..3807bea3 100644 --- a/TGC.Examples/Collision/EjemploPicking.cs +++ b/TGC.Examples/Collision/EjemploPicking.cs @@ -56,7 +56,7 @@ public override void Init() { var center = new TGCVector3((boxSize.X + boxSize.X / 2) * i, (boxSize.Y + boxSize.Y / 2) * j, 0); var box = TGCBox.fromSize(center, boxSize, texture); - box.AutoTransformEnable = true; + box.AutoTransform = true; boxes.Add(box); } } @@ -68,7 +68,7 @@ public override void Init() //Crear caja para marcar en que lugar hubo colision collisionPointMesh = TGCBox.fromSize(new TGCVector3(3, 3, 3), Color.Red); - collisionPointMesh.AutoTransformEnable = true; + collisionPointMesh.AutoTransform = true; selected = false; //UserVars para mostrar en que punto hubo colision diff --git a/TGC.Examples/DirectX/DirectXLight.cs b/TGC.Examples/DirectX/DirectXLight.cs index 24be30f4..2e1f8250 100644 --- a/TGC.Examples/DirectX/DirectXLight.cs +++ b/TGC.Examples/DirectX/DirectXLight.cs @@ -99,10 +99,10 @@ public override void Update() public override void Render() { - PreRender(); - //Pongo el fondo negro - D3DDevice.Instance.Device.Clear(ClearFlags.Target, Color.Black, 1.0f, 0); + D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + BeginScene(); + ClearTextures(); //Obtener valores de Modifiers var vAngleX = (float)Modifiers["angleX"]; diff --git a/TGC.Examples/GeometryBasics/EjemploCajas.cs b/TGC.Examples/GeometryBasics/EjemploCajas.cs index 9d79c5ab..29ba036a 100644 --- a/TGC.Examples/GeometryBasics/EjemploCajas.cs +++ b/TGC.Examples/GeometryBasics/EjemploCajas.cs @@ -42,7 +42,7 @@ public override void Init() { //Crear caja vacia box = new TGCBox(); - box.AutoTransformEnable = true; + box.AutoTransform = true; //Crear caja debug vacia debugBox = new TgcBoxDebug(); currentTexture = null; diff --git a/TGC.Examples/GeometryBasics/EjemploCilindro.cs b/TGC.Examples/GeometryBasics/EjemploCilindro.cs index dd3a6fa8..afd501bb 100644 --- a/TGC.Examples/GeometryBasics/EjemploCilindro.cs +++ b/TGC.Examples/GeometryBasics/EjemploCilindro.cs @@ -32,9 +32,9 @@ public EjemploCilindro(string mediaDir, string shadersDir, TgcUserVars userVars, public override void Init() { cylinder = new TgcCylinder(TGCVector3.Empty, 2, 4); - cylinder.AutoTransformEnable = true; + cylinder.AutoTransform = true; - cylinder.AlphaBlendEnable = true; + cylinder.AlphaBlend = true; Modifiers.addBoolean("boundingCylinder", "boundingCylinder", false); Modifiers.addColor("color", Color.White); diff --git a/TGC.Examples/GeometryBasics/EjemploQuad.cs b/TGC.Examples/GeometryBasics/EjemploQuad.cs index 170c872c..7038a6e9 100644 --- a/TGC.Examples/GeometryBasics/EjemploQuad.cs +++ b/TGC.Examples/GeometryBasics/EjemploQuad.cs @@ -19,7 +19,7 @@ namespace TGC.Examples.GeometryBasics public class EjemploQuad : TGCExampleViewer { private TgcArrow normalArrow; - private TgcQuad quad; + private TGCQuad quad; public EjemploQuad(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) : base(mediaDir, shadersDir, userVars, modifiers) @@ -33,7 +33,7 @@ public EjemploQuad(string mediaDir, string shadersDir, TgcUserVars userVars, Tgc public override void Init() { //Crear Quad vacio - quad = new TgcQuad(); + quad = new TGCQuad(); //Modifiers para vararia sus parametros Modifiers.addVertex2f("size", TGCVector2.Zero, new TGCVector2(100, 100), new TGCVector2(20, 20)); diff --git a/TGC.Examples/GeometryBasics/EjemploSphere.cs b/TGC.Examples/GeometryBasics/EjemploSphere.cs index 11906179..d96ebc6e 100644 --- a/TGC.Examples/GeometryBasics/EjemploSphere.cs +++ b/TGC.Examples/GeometryBasics/EjemploSphere.cs @@ -39,7 +39,7 @@ public override void Init() //Crear esfera sphere = new TGCSphere(); //No recomendamos utilizar AutoTransformEnable, con juegos complejos se pierde el control. - sphere.AutoTransformEnable = true; + sphere.AutoTransform = true; currentTexture = null; //Modifiers para vararis sus parametros diff --git a/TGC.Examples/Lights/EjemploMultiDiffuseLights.cs b/TGC.Examples/Lights/EjemploMultiDiffuseLights.cs index 6c99da6b..61158e65 100644 --- a/TGC.Examples/Lights/EjemploMultiDiffuseLights.cs +++ b/TGC.Examples/Lights/EjemploMultiDiffuseLights.cs @@ -68,7 +68,7 @@ public override void Init() { var co = c[i % c.Length]; lightMeshes[i] = TGCBox.fromSize(new TGCVector3(10, 10, 10), co); - lightMeshes[i].AutoTransformEnable = true; + lightMeshes[i].AutoTransform = true; origLightPos[i] = new TGCVector3(-40, 20 + i * 20, 400); } diff --git a/TGC.Examples/Lights/EjemploPointLight.cs b/TGC.Examples/Lights/EjemploPointLight.cs index 298961f2..c68a58da 100644 --- a/TGC.Examples/Lights/EjemploPointLight.cs +++ b/TGC.Examples/Lights/EjemploPointLight.cs @@ -61,7 +61,7 @@ public override void Init() skeletalMesh.computeNormals(); //Pongo al mesh en posicion, activo e AutoTransform - skeletalMesh.AutoTransformEnable = true; + skeletalMesh.AutoTransform = true; skeletalMesh.Position = new TGCVector3(0, 0, 100); skeletalMesh.RotateY(FastMath.PI); @@ -72,7 +72,7 @@ public override void Init() lightMesh = TGCBox.fromSize(new TGCVector3(10, 10, 10)); //Pongo al mesh en posicion, activo e AutoTransform - lightMesh.AutoTransformEnable = true; + lightMesh.AutoTransform = true; lightMesh.Position = new TGCVector3(0, 150, 150); //Modifiers de la luz diff --git a/TGC.Examples/Lights/TgcMeshBumpMapping.cs b/TGC.Examples/Lights/TgcMeshBumpMapping.cs index b1ded43d..802dcfa3 100644 --- a/TGC.Examples/Lights/TgcMeshBumpMapping.cs +++ b/TGC.Examples/Lights/TgcMeshBumpMapping.cs @@ -274,7 +274,7 @@ public static TgcMeshBumpMapping fromTgcMesh(TgcMesh mesh, TgcTexture[] normalMa bumpMesh.materials = materials; bumpMesh.NormalMaps = normalMaps; bumpMesh.layer = mesh.Layer; - bumpMesh.alphaBlendEnable = mesh.AlphaBlendEnable; + bumpMesh.alphaBlendEnable = mesh.AlphaBlend; bumpMesh.UserProperties = mesh.UserProperties; bumpMesh.boundingBox = mesh.BoundingBox.clone(); bumpMesh.enabled = true; diff --git a/TGC.Examples/MeshExamples/EjemploBatchPrimitives.cs b/TGC.Examples/MeshExamples/EjemploBatchPrimitives.cs index 5e81a6be..c5875a97 100644 --- a/TGC.Examples/MeshExamples/EjemploBatchPrimitives.cs +++ b/TGC.Examples/MeshExamples/EjemploBatchPrimitives.cs @@ -64,15 +64,15 @@ private void createMeshes(int cajasPorCuadrante) //Crear tres niveles de caja, una abajo y otra arriba, con texturas diferentes cajasNivel1[cajas] = TGCBox.fromSize(new TGCVector3(i * boxSize, 0, j * boxSize * 1.5f), new TGCVector3(boxSize, boxSize, boxSize), box1Texture); - cajasNivel1[cajas].AutoTransformEnable = true; + cajasNivel1[cajas].AutoTransform = true; cajasNivel2[cajas] = TGCBox.fromSize(new TGCVector3(i * boxSize, boxSize, j * boxSize * 1.5f), new TGCVector3(boxSize, boxSize, boxSize), box2Texture); - cajasNivel2[cajas].AutoTransformEnable = true; + cajasNivel2[cajas].AutoTransform = true; cajasNivel3[cajas] = TGCBox.fromSize(new TGCVector3(i * boxSize, boxSize * 2, j * boxSize * 1.5f), new TGCVector3(boxSize, boxSize, boxSize), box3Texture); - cajasNivel3[cajas].AutoTransformEnable = true; + cajasNivel3[cajas].AutoTransform = true; cajas++; } } diff --git a/TGC.Examples/MeshExamples/EjemploDisposeMesh.cs b/TGC.Examples/MeshExamples/EjemploDisposeMesh.cs index f06499e8..895840c7 100644 --- a/TGC.Examples/MeshExamples/EjemploDisposeMesh.cs +++ b/TGC.Examples/MeshExamples/EjemploDisposeMesh.cs @@ -45,7 +45,7 @@ public override void Init() for (var j = 0; j < 50; j++) { var mesh = baseMesh.clone(i + " - " + j); - mesh.AutoTransformEnable = true; + mesh.AutoTransform = true; mesh.Move(i * 100, 0, j * 100); meshes.Add(mesh); //Se agrega un callback function para informar cuando se realiza el dispose. diff --git a/TGC.Examples/MeshExamples/EjemploMeshInstancias.cs b/TGC.Examples/MeshExamples/EjemploMeshInstancias.cs index 907f8ce6..9ac9eaee 100644 --- a/TGC.Examples/MeshExamples/EjemploMeshInstancias.cs +++ b/TGC.Examples/MeshExamples/EjemploMeshInstancias.cs @@ -58,7 +58,7 @@ public override void Init() //Crear instancia de modelo var instance = palmeraOriginal.createMeshInstance(palmeraOriginal.Name + i + "_" + j); //No recomendamos utilizar AutoTransform, en juegos complejos se pierde el control. mejor utilizar Transformaciones con matrices. - instance.AutoTransformEnable = true; + instance.AutoTransform = true; //Desplazarlo instance.Move(i * offset, 0, j * offset); //instance.Scale = new TGCVector3(0.25f, 0.25f, 0.25f); diff --git a/TGC.Examples/MeshExamples/EjemploMeshLoader.cs b/TGC.Examples/MeshExamples/EjemploMeshLoader.cs index 4f4b516c..0b3edf27 100644 --- a/TGC.Examples/MeshExamples/EjemploMeshLoader.cs +++ b/TGC.Examples/MeshExamples/EjemploMeshLoader.cs @@ -174,7 +174,7 @@ public override void Render() currentAlphaBlending = alphaBlending; foreach (var mesh in currentScene.Meshes) { - mesh.AlphaBlendEnable = currentAlphaBlending; + mesh.AlphaBlend = currentAlphaBlending; } } diff --git a/TGC.Examples/MeshExamples/EjemploTriangulosYPlanos.cs b/TGC.Examples/MeshExamples/EjemploTriangulosYPlanos.cs index 08eaf2be..48ba40ac 100644 --- a/TGC.Examples/MeshExamples/EjemploTriangulosYPlanos.cs +++ b/TGC.Examples/MeshExamples/EjemploTriangulosYPlanos.cs @@ -24,7 +24,7 @@ public class EjemploTriangulosYPlanos : TGCExampleViewer private readonly Random random = new Random(); private TgcMesh mesh; private List normals; - private List planes; + private List planes; private List triangles; public EjemploTriangulosYPlanos(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) @@ -52,7 +52,7 @@ public override void Init() var triCount = vertices.Length / 3; triangles = new List(triCount); normals = new List(); - planes = new List(); + planes = new List(); for (var i = 0; i < triCount; i++) { //Obtenemos los 3 vertices del triangulo, es importante saber como esta estructurado nuestro mesh. @@ -74,7 +74,7 @@ public override void Init() ///////////// Creacion de elementos para poder dibujar a pantalla (propios de este ejemplo) /////////////// //Crear un quad (pequeno plano) con la clase TgcQuad para poder dibujar el plano que contiene al triangulo - var quad = new TgcQuad(); + var quad = new TGCQuad(); quad.Center = center; quad.Normal = normal; quad.Color = adaptColorRandom(Color.DarkGreen); diff --git a/TGC.Examples/MeshExamples/ModeloConAlpha.cs b/TGC.Examples/MeshExamples/ModeloConAlpha.cs index a732ebbf..6db56e77 100644 --- a/TGC.Examples/MeshExamples/ModeloConAlpha.cs +++ b/TGC.Examples/MeshExamples/ModeloConAlpha.cs @@ -32,7 +32,7 @@ public override void Init() { /* Cargar ecena que tiene un modelo configurado con AlphaBlending * Los modelos fueron exportados en 3Ds MAX con el mapa "Opacity" cargado en el "Material Editor" - * Entonces el TgcSceneLoader automaticamente hace mesh.AlphaBlendEnable(true); + * Entonces el TgcSceneLoader automaticamente hace mesh.AlphaBlend(true); */ var loader = new TgcSceneLoader(); scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Pino\\Pino-TgcScene.xml"); @@ -52,7 +52,7 @@ public override void Update() foreach (var mesh in scene.Meshes) { - mesh.AlphaBlendEnable = alpha; + mesh.AlphaBlend = alpha; } } diff --git a/TGC.Examples/Multiplayer/EjemploClient.cs b/TGC.Examples/Multiplayer/EjemploClient.cs index 522b5ac1..ff1e4e5b 100644 --- a/TGC.Examples/Multiplayer/EjemploClient.cs +++ b/TGC.Examples/Multiplayer/EjemploClient.cs @@ -2,35 +2,29 @@ using System.Net; using System.Net.Sockets; using System.Text; -using TGC.Core.Example; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Example; namespace TGC.Examples.Multiplayer { /// /// EjemploClient /// - public class EjemploClient : TgcExample + public class EjemploClient : TGCExampleViewer { private float acumulatedTime; private int mensaje; private Socket serverSocket; - public override string getCategory() + public EjemploClient(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) : base(mediaDir, shadersDir, userVars, modifiers) { - return "Multiplayer"; + Category = "Multiplayer"; + Name = "EjemploClient"; + Description = "EjemploClient."; } - public override string getName() - { - return "EjemploClient"; - } - - public override string getDescription() - { - return "EjemploClient."; - } - - public override void init() + public override void Init() { var ipAddress = Dns.GetHostAddresses("localhost"); var Ipep = new IPEndPoint(ipAddress[0], 4444); @@ -43,7 +37,12 @@ public override void init() mensaje = 0; } - public override void render(float elapsedTime) + public override void Update() + { + PreUpdate(); + } + + public override void Render() { if (serverSocket.Poll(0, SelectMode.SelectRead)) { @@ -62,7 +61,7 @@ public override void render(float elapsedTime) if (serverSocket.Connected) { - acumulatedTime += elapsedTime; + acumulatedTime += ElapsedTime; if (acumulatedTime > 2) { acumulatedTime = 0; @@ -73,7 +72,7 @@ public override void render(float elapsedTime) } } - public override void close() + public override void Dispose() { serverSocket.Shutdown(SocketShutdown.Both); serverSocket.Close(); diff --git a/TGC.Examples/Multiplayer/EjemploNetworkingModifier.cs b/TGC.Examples/Multiplayer/EjemploNetworkingModifier.cs index a5f6feb1..4962fee2 100644 --- a/TGC.Examples/Multiplayer/EjemploNetworkingModifier.cs +++ b/TGC.Examples/Multiplayer/EjemploNetworkingModifier.cs @@ -1,8 +1,9 @@ using System.Diagnostics; using System.Drawing; -using TGC.Core.Example; -using TGC.Util; -using TGC.Util.Networking; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Core.UserControls.Networking; +using TGC.Examples.Example; namespace TGC.Examples.Multiplayer { @@ -15,35 +16,32 @@ namespace TGC.Examples.Multiplayer /// y el servidor lo imprime por consola.... o como hacer el TP de Operativo en 5 min. /// Autor: Matías Leone, Leandro Barbagallo /// - public class EjemploNetworkingModifier : TgcExample + public class EjemploNetworkingModifier : TGCExampleViewer { private float acumulatedTime; private TgcNetworkingModifier networkingMod; - public override string getCategory() + public EjemploNetworkingModifier(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) : base(mediaDir, shadersDir, userVars, modifiers) { - return "Multiplayer"; + Category = "Multiplayer"; + Name = "NetworkingModifier"; + Description = "El cliente envia un mensaje cada 1 segundo al servidor y el servidor lo imprime por consola."; } - public override string getName() + public override void Init() { - return "NetworkingModifier"; - } + //Crear Modifier de Networking + networkingMod = Modifiers.addNetworking("Networking", "MyServer", "MyClient"); - public override string getDescription() - { - return "El cliente envia un mensaje cada 1 segundo al servidor y el servidor lo imprime por consola."; + acumulatedTime = 0; } - public override void init() + public override void Update() { - //Crear Modifier de Networking - networkingMod = GuiController.Instance.Modifiers.addNetworking("Networking", "MyServer", "MyClient"); - - acumulatedTime = 0; + PreUpdate(); } - public override void render(float elapsedTime) + public override void Render() { //Actualizar siempre primero todos los valores de red. //Esto hace que el cliente y el servidor reciban todos los mensajes y actualicen su es @@ -70,7 +68,7 @@ public override void render(float elapsedTime) if (networkingMod.Client.Online) { //Mandamos un mensaje al server cada 1 segundo - acumulatedTime += elapsedTime; + acumulatedTime += ElapsedTime; if (acumulatedTime > 1) { acumulatedTime = 0; @@ -79,7 +77,7 @@ public override void render(float elapsedTime) var msg = new TgcSocketSendMsg(); //Agregar un dato al mensaje, un string en este caso - msg.write("Hello world - ElapsedTime: " + elapsedTime); + msg.write("Hello world - ElapsedTime: " + ElapsedTime); //Enviar mensaje al server networkingMod.Client.send(msg); @@ -87,7 +85,7 @@ public override void render(float elapsedTime) } } - public override void close() + public override void Dispose() { //Cerrar todas las conexiones networkingMod.dispose(); diff --git a/TGC.Examples/Multiplayer/EjemploServer.cs b/TGC.Examples/Multiplayer/EjemploServer.cs index 1a25fb3b..78d7670b 100644 --- a/TGC.Examples/Multiplayer/EjemploServer.cs +++ b/TGC.Examples/Multiplayer/EjemploServer.cs @@ -3,35 +3,29 @@ using System.Net; using System.Net.Sockets; using System.Text; -using TGC.Core.Example; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Example; namespace TGC.Examples.Multiplayer { /// /// EjemploServer /// - public class EjemploServer : TgcExample + public class EjemploServer : TGCExampleViewer { private List clients; private int recibido; private Socket serverSocket; - public override string getCategory() + public EjemploServer(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) : base(mediaDir, shadersDir, userVars, modifiers) { - return "Multiplayer"; + Category = "Multiplayer"; + Name = "EjemploServer"; + Description = "EjemploServer."; } - public override string getName() - { - return "EjemploServer"; - } - - public override string getDescription() - { - return "EjemploServer."; - } - - public override void init() + public override void Init() { var ipAddress = Dns.GetHostAddresses("localhost"); var Ipep = new IPEndPoint(ipAddress[0], 4444); @@ -51,7 +45,12 @@ public override void init() */ } - public override void render(float elapsedTime) + public override void Update() + { + PreUpdate(); + } + + public override void Render() { if (serverSocket.Poll(0, SelectMode.SelectRead)) { @@ -94,7 +93,7 @@ public override void render(float elapsedTime) } } - public override void close() + public override void Dispose() { foreach (var clientSocket in clients) { diff --git a/TGC.Examples/Multiplayer/VehiculosMultiplayer.cs b/TGC.Examples/Multiplayer/VehiculosMultiplayer.cs index 6956e9de..a85f7a68 100644 --- a/TGC.Examples/Multiplayer/VehiculosMultiplayer.cs +++ b/TGC.Examples/Multiplayer/VehiculosMultiplayer.cs @@ -1,16 +1,17 @@ -using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using Microsoft.DirectX.DirectInput; using System; using System.Collections.Generic; using TGC.Core.Direct3D; -using TGC.Core.Example; -using TGC.Core.Geometries; -using TGC.Core.Input; +using TGC.Core.Geometry; +using TGC.Core.Mathematica; using TGC.Core.SceneLoader; using TGC.Core.Textures; -using TGC.Util; -using TGC.Util.Networking; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Core.UserControls.Networking; +using TGC.Examples.Camara; +using TGC.Examples.Example; namespace TGC.Examples.Multiplayer { @@ -26,33 +27,22 @@ namespace TGC.Examples.Multiplayer /// El server simplemente recibe y redirige la información. /// Autor: Matías Leone, Leandro Barbagallo /// - public class VehiculosMultiplayer : TgcExample + public class VehiculosMultiplayer : TGCExampleViewer { private float acumulatedTime; private TgcNetworkingModifier networkingMod; - private TgcThirdPersonCamera camara; - public override string getCategory() + public VehiculosMultiplayer(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) : base(mediaDir, shadersDir, userVars, modifiers) { - return "Multiplayer"; + Category = "Multiplayer"; + Name = "Vehiculos Multiplayer"; + Description = "Multiplayer en la cual hasta 4 jugadores pueden conectarse y utilizar vehículos sobre un mismo escenario."; } - public override string getName() - { - return "Vehiculos Multiplayer"; - } - - public override string getDescription() - { - return - "Partida multiplayer en la cual hasta 4 jugadores pueden conectarse y utilizar vehículos sobre un mismo escenario."; - } - - public override void init() + public override void Init() { //Crear Modifier de Networking - networkingMod = GuiController.Instance.Modifiers.addNetworking("Networking", "VehiculosServer", - "VehiculosClient"); + networkingMod = Modifiers.addNetworking("Networking", "VehiculosServer", "VehiculosClient"); acumulatedTime = 0; @@ -63,7 +53,12 @@ public override void init() initClient(); } - public override void render(float elapsedTime) + public override void Update() + { + PreUpdate(); + } + + public override void Render() { //Actualizar siempre primero todos los valores de red. //Esto hace que el cliente y el servidor reciban todos los mensajes y actualicen su estado interno @@ -82,23 +77,23 @@ public override void render(float elapsedTime) } } - public override void close() + public override void Dispose() { //Cierra todas las conexiones networkingMod.dispose(); - piso.dispose(); + piso.Dispose(); //Renderizar meshPrincipal if (meshPrincipal != null) { - meshPrincipal.dispose(); + meshPrincipal.Dispose(); } //Renderizar otrosMeshes foreach (var entry in otrosMeshes) { - entry.Value.dispose(); + entry.Value.Dispose(); } } @@ -123,11 +118,11 @@ private enum MyServerProtocol [Serializable] private class VehiculoData { - public readonly Vector3 initialPos; + public readonly TGCVector3 initialPos; public readonly string meshPath; public int playerID; - public VehiculoData(Vector3 initialPos, string meshPath) + public VehiculoData(TGCVector3 initialPos, string meshPath) { playerID = -1; this.initialPos = initialPos; @@ -143,16 +138,13 @@ public VehiculoData(Vector3 initialPos, string meshPath) private void initServerData() { //Configurar datos para los 4 clientes posibles del servidor - var mediaPath = GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\"; + var mediaPath = MediaDir + "ModelosTgc\\"; vehiculosData = new[] { - new VehiculoData(new Vector3(0, 0, 0), - mediaPath + "TanqueFuturistaRuedas\\TanqueFuturistaRuedas-TgcScene.xml"), - new VehiculoData(new Vector3(100, 0, 0), - mediaPath + "HelicopteroMilitar\\HelicopteroMilitar-TgcScene.xml"), - new VehiculoData(new Vector3(200, 0, 0), mediaPath + "Auto\\Auto-TgcScene.xml"), - new VehiculoData(new Vector3(0, 0, 200), - mediaPath + "AerodeslizadorFuturista\\AerodeslizadorFuturista-TgcScene.xml") + new VehiculoData(new TGCVector3(0, 0, 0), mediaPath + "TanqueFuturistaRuedas\\TanqueFuturistaRuedas-TgcScene.xml"), + new VehiculoData(new TGCVector3(100, 0, 0), mediaPath + "HelicopteroMilitar\\HelicopteroMilitar-TgcScene.xml"), + new VehiculoData(new TGCVector3(200, 0, 0), mediaPath + "Auto\\Auto-TgcScene.xml"), + new VehiculoData(new TGCVector3(0, 0, 200), mediaPath + "AerodeslizadorFuturista\\AerodeslizadorFuturista-TgcScene.xml") }; } @@ -252,7 +244,7 @@ private void atenderClienteDesconectado(TgcSocketClientInfo clientInfo) private void serverAtenderPosicionActualizada(TgcSocketClientRecvMesg clientMsg) { //Nueva posicion del cliente - var newPos = (Matrix)clientMsg.Msg.readNext(); + var newPos = (TGCMatrix)clientMsg.Msg.readNext(); //Enviar a todos menos al cliente que nos acaba de informar var sendMsg = new TgcSocketSendMsg(); @@ -277,9 +269,10 @@ private enum MyClientProtocol PosicionActualizada } - private TgcBox piso; + private TGCBox piso; private TgcMesh meshPrincipal; private readonly Dictionary otrosMeshes = new Dictionary(); + private TgcThirdPersonCamera camaraInterna; /// /// Iniciar cliente @@ -287,14 +280,13 @@ private enum MyClientProtocol private void initClient() { //Crear piso - var pisoTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, - GuiController.Instance.ExamplesMediaDir + "Texturas\\Quake\\TexturePack2\\rock_wall.jpg"); - piso = TgcBox.fromSize(new Vector3(0, -60, 0), new Vector3(5000, 5, 5000), pisoTexture); + var pisoTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\Quake\\TexturePack2\\rock_wall.jpg"); + piso = TGCBox.fromSize(new TGCVector3(0, -60, 0), new TGCVector3(5000, 5, 5000), pisoTexture); //Camara en 3ra persona - this.camara = new TgcThirdPersonCamera(); - CamaraManager.Instance.CurrentCamera = this.camara; - this.camara.Enable = true; + camaraInterna.resetValues(); + camaraInterna = new TgcThirdPersonCamera(meshPrincipal.Position, 100, 400); + Camara = camaraInterna; } /// @@ -336,7 +328,7 @@ private void updateClient() renderClient(); //Enviar al server mensaje con posicion actualizada, 10 paquetes por segundo - acumulatedTime += GuiController.Instance.ElapsedTime; + acumulatedTime += ElapsedTime; if (acumulatedTime > 0.1) { acumulatedTime = 0; @@ -366,10 +358,6 @@ private void clienteAtenderInformacionInicial(TgcSocketRecvMsg msg) //Ubicarlo en escenario meshPrincipal.Position = vehiculoData.initialPos; - //Camara - this.camara.resetValues(); - this.camara.setCamera(meshPrincipal.Position, 100, 400); - //Ver si ya habia mas clientes para cuando nosotros nos conectamos var otrosVehiculosCant = (int)msg.readNext(); for (var i = 0; i < otrosVehiculosCant; i++) @@ -385,36 +373,34 @@ private void clienteAtenderInformacionInicial(TgcSocketRecvMsg msg) private void renderClient() { //Calcular proxima posicion de personaje segun Input - var elapsedTime = GuiController.Instance.ElapsedTime; var moveForward = 0f; float rotate = 0; - var d3dInput = TgcD3dInput.Instance; var moving = false; var rotating = false; //Adelante - if (d3dInput.keyDown(Key.W)) + if (Input.keyDown(Key.W)) { moveForward = -VELODICAD_CAMINAR; moving = true; } //Atras - if (d3dInput.keyDown(Key.S)) + if (Input.keyDown(Key.S)) { moveForward = VELODICAD_CAMINAR; moving = true; } //Derecha - if (d3dInput.keyDown(Key.D)) + if (Input.keyDown(Key.D)) { rotate = VELOCIDAD_ROTACION; rotating = true; } //Izquierda - if (d3dInput.keyDown(Key.A)) + if (Input.keyDown(Key.A)) { rotate = -VELOCIDAD_ROTACION; rotating = true; @@ -423,32 +409,32 @@ private void renderClient() //Si hubo rotacion if (rotating) { - meshPrincipal.rotateY(Geometry.DegreeToRadian(rotate * elapsedTime)); - this.camara.rotateY(rotate); + meshPrincipal.RotateY(Geometry.DegreeToRadian(rotate * ElapsedTime)); + this.camaraInterna.rotateY(rotate); } //Si hubo desplazamiento if (moving) { - meshPrincipal.moveOrientedY(moveForward * elapsedTime); + meshPrincipal.MoveOrientedY(moveForward * ElapsedTime); } //Hacer que la camara siga al personaje en su nueva posicion - this.camara.Target = meshPrincipal.Position; + this.camaraInterna.Target = meshPrincipal.Position; //Render piso - piso.render(); + piso.Render(); //Renderizar meshPrincipal if (meshPrincipal != null) { - meshPrincipal.render(); + meshPrincipal.Render(); } //Renderizar otrosMeshes foreach (var entry in otrosMeshes) { - entry.Value.render(); + entry.Value.Render(); } } @@ -474,8 +460,8 @@ private void crearMeshOtroCliente(VehiculoData vehiculoData) otrosMeshes.Add(vehiculoData.playerID, mesh); //Ubicarlo en escenario - mesh.AutoTransformEnable = false; - mesh.Transform = Matrix.Translation(vehiculoData.initialPos); + mesh.AutoTransform = false; + mesh.Transform = TGCMatrix.Translation(vehiculoData.initialPos); } /// @@ -484,7 +470,7 @@ private void crearMeshOtroCliente(VehiculoData vehiculoData) private void clienteAtenderActualizarUbicaciones(TgcSocketRecvMsg msg) { var playerId = (int)msg.readNext(); - var nextPos = (Matrix)msg.readNext(); + var nextPos = (TGCMatrix)msg.readNext(); if (otrosMeshes.ContainsKey(playerId)) { @@ -498,7 +484,7 @@ private void clienteAtenderActualizarUbicaciones(TgcSocketRecvMsg msg) private void clienteAtenderOtroClienteDesconectado(TgcSocketRecvMsg msg) { var playerId = (int)msg.readNext(); - otrosMeshes[playerId].dispose(); + otrosMeshes[playerId].Dispose(); otrosMeshes.Remove(playerId); } diff --git a/TGC.Examples/Optimization/PortalRenderingFramework.cs b/TGC.Examples/Optimization/PortalRenderingFramework.cs index 97fe5393..a61fc144 100644 --- a/TGC.Examples/Optimization/PortalRenderingFramework.cs +++ b/TGC.Examples/Optimization/PortalRenderingFramework.cs @@ -95,7 +95,7 @@ public override void Render() foreach (var mesh in scene.Meshes) { //Contador de modelos - if (mesh.Enabled && !mesh.AlphaBlendEnable) + if (mesh.Enabled && !mesh.AlphaBlend) { meshCount++; } @@ -109,7 +109,7 @@ public override void Render() foreach (var mesh in scene.Meshes) { //Contador de modelos - if (mesh.Enabled && mesh.AlphaBlendEnable) + if (mesh.Enabled && mesh.AlphaBlend) { meshCount++; } diff --git a/TGC.Examples/Others/EjemploDefault.cs b/TGC.Examples/Others/EjemploDefault.cs index e4444d01..648f35ea 100644 --- a/TGC.Examples/Others/EjemploDefault.cs +++ b/TGC.Examples/Others/EjemploDefault.cs @@ -38,7 +38,7 @@ public override void Init() //Cargar mesh var loader = new TgcSceneLoader(); mesh = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\LogoTGC\\LogoTGC-TgcScene.xml").Meshes[0]; - mesh.AutoTransformEnable = true; + mesh.AutoTransform = true; //Cargar Shader de PhongShading mesh.Effect = TgcShaders.Instance.TgcMeshPhongShader; @@ -70,7 +70,7 @@ public override void Render() { //BackgroundColor D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); - D3DDevice.Instance.Device.BeginScene(); + BeginScene(); ClearTextures(); //Cargar variables shader diff --git a/TGC.Examples/Quake3Loader/Q3ShaderParser.cs b/TGC.Examples/Quake3Loader/Q3ShaderParser.cs index a22c1a62..173107fb 100644 --- a/TGC.Examples/Quake3Loader/Q3ShaderParser.cs +++ b/TGC.Examples/Quake3Loader/Q3ShaderParser.cs @@ -909,7 +909,7 @@ private static List BuildEffectState(QShaderData shader, QShaderStage qs { var StateLines = new List(); - StateLines.Add("AlphaBlendEnable = " + qstage.HasBlendFunc.ToString().ToLower() + ";"); + StateLines.Add("AlphaBlend = " + qstage.HasBlendFunc.ToString().ToLower() + ";"); StateLines.Add("SrcBlend = " + GLtoDXBlend(qstage.BlendSrc) + ";"); StateLines.Add("DestBlend = " + GLtoDXBlend(qstage.BlendDest) + ";"); //StateLines.Add("ZWriteEnable = " + (!qstage.HasBlendFunc).ToString().ToLower() + ";"); diff --git a/TGC.Examples/Shaders/BumpMapping.fx b/TGC.Examples/Shaders/BumpMapping.fx index 16c1cb6e..33011223 100644 --- a/TGC.Examples/Shaders/BumpMapping.fx +++ b/TGC.Examples/Shaders/BumpMapping.fx @@ -18,24 +18,24 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Textura utilizada para BumpMapping texture texNormalMap; sampler2D normalMap = sampler_state { - Texture = (texNormalMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texNormalMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Material del mesh @@ -66,116 +66,116 @@ float reflection; //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float3 Tangent : TANGENT0; - float3 Binormal : BINORMAL0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float3 Tangent : TANGENT0; + float3 Binormal : BINORMAL0; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 WorldPosition : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; - float3 WorldTangent : TEXCOORD3; - float3 WorldBinormal : TEXCOORD4; - float3 LightVec : TEXCOORD5; - float3 HalfAngleVec : TEXCOORD6; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 WorldPosition : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; + float3 WorldTangent : TEXCOORD3; + float3 WorldBinormal : TEXCOORD4; + float3 LightVec : TEXCOORD5; + float3 HalfAngleVec : TEXCOORD6; }; //Vertex Shader VS_OUTPUT vs_general(VS_INPUT input) { - VS_OUTPUT output; + VS_OUTPUT output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Las Coordenadas de textura quedan igual - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; //Posicion pasada a World-Space - output.WorldPosition = mul(input.Position, matWorld).xyz; + output.WorldPosition = mul(input.Position, matWorld).xyz; //Pasar normal, tangent y binormal a World-Space - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; - output.WorldTangent = mul(input.Tangent, matInverseTransposeWorld).xyz; - output.WorldBinormal = mul(input.Binormal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldTangent = mul(input.Tangent, matInverseTransposeWorld).xyz; + output.WorldBinormal = mul(input.Binormal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - output.WorldPosition; + float3 viewVector = eyePosition.xyz - output.WorldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT { - float2 Texcoord : TEXCOORD0; - float3 WorldPosition : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; - float3 WorldTangent : TEXCOORD3; - float3 WorldBinormal : TEXCOORD4; - float3 LightVec : TEXCOORD5; - float3 HalfAngleVec : TEXCOORD6; + float2 Texcoord : TEXCOORD0; + float3 WorldPosition : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; + float3 WorldTangent : TEXCOORD3; + float3 WorldBinormal : TEXCOORD4; + float3 LightVec : TEXCOORD5; + float3 HalfAngleVec : TEXCOORD6; }; //Pixel Shader float4 ps_general(PS_INPUT input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); - float3 Tn = normalize(input.WorldTangent); - float3 Bn = normalize(input.WorldBinormal); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); + float3 Tn = normalize(input.WorldTangent); + float3 Bn = normalize(input.WorldBinormal); //Calcular intensidad de luz, con atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; - float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) //Obtener texel de la textura - float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); //Obtener normal de normalMap y ajustar rango de [0, 1] a [-1, 1] - float3 bumpNormal = tex2D(normalMap, input.Texcoord).rgb; - bumpNormal = (bumpNormal * 2.0f) - 1.0f; + float3 bumpNormal = tex2D(normalMap, input.Texcoord).rgb; + bumpNormal = (bumpNormal * 2.0f) - 1.0f; //Suavizar con bumpiness - bumpNormal = lerp(BUMP_SMOOTH, bumpNormal, bumpiness); + bumpNormal = lerp(BUMP_SMOOTH, bumpNormal, bumpiness); //Pasar de Tangent-Space a World-Space - bumpNormal = Nn + bumpNormal.x * Tn + bumpNormal.y * Bn; - bumpNormal = normalize(bumpNormal); + bumpNormal = Nn + bumpNormal.x * Tn + bumpNormal.y * Bn; + bumpNormal = normalize(bumpNormal); //Componente Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Componente Diffuse: N dot L, usando normal de NormalMap - float3 n_dot_l = dot(bumpNormal, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(bumpNormal, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp, usando normal de NormalMap - float3 n_dot_h = dot(bumpNormal, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(bumpNormal, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (intensity * lightColor * materialSpecularColor * pow(max(0.0, n_dot_h), materialSpecularExp)); /* Color final: modular (Emissive + Ambient + Diffuse) por el color de la textura, y luego sumar Specular. El color Alpha sale del diffuse material */ - float4 finalColor = float4((materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight, materialDiffuseColor.a); + float4 finalColor = float4((materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight, materialDiffuseColor.a); - return finalColor; + return finalColor; } /* @@ -183,9 +183,9 @@ float4 ps_general(PS_INPUT input) : COLOR0 */ technique BumpMappingTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_general(); - PixelShader = compile ps_2_0 ps_general(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_general(); + PixelShader = compile ps_3_0 ps_general(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/BumpMappingNoTangent.fx b/TGC.Examples/Shaders/BumpMappingNoTangent.fx index 279a2163..cb8b0ee1 100644 --- a/TGC.Examples/Shaders/BumpMappingNoTangent.fx +++ b/TGC.Examples/Shaders/BumpMappingNoTangent.fx @@ -5,32 +5,32 @@ float4x4 matWorldViewProjection; struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float2 Texcoord : TEXCOORD0; }; struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 ViewDirection : TEXCOORD1; - float3 LightDirection: TEXCOORD2; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 ViewDirection : TEXCOORD1; + float3 LightDirection : TEXCOORD2; }; VS_OUTPUT vs_main(VS_INPUT Input) { - VS_OUTPUT Output; + VS_OUTPUT Output; - Output.Position = mul(Input.Position, matWorldViewProjection); - Output.Texcoord = Input.Texcoord; + Output.Position = mul(Input.Position, matWorldViewProjection); + Output.Texcoord = Input.Texcoord; - float3 fvObjectPosition = mul(Input.Position, matWorld); + float3 fvObjectPosition = mul(Input.Position, matWorld); - Output.ViewDirection = normalize(fvEyePosition - fvObjectPosition); - Output.LightDirection = normalize(fvLightPosition - fvObjectPosition); + Output.ViewDirection = normalize(fvEyePosition - fvObjectPosition); + Output.LightDirection = normalize(fvLightPosition - fvObjectPosition); - return(Output); + return (Output); } float4 fvAmbient = float4(0.39, 0.49, 0.53, 1.00); @@ -41,48 +41,48 @@ float fSpecularPower = float(1.99); texture base_Tex; sampler2D baseMap = sampler_state { - Texture = (base_Tex); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (base_Tex); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; texture bump_Tex; sampler2D bumpMap = sampler_state { - Texture = (bump_Tex); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (bump_Tex); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; struct PS_INPUT { - float2 Texcoord : TEXCOORD0; - float3 ViewDirection : TEXCOORD1; - float3 LightDirection: TEXCOORD2; + float2 Texcoord : TEXCOORD0; + float3 ViewDirection : TEXCOORD1; + float3 LightDirection : TEXCOORD2; }; float4 ps_main(PS_INPUT Input) : COLOR0 { - float3 fvLightDirection = normalize(Input.LightDirection); - float3 fvNormal = mul(tex2D(bumpMap, Input.Texcoord), matWorld); - float fNDotL = clamp(dot(fvNormal, fvLightDirection), 0, 1); + float3 fvLightDirection = normalize(Input.LightDirection); + float3 fvNormal = mul(tex2D(bumpMap, Input.Texcoord), matWorld); + float fNDotL = clamp(dot(fvNormal, fvLightDirection), 0, 1); - float3 fvReflection = normalize(((2.0f * fvNormal) * (fNDotL)) - fvLightDirection); - float3 fvViewDirection = normalize(Input.ViewDirection); - float fRDotV = max(0.0f, dot(fvReflection, fvViewDirection)); + float3 fvReflection = normalize(((2.0f * fvNormal) * (fNDotL)) - fvLightDirection); + float3 fvViewDirection = normalize(Input.ViewDirection); + float fRDotV = max(0.0f, dot(fvReflection, fvViewDirection)); - float4 fvBaseColor = tex2D(baseMap, Input.Texcoord); + float4 fvBaseColor = tex2D(baseMap, Input.Texcoord); - float4 fvTotalAmbient = fvAmbient * fvBaseColor; - float4 fvTotalDiffuse = fvDiffuse * fNDotL * fvBaseColor; - float4 fvTotalSpecular = fvSpecular * pow(fRDotV, fSpecularPower); + float4 fvTotalAmbient = fvAmbient * fvBaseColor; + float4 fvTotalDiffuse = fvDiffuse * fNDotL * fvBaseColor; + float4 fvTotalSpecular = fvSpecular * pow(fRDotV, fSpecularPower); - return(saturate(fvTotalAmbient + fvTotalDiffuse + fvTotalSpecular)); + return (saturate(fvTotalAmbient + fvTotalDiffuse + fvTotalSpecular)); //return float4(fvNormal.xyz, 1); //return float4(Input.Texcoord.x, Input.Texcoord.y, 0,1) ; @@ -94,9 +94,9 @@ float4 ps_main(PS_INPUT Input) : COLOR0 //--------------------------------------------------------------// technique DefaultTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_main(); - PixelShader = compile ps_2_0 ps_main(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_main(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/Cel.fx b/TGC.Examples/Shaders/Cel.fx index 48cc3dbb..83ec85cf 100644 --- a/TGC.Examples/Shaders/Cel.fx +++ b/TGC.Examples/Shaders/Cel.fx @@ -1,66 +1,68 @@ //----------------------------------------------------------------------------- // Global variables //----------------------------------------------------------------------------- -float4x4 mWorldViewProj : WORLDVIEWPROJECTION; // World * View * Projection transformation -float4x4 mInvWorld: WORLDINVERSE; // Inverted world matrix -float3 mLightPos; // Light position +float4x4 mWorldViewProj : WORLDVIEWPROJECTION; // World * View * Projection transformation +float4x4 mInvWorld : WORLDINVERSE; // Inverted world matrix +float3 mLightPos; // Light position sampler2D tex0 : register(s0); sampler1D diffuseRamp : register(s1); struct VS_OUTPUT { - float4 Position: POSITION0; - float2 TexCoord: TEXCOORD0; - float2 diffuse: TEXCOORD1; + float4 Position : POSITION0; + float2 TexCoord : TEXCOORD0; + float2 diffuse : TEXCOORD1; }; VS_OUTPUT vertexMain( - float4 Position: POSITION0, + float4 Position : POSITION0, float2 TexCoord : TEXCOORD0, float2 diffuse : TEXCOORD1, float3 Normal : NORMAL0) { - VS_OUTPUT Output; + VS_OUTPUT Output; // calculate light vector - float3 N = normalize(Normal); - float3 L = normalize(mLightPos - Position.xyz); + float3 N = normalize(Normal); + float3 L = normalize(mLightPos - Position.xyz); // Calculate diffuse component - diffuse = max(dot(N, L), 0); + diffuse = max(dot(N, L), 0); // Shading offset - float offset = 0.1f; + float offset = 0.1f; //Subtract the offset and clamp the texture to 0 - diffuse = clamp(diffuse + offset, 0, 1); + diffuse = clamp(diffuse + offset, 0, 1); - Output.Position = mul(Position, mWorldViewProj); - Output.diffuse = diffuse; - Output.TexCoord = TexCoord; - return(Output); + Output.Position = mul(Position, mWorldViewProj); + Output.diffuse = diffuse; + Output.TexCoord = TexCoord; + return (Output); } float4 pixelMain( - float2 TexCoord: TEXCOORD0, + float2 TexCoord : TEXCOORD0, float2 diffuseIn : TEXCOORD1 ) : COLOR0 { - float4 color = float4(1,1,1,1); - float4 diffuse = float4(0.8f, 0.8f, 0.8f, 1.0f); + float4 color = float4(1, 1, 1, 1); + float4 diffuse = float4(0.8f, 0.8f, 0.8f, 1.0f); // Step functions from textures - diffuseIn = tex1D(diffuseRamp, diffuseIn.x).x; + diffuseIn = tex1D(diffuseRamp, diffuseIn.x).x; - color = (diffuse * diffuseIn.x); - float4 col = tex2D(tex0, TexCoord); - col *= 2; - return(color*col); + color = (diffuse * diffuseIn.x); + float4 col = tex2D(tex0, TexCoord); + col *= 2; + return (color * col); } -technique DefaultTechnique { - pass p0 { - CullMode = None; - VertexShader = compile vs_3_0 vertexMain(); - PixelShader = compile ps_3_0 pixelMain(); - } +technique DefaultTechnique +{ + pass p0 + { + CullMode = None; + VertexShader = compile vs_3_0 vertexMain(); + PixelShader = compile ps_3_0 pixelMain(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/DynamicLights.fx b/TGC.Examples/Shaders/DynamicLights.fx index 9ddb7cb8..2d0fd6c7 100644 --- a/TGC.Examples/Shaders/DynamicLights.fx +++ b/TGC.Examples/Shaders/DynamicLights.fx @@ -22,9 +22,10 @@ float lightIntensity; float lightAttenuation; //No vale para DirectionalLight //Estructura para guardar datos de la Luz -struct LightSampleValues { - float3 L; - float iL; +struct LightSampleValues +{ + float3 L; + float iL; }; /*-------------- DIRECTIONAL LIGHT ---------------*/ @@ -32,10 +33,10 @@ struct LightSampleValues { //Calcular valores de luz para Directional Light LightSampleValues computeDirLightValues() { - LightSampleValues values; - values.L = lightPosition.xyz; - values.iL = lightIntensity; - return values; + LightSampleValues values; + values.L = lightPosition.xyz; + values.iL = lightIntensity; + return values; } /*-------------- POINT LIGHT ---------------*/ @@ -43,16 +44,16 @@ LightSampleValues computeDirLightValues() //Calcular valores de luz para Point Light LightSampleValues computePointLightValues(in float4 surfacePosition) { - LightSampleValues values; - values.L = lightPosition.xyz - surfacePosition.xyz; - float dist = length(values.L); - values.L = values.L / dist; // normalize + LightSampleValues values; + values.L = lightPosition.xyz - surfacePosition.xyz; + float dist = length(values.L); + values.L = values.L / dist; // normalize //attenuation - float distAtten = dist * lightAttenuation; + float distAtten = dist * lightAttenuation; - values.iL = lightIntensity / distAtten; - return values; + values.iL = lightIntensity / distAtten; + return values; } /*-------------- SPOT LIGHT ---------------*/ @@ -65,20 +66,20 @@ float spotLightExponent; //Calcular valores de luz para Spot Light LightSampleValues computeSpotLightValues(in float4 surfacePosition) { - LightSampleValues values; - values.L = lightPosition.xyz - surfacePosition.xyz; - float dist = length(values.L); - values.L = values.L / dist; // normalize + LightSampleValues values; + values.L = lightPosition.xyz - surfacePosition.xyz; + float dist = length(values.L); + values.L = values.L / dist; // normalize //attenuation - float distAtten = dist * lightAttenuation; + float distAtten = dist * lightAttenuation; - float spotAtten = dot(-spotLightDir, values.L); - spotAtten = (spotAtten > spotLightAngleCos) + float spotAtten = dot(-spotLightDir, values.L); + spotAtten = (spotAtten > spotLightAngleCos) ? pow(spotAtten, spotLightExponent) : 0.0; - values.iL = lightIntensity * spotAtten / distAtten; - return values; + values.iL = lightIntensity * spotAtten / distAtten; + return values; } /*-------------- Calculo de componentes: AMBIENT, DIFFUSE y SPECULAR ---------------*/ @@ -86,21 +87,21 @@ LightSampleValues computeSpotLightValues(in float4 surfacePosition) //Calcular color RGB de Ambient float3 computeAmbientComponent(in LightSampleValues light) { - return light.iL * lightColor * materialAmbientColor; + return light.iL * lightColor * materialAmbientColor; } //Calcular color RGB de Diffuse float3 computeDiffuseComponent(in float3 surfaceNormal, in LightSampleValues light) { - return light.iL * lightColor * materialDiffuseColor.rgb * max(0.0, dot(surfaceNormal, light.L)); + return light.iL * lightColor * materialDiffuseColor.rgb * max(0.0, dot(surfaceNormal, light.L)); } //Calcular color RGB de Specular float3 computeSpecularComponent(in float3 surfaceNormal, in float4 surfacePosition, in LightSampleValues light) { - float3 viewVector = normalize(-surfacePosition.xyz); - float3 reflectionVector = 2.0 * dot(light.L, surfaceNormal) * surfaceNormal - light.L; - return (dot(surfaceNormal, light.L) <= 0.0) + float3 viewVector = normalize(-surfacePosition.xyz); + float3 reflectionVector = 2.0 * dot(light.L, surfaceNormal) * surfaceNormal - light.L; + return (dot(surfaceNormal, light.L) <= 0.0) ? float3(0.0, 0.0, 0.0) : ( light.iL * lightColor * materialSpecularColor @@ -111,88 +112,88 @@ float3 computeSpecularComponent(in float3 surfaceNormal, in float4 surfacePositi //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float4 lightingPosition : TEXCOORD1; - float3 lightingNormal : TEXCOORD2; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float4 lightingPosition : TEXCOORD1; + float3 lightingNormal : TEXCOORD2; }; //Vertex Shader VS_OUTPUT vs_general(VS_INPUT input) { - VS_OUTPUT output; + VS_OUTPUT output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Las Coordenadas de textura quedan igual - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; // The position and normal for lighting // must be in camera space, not homogeneous space //Almacenar la posicion del vertice en ViewSpace para ser usada luego por la luz - output.lightingPosition = mul(input.Position, matWorldView); + output.lightingPosition = mul(input.Position, matWorldView); //Almacenar la normal del vertice en ViewSpace para ser usada luego por la luz - output.lightingNormal = mul(input.Normal, matWorldView); + output.lightingNormal = mul(input.Normal, matWorldView); - return output; + return output; } //Textura utilizada por el Pixel Shader texture diffuseMap_Tex; sampler2D diffuseMap = sampler_state { - Texture = (diffuseMap_Tex); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (diffuseMap_Tex); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Input del Pixel Shader struct PS_INPUT { - float2 Texcoord : TEXCOORD0; - float4 lightingPosition : TEXCOORD1; - float3 lightingNormal : TEXCOORD2; + float2 Texcoord : TEXCOORD0; + float4 lightingPosition : TEXCOORD1; + float3 lightingNormal : TEXCOORD2; }; //Pixel Shader para Directional Light float4 directional_light_ps(PS_INPUT input) : COLOR0 { //Calcular datos de iluminacion para Directional Light - LightSampleValues light = computeDirLightValues(); + LightSampleValues light = computeDirLightValues(); -//Sumar Emissive + Ambient + Diffuse -float3 interpolatedNormal = normalize(input.lightingNormal); -float4 diffuseLighting; -diffuseLighting.rgb = materialEmissiveColor + computeAmbientComponent(light) + computeDiffuseComponent(interpolatedNormal, light); -diffuseLighting.a = materialDiffuseColor.a; + //Sumar Emissive + Ambient + Diffuse + float3 interpolatedNormal = normalize(input.lightingNormal); + float4 diffuseLighting; + diffuseLighting.rgb = materialEmissiveColor + computeAmbientComponent(light) + computeDiffuseComponent(interpolatedNormal, light); + diffuseLighting.a = materialDiffuseColor.a; -//Calcular Specular por separado -float4 specularLighting; -specularLighting.rgb = computeSpecularComponent(interpolatedNormal, input.lightingPosition, light); -specularLighting.a = 0; + //Calcular Specular por separado + float4 specularLighting; + specularLighting.rgb = computeSpecularComponent(interpolatedNormal, input.lightingPosition, light); + specularLighting.a = 0; -//Obtener texel de la textura -float4 texelColor = tex2D(diffuseMap, input.Texcoord); + //Obtener texel de la textura + float4 texelColor = tex2D(diffuseMap, input.Texcoord); -//Modular Diffuse con color de la textura y sumar luego Specular -float4 finalColor = diffuseLighting * texelColor + specularLighting; + //Modular Diffuse con color de la textura y sumar luego Specular + float4 finalColor = diffuseLighting * texelColor + specularLighting; -return finalColor; + return finalColor; } /* @@ -200,37 +201,37 @@ return finalColor; */ technique DirectionalLightTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_general(); - PixelShader = compile ps_2_0 directional_light_ps(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_general(); + PixelShader = compile ps_3_0 directional_light_ps(); + } } //Pixel Shader para Point Light float4 point_light_ps(PS_INPUT input) : COLOR0 { //Calcular datos de iluminacion para Directional Light - LightSampleValues light = computePointLightValues(input.lightingPosition); + LightSampleValues light = computePointLightValues(input.lightingPosition); -//Sumar Emissive + Ambient + Diffuse -float3 interpolatedNormal = normalize(input.lightingNormal); -float4 diffuseLighting; -diffuseLighting.rgb = materialEmissiveColor + computeAmbientComponent(light) + computeDiffuseComponent(interpolatedNormal, light); -diffuseLighting.a = materialDiffuseColor.a; + //Sumar Emissive + Ambient + Diffuse + float3 interpolatedNormal = normalize(input.lightingNormal); + float4 diffuseLighting; + diffuseLighting.rgb = materialEmissiveColor + computeAmbientComponent(light) + computeDiffuseComponent(interpolatedNormal, light); + diffuseLighting.a = materialDiffuseColor.a; -//Calcular Specular por separado -float4 specularLighting; -specularLighting.rgb = computeSpecularComponent(interpolatedNormal, input.lightingPosition, light); -specularLighting.a = 0; + //Calcular Specular por separado + float4 specularLighting; + specularLighting.rgb = computeSpecularComponent(interpolatedNormal, input.lightingPosition, light); + specularLighting.a = 0; -//Obtener texel de la textura -float4 texelColor = tex2D(diffuseMap, input.Texcoord); + //Obtener texel de la textura + float4 texelColor = tex2D(diffuseMap, input.Texcoord); -//Modular Diffuse con color de la textura y sumar luego Specular -float4 finalColor = diffuseLighting * texelColor + specularLighting; + //Modular Diffuse con color de la textura y sumar luego Specular + float4 finalColor = diffuseLighting * texelColor + specularLighting; -return finalColor; + return finalColor; } /* @@ -238,37 +239,37 @@ return finalColor; */ technique PointLightTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_general(); - PixelShader = compile ps_2_0 point_light_ps(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_general(); + PixelShader = compile ps_3_0 point_light_ps(); + } } //Pixel Shader para Spot Light float4 spot_light_ps(PS_INPUT input) : COLOR0 { //Calcular datos de iluminacion para Directional Light - LightSampleValues light = computeSpotLightValues(input.lightingPosition); + LightSampleValues light = computeSpotLightValues(input.lightingPosition); -//Sumar Emissive + Ambient + Diffuse -float3 interpolatedNormal = normalize(input.lightingNormal); -float4 diffuseLighting; -diffuseLighting.rgb = materialEmissiveColor + computeAmbientComponent(light) + computeDiffuseComponent(interpolatedNormal, light); -diffuseLighting.a = materialDiffuseColor.a; + //Sumar Emissive + Ambient + Diffuse + float3 interpolatedNormal = normalize(input.lightingNormal); + float4 diffuseLighting; + diffuseLighting.rgb = materialEmissiveColor + computeAmbientComponent(light) + computeDiffuseComponent(interpolatedNormal, light); + diffuseLighting.a = materialDiffuseColor.a; -//Calcular Specular por separado -float4 specularLighting; -specularLighting.rgb = computeSpecularComponent(interpolatedNormal, input.lightingPosition, light); -specularLighting.a = 0; + //Calcular Specular por separado + float4 specularLighting; + specularLighting.rgb = computeSpecularComponent(interpolatedNormal, input.lightingPosition, light); + specularLighting.a = 0; -//Obtener texel de la textura -float4 texelColor = tex2D(diffuseMap, input.Texcoord); + //Obtener texel de la textura + float4 texelColor = tex2D(diffuseMap, input.Texcoord); //Modular Diffuse con color de la textura y sumar luego Specular -float4 finalColor = diffuseLighting * texelColor + specularLighting; + float4 finalColor = diffuseLighting * texelColor + specularLighting; -return finalColor; + return finalColor; } /* @@ -276,45 +277,45 @@ return finalColor; */ technique SpotLightTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_general(); - PixelShader = compile ps_2_0 spot_light_ps(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_general(); + PixelShader = compile ps_3_0 spot_light_ps(); + } } //Output del Vertex Shader struct VS_OUTPUT_NO_LIGHT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; }; //Vertex Shader VS_OUTPUT_NO_LIGHT no_light_vs(VS_INPUT input) { - VS_OUTPUT_NO_LIGHT output; + VS_OUTPUT_NO_LIGHT output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Las Coordenadas de textura quedan igual - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_NO_LIGHT { - float2 Texcoord : TEXCOORD0; + float2 Texcoord : TEXCOORD0; }; //Pixel Shader sin luz float4 no_light_ps(PS_INPUT_NO_LIGHT input) : COLOR0 { //Obtener texel de la textura - return tex2D(diffuseMap, input.Texcoord); + return tex2D(diffuseMap, input.Texcoord); } /* @@ -322,9 +323,9 @@ float4 no_light_ps(PS_INPUT_NO_LIGHT input) : COLOR0 */ technique NoLightTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 no_light_vs(); - PixelShader = compile ps_2_0 no_light_ps(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 no_light_vs(); + PixelShader = compile ps_3_0 no_light_ps(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/Ejemplo1.fx b/TGC.Examples/Shaders/Ejemplo1.fx index fb71e809..8ca799d1 100644 --- a/TGC.Examples/Shaders/Ejemplo1.fx +++ b/TGC.Examples/Shaders/Ejemplo1.fx @@ -17,12 +17,12 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; float darkFactor; @@ -33,9 +33,9 @@ float textureOffset; struct VS_OUTPUT { - float4 Position : POSITION; - float4 Color : COLOR0; - float2 TexCoord : TEXCOORD0; + float4 Position : POSITION; + float4 Color : COLOR0; + float2 TexCoord : TEXCOORD0; }; VS_OUTPUT VS_main( @@ -45,13 +45,13 @@ VS_OUTPUT VS_main( float2 TexCoord : TEXCOORD0 ) { - VS_OUTPUT Out = (VS_OUTPUT)0; + VS_OUTPUT Out = (VS_OUTPUT) 0; - Out.Position = mul(Position, matWorldViewProj); - Out.Color = Color; - Out.TexCoord = TexCoord; + Out.Position = mul(Position, matWorldViewProj); + Out.Color = Color; + Out.TexCoord = TexCoord; - return Out; + return Out; } VS_OUTPUT VS_randomTexCoord( @@ -61,13 +61,13 @@ VS_OUTPUT VS_randomTexCoord( float2 TexCoord : TEXCOORD0 ) { - VS_OUTPUT Out = (VS_OUTPUT)0; + VS_OUTPUT Out = (VS_OUTPUT) 0; - Out.Position = mul(Position, matWorldViewProj); - Out.Color = Color; - Out.TexCoord = TexCoord + random; + Out.Position = mul(Position, matWorldViewProj); + Out.Color = Color; + Out.TexCoord = TexCoord + random; - return Out; + return Out; } VS_OUTPUT VS_randomColor( @@ -77,13 +77,13 @@ VS_OUTPUT VS_randomColor( float2 TexCoord : TEXCOORD0 ) { - VS_OUTPUT Out = (VS_OUTPUT)0; + VS_OUTPUT Out = (VS_OUTPUT) 0; - Out.Position = mul(Position, matWorldViewProj); - Out.Color = random; - Out.TexCoord = TexCoord; + Out.Position = mul(Position, matWorldViewProj); + Out.Color = random; + Out.TexCoord = TexCoord; - return Out; + return Out; } VS_OUTPUT VS_textureOffset( @@ -93,113 +93,131 @@ VS_OUTPUT VS_textureOffset( float2 TexCoord : TEXCOORD0 ) { - VS_OUTPUT Out = (VS_OUTPUT)0; + VS_OUTPUT Out = (VS_OUTPUT) 0; - Out.Position = mul(Position, matWorldViewProj); - Out.Color = random; - Out.TexCoord = TexCoord; - Out.TexCoord[0] += textureOffset; + Out.Position = mul(Position, matWorldViewProj); + Out.Color = random; + Out.TexCoord = TexCoord; + Out.TexCoord[0] += textureOffset; - return Out; + return Out; } /*********************************************** Pixel Shaders ***************************************************/ float4 PS_onlyColor(VS_OUTPUT In) : COLOR { - return In.Color; + return In.Color; } float4 PS_onlyTexture(VS_OUTPUT In) : COLOR { - return tex2D(diffuseMap, In.TexCoord); + return tex2D(diffuseMap, In.TexCoord); } float4 PS_darkening(VS_OUTPUT In) : COLOR { - return darkFactor * tex2D(diffuseMap, In.TexCoord); + return darkFactor * tex2D(diffuseMap, In.TexCoord); } float4 PS_complementing(VS_OUTPUT In) : COLOR { - return 1 - tex2D(diffuseMap, In.TexCoord); + return 1 - tex2D(diffuseMap, In.TexCoord); } float4 PS_maskRedOut(VS_OUTPUT In) : COLOR { - float4 outColor = tex2D(diffuseMap, In.TexCoord); - outColor.r = 0.0f; - return outColor; + float4 outColor = tex2D(diffuseMap, In.TexCoord); + outColor.r = 0.0f; + return outColor; } float4 PS_redOnly(VS_OUTPUT In) : COLOR { - float4 outColor = tex2D(diffuseMap, In.TexCoord); - outColor.bga = 0.0f; - return outColor; + float4 outColor = tex2D(diffuseMap, In.TexCoord); + outColor.bga = 0.0f; + return outColor; } /*********************************************** Techniques ***************************************************/ -technique OnlyTexture { - pass p0 { - VertexShader = compile vs_2_0 VS_main(); - PixelShader = compile ps_2_0 PS_onlyTexture(); - } +technique OnlyTexture +{ + pass p0 + { + VertexShader = compile vs_3_0 VS_main(); + PixelShader = compile ps_3_0 PS_onlyTexture(); + } } -technique OnlyColor { - pass p0 { - VertexShader = compile vs_2_0 VS_main(); - PixelShader = compile ps_2_0 PS_onlyColor(); - } +technique OnlyColor +{ + pass p0 + { + VertexShader = compile vs_3_0 VS_main(); + PixelShader = compile ps_3_0 PS_onlyColor(); + } } -technique Darkening { - pass p0 { - VertexShader = compile vs_2_0 VS_main(); - PixelShader = compile ps_2_0 PS_darkening(); - } +technique Darkening +{ + pass p0 + { + VertexShader = compile vs_3_0 VS_main(); + PixelShader = compile ps_3_0 PS_darkening(); + } } -technique Complementing { - pass p0 { - VertexShader = compile vs_2_0 VS_main(); - PixelShader = compile ps_2_0 PS_complementing(); - } +technique Complementing +{ + pass p0 + { + VertexShader = compile vs_3_0 VS_main(); + PixelShader = compile ps_3_0 PS_complementing(); + } } -technique MaskRedOut { - pass p0 { - VertexShader = compile vs_2_0 VS_main(); - PixelShader = compile ps_2_0 PS_maskRedOut(); - } +technique MaskRedOut +{ + pass p0 + { + VertexShader = compile vs_3_0 VS_main(); + PixelShader = compile ps_3_0 PS_maskRedOut(); + } } -technique RedOnly { - pass p0 { - VertexShader = compile vs_2_0 VS_main(); - PixelShader = compile ps_2_0 PS_redOnly(); - } +technique RedOnly +{ + pass p0 + { + VertexShader = compile vs_3_0 VS_main(); + PixelShader = compile ps_3_0 PS_redOnly(); + } } -technique RandomTexCoord { - pass p0 { - VertexShader = compile vs_2_0 VS_randomTexCoord(); - PixelShader = compile ps_2_0 PS_onlyTexture(); - } +technique RandomTexCoord +{ + pass p0 + { + VertexShader = compile vs_3_0 VS_randomTexCoord(); + PixelShader = compile ps_3_0 PS_onlyTexture(); + } } -technique RandomColorVS { - pass p0 { - VertexShader = compile vs_2_0 VS_randomColor(); - PixelShader = compile ps_2_0 PS_onlyColor(); - } +technique RandomColorVS +{ + pass p0 + { + VertexShader = compile vs_3_0 VS_randomColor(); + PixelShader = compile ps_3_0 PS_onlyColor(); + } } -technique TextureOffset { - pass p0 { - VertexShader = compile vs_2_0 VS_textureOffset(); - PixelShader = compile ps_2_0 PS_onlyTexture(); - } +technique TextureOffset +{ + pass p0 + { + VertexShader = compile vs_3_0 VS_textureOffset(); + PixelShader = compile ps_3_0 PS_onlyTexture(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/EjemploBoxDirectX.fx b/TGC.Examples/Shaders/EjemploBoxDirectX.fx index cc094829..c4da8b84 100644 --- a/TGC.Examples/Shaders/EjemploBoxDirectX.fx +++ b/TGC.Examples/Shaders/EjemploBoxDirectX.fx @@ -16,21 +16,21 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture tex0; sampler2D sampler0 = sampler_state { - Texture = (tex0); + Texture = (tex0); }; //Textura 1 texture tex1; sampler2D sampler1 = sampler_state { - Texture = (tex1); + Texture = (tex1); }; //Textura 2 texture tex2; sampler2D sampler2 = sampler_state { - Texture = (tex2); + Texture = (tex2); }; /**************************************************************************************/ @@ -40,79 +40,79 @@ sampler2D sampler2 = sampler_state //Input del Vertex Shader. Tiene que coincidir con el VertexDeclaration del ejemplo struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 texcoord0 : TEXCOORD0; - float2 texcoord1 : TEXCOORD1; - float2 texcoord2 : TEXCOORD2; - float3 auxValue1 : TEXCOORD3; - float3 auxValue2 : TEXCOORD4; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 texcoord0 : TEXCOORD0; + float2 texcoord1 : TEXCOORD1; + float2 texcoord2 : TEXCOORD2; + float3 auxValue1 : TEXCOORD3; + float3 auxValue2 : TEXCOORD4; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 texcoord0 : TEXCOORD0; - float2 texcoord1 : TEXCOORD1; - float2 texcoord2 : TEXCOORD2; - float3 auxValue1 : TEXCOORD3; - float3 auxValue2 : TEXCOORD4; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 texcoord0 : TEXCOORD0; + float2 texcoord1 : TEXCOORD1; + float2 texcoord2 : TEXCOORD2; + float3 auxValue1 : TEXCOORD3; + float3 auxValue2 : TEXCOORD4; }; //Vertex Shader VS_OUTPUT vs_EjemploBoxDirectX(VS_INPUT input) { - VS_OUTPUT output; + VS_OUTPUT output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); - output.Normal = mul(input.Normal, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); + output.Normal = mul(input.Normal, matWorldViewProj); //Enviar el resto de los valores directamente al pixel shader - output.Color = input.Color; - output.texcoord0 = input.texcoord0; - output.texcoord1 = input.texcoord1; - output.texcoord2 = input.texcoord2; - output.auxValue1 = input.auxValue1; - output.auxValue2 = input.auxValue2; - - return output; + output.Color = input.Color; + output.texcoord0 = input.texcoord0; + output.texcoord1 = input.texcoord1; + output.texcoord2 = input.texcoord2; + output.auxValue1 = input.auxValue1; + output.auxValue2 = input.auxValue2; + + return output; } //Input del Pixel Shader struct PS_INPUT { - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 texcoord0 : TEXCOORD0; - float2 texcoord1 : TEXCOORD1; - float2 texcoord2 : TEXCOORD2; - float3 auxValue1 : TEXCOORD3; - float3 auxValue2 : TEXCOORD4; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 texcoord0 : TEXCOORD0; + float2 texcoord1 : TEXCOORD1; + float2 texcoord2 : TEXCOORD2; + float3 auxValue1 : TEXCOORD3; + float3 auxValue2 : TEXCOORD4; }; //Pixel Shader float4 ps_EjemploBoxDirectX(PS_INPUT input) : COLOR0 { //Obtener texel de las 3 texturas (usamos cualquier uv) - float4 texel0 = tex2D(sampler0, input.texcoord0); - float4 texel1 = tex2D(sampler1, input.texcoord1); - float4 texel2 = tex2D(sampler2, input.texcoord2); + float4 texel0 = tex2D(sampler0, input.texcoord0); + float4 texel1 = tex2D(sampler1, input.texcoord1); + float4 texel2 = tex2D(sampler2, input.texcoord2); //return float4(input.Normal, 1); - return input.Color; + return input.Color; } //technique EjemploBoxDirectX technique EjemploBoxDirectX { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_EjemploBoxDirectX(); - PixelShader = compile ps_3_0 ps_EjemploBoxDirectX(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_EjemploBoxDirectX(); + PixelShader = compile ps_3_0 ps_EjemploBoxDirectX(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/EjemploGetZBuffer.fx b/TGC.Examples/Shaders/EjemploGetZBuffer.fx index 458007e8..3a8b28a5 100644 --- a/TGC.Examples/Shaders/EjemploGetZBuffer.fx +++ b/TGC.Examples/Shaders/EjemploGetZBuffer.fx @@ -24,12 +24,12 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; /**************************************************************************************/ @@ -39,45 +39,45 @@ sampler2D diffuseMap = sampler_state //Input del Vertex Shader struct VS_INPUT_GenerateZBuffer { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_GenerateZBuffer { - float4 Position : POSITION0; - float2 Depth : TEXCOORD0; + float4 Position : POSITION0; + float2 Depth : TEXCOORD0; }; //Vertex Shader VS_OUTPUT_GenerateZBuffer vs_GenerateZBuffer(VS_INPUT_GenerateZBuffer input) { - VS_OUTPUT_GenerateZBuffer output; + VS_OUTPUT_GenerateZBuffer output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Guardar Z y W proyectado para usar en el pixel shader - output.Depth.x = output.Position.z; - output.Depth.y = output.Position.w; + output.Depth.x = output.Position.z; + output.Depth.y = output.Position.w; - return output; + return output; } //Input del Pixel Shader struct PS_GenerateZBuffer { - float2 Depth: TEXCOORD0; + float2 Depth : TEXCOORD0; }; //Pixel Shader float4 ps_GenerateZBuffer(PS_GenerateZBuffer input) : COLOR0 { //Calcular depth como 1 - (Z / W) y grabar en la textura - return 1 - (input.Depth.x / input.Depth.y); + return 1 - (input.Depth.x / input.Depth.y); } /* @@ -85,11 +85,11 @@ float4 ps_GenerateZBuffer(PS_GenerateZBuffer input) : COLOR0 */ technique GenerateZBuffer { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_GenerateZBuffer(); - PixelShader = compile ps_2_0 ps_GenerateZBuffer(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_GenerateZBuffer(); + PixelShader = compile ps_3_0 ps_GenerateZBuffer(); + } } /**************************************************************************************/ @@ -103,75 +103,75 @@ float2 screenDimensions; texture texZBuffer; sampler2D zBuffer = sampler_state { - Texture = (texZBuffer); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texZBuffer); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Input del Vertex Shader struct VS_INPUT_AlterColorByDepth { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_AlterColorByDepth { - float4 Position : POSITION0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Vertex Shader VS_OUTPUT_AlterColorByDepth vs_AlterColorByDepth(VS_INPUT_AlterColorByDepth input) { - VS_OUTPUT_AlterColorByDepth output; + VS_OUTPUT_AlterColorByDepth output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; - return output; + return output; } //Input del Pixel Shader struct PS_AlterColorByDepth { - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float2 Pos2D: VPOS; //Esta variable te la otorga automaticamente el shader. Es la posicion en pantalla + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float2 Pos2D : VPOS; //Esta variable te la otorga automaticamente el shader. Es la posicion en pantalla }; //Pixel Shader float4 ps_AlterColorByDepth(PS_AlterColorByDepth input) : COLOR0 { //Obtener las coordenadas UV del ZBuffer. Son entre 0 y 1 entonces hay que dividir por las dimensiones de la pantalla - float2 zBufferUV = input.Pos2D / screenDimensions; + float2 zBufferUV = input.Pos2D / screenDimensions; //Obtener valor del zBuffer - float depth = tex2D(zBuffer, zBufferUV).r; + float depth = tex2D(zBuffer, zBufferUV).r; //Color tradicional del mesh - float4 meshColor = tex2D(diffuseMap, input.Texcoord); + float4 meshColor = tex2D(diffuseMap, input.Texcoord); //Variar color segun la distancia - float4 adaptedColor = meshColor * depth * 100; - adaptedColor.r = min(adaptedColor.r, meshColor.r); - adaptedColor.g = min(adaptedColor.g, meshColor.g); - adaptedColor.b = min(adaptedColor.b, meshColor.b); - adaptedColor.a = 1; - return adaptedColor; + float4 adaptedColor = meshColor * depth * 100; + adaptedColor.r = min(adaptedColor.r, meshColor.r); + adaptedColor.g = min(adaptedColor.g, meshColor.g); + adaptedColor.b = min(adaptedColor.b, meshColor.b); + adaptedColor.a = 1; + return adaptedColor; } /* @@ -179,9 +179,9 @@ float4 ps_AlterColorByDepth(PS_AlterColorByDepth input) : COLOR0 */ technique AlterColorByDepth { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_AlterColorByDepth(); - PixelShader = compile ps_3_0 ps_AlterColorByDepth(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_AlterColorByDepth(); + PixelShader = compile ps_3_0 ps_AlterColorByDepth(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/EnvironmentMap.fx b/TGC.Examples/Shaders/EnvironmentMap.fx index bc4ed8c6..9c8b479f 100644 --- a/TGC.Examples/Shaders/EnvironmentMap.fx +++ b/TGC.Examples/Shaders/EnvironmentMap.fx @@ -20,36 +20,36 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Textura utilizada para BumpMapping texture texNormalMap; sampler2D normalMap = sampler_state { - Texture = (texNormalMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texNormalMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Textura utilizada para EnvironmentMap texture texCubeMap; samplerCUBE cubeMap = sampler_state { - Texture = (texCubeMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texCubeMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Material del mesh @@ -80,105 +80,105 @@ float reflection; //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float3 Tangent : TANGENT0; - float3 Binormal : BINORMAL0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float3 Tangent : TANGENT0; + float3 Binormal : BINORMAL0; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD1; - float3 WorldPosition : TEXCOORD2; - float3 WorldNormal : TEXCOORD3; - float3 WorldTangent : TEXCOORD4; - float3 WorldBinormal : TEXCOORD5; - float3 LightVec : TEXCOORD6; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD1; + float3 WorldPosition : TEXCOORD2; + float3 WorldNormal : TEXCOORD3; + float3 WorldTangent : TEXCOORD4; + float3 WorldBinormal : TEXCOORD5; + float3 LightVec : TEXCOORD6; }; //Vertex Shader VS_OUTPUT vs_general(VS_INPUT input) { - VS_OUTPUT output; + VS_OUTPUT output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Las Coordenadas de textura quedan igual - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; //Posicion pasada a World-Space - output.WorldPosition = mul(input.Position, matWorld).xyz; + output.WorldPosition = mul(input.Position, matWorld).xyz; //Pasar normal, tangent y binormal a World-Space - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; - output.WorldTangent = mul(input.Tangent, matInverseTransposeWorld).xyz; - output.WorldBinormal = mul(input.Binormal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldTangent = mul(input.Tangent, matInverseTransposeWorld).xyz; + output.WorldBinormal = mul(input.Binormal, matInverseTransposeWorld).xyz; //Vector desde el vertice hacia la luz - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT { - float2 Texcoord : TEXCOORD1; - float3 WorldPosition : TEXCOORD2; - float3 WorldNormal : TEXCOORD3; - float3 WorldTangent : TEXCOORD4; - float3 WorldBinormal : TEXCOORD5; - float3 LightVec : TEXCOORD6; + float2 Texcoord : TEXCOORD1; + float3 WorldPosition : TEXCOORD2; + float3 WorldNormal : TEXCOORD3; + float3 WorldTangent : TEXCOORD4; + float3 WorldBinormal : TEXCOORD5; + float3 LightVec : TEXCOORD6; }; //Pixel Shader float4 ps_general(PS_INPUT input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Tn = normalize(input.WorldTangent); - float3 Bn = normalize(input.WorldBinormal); - float3 Ln = normalize(input.LightVec); + float3 Nn = normalize(input.WorldNormal); + float3 Tn = normalize(input.WorldTangent); + float3 Bn = normalize(input.WorldBinormal); + float3 Ln = normalize(input.LightVec); //Obtener texel de la textura - float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); //Obtener normal de normalMap y ajustar rango de [0, 1] a [-1, 1] - float3 bumpNormal = tex2D(normalMap, input.Texcoord).rgb; - bumpNormal = (bumpNormal * 2.0f) - 1.0f; + float3 bumpNormal = tex2D(normalMap, input.Texcoord).rgb; + bumpNormal = (bumpNormal * 2.0f) - 1.0f; //Suavizar con bumpiness - bumpNormal = lerp(BUMP_SMOOTH, bumpNormal, bumpiness); + bumpNormal = lerp(BUMP_SMOOTH, bumpNormal, bumpiness); //Pasar de Tangent-Space a World-Space - bumpNormal = Nn + bumpNormal.x * Tn + bumpNormal.y * Bn; - bumpNormal = normalize(bumpNormal); + bumpNormal = Nn + bumpNormal.x * Tn + bumpNormal.y * Bn; + bumpNormal = normalize(bumpNormal); //Obtener texel de CubeMap - float3 Vn = normalize(eyePosition.xyz - input.WorldPosition); - float3 R = reflect(Vn,Nn); - float3 reflectionColor = texCUBE(cubeMap, R).rgb; + float3 Vn = normalize(eyePosition.xyz - input.WorldPosition); + float3 R = reflect(Vn, Nn); + float3 reflectionColor = texCUBE(cubeMap, R).rgb; //Calcular intensidad de luz, con atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; - float intensity = lightIntensity / distAtten; + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float intensity = lightIntensity / distAtten; //Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Diffuse (N dot L, usando normal de NormalMap) - float3 n_dot_l = dot(bumpNormal, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); + float3 n_dot_l = dot(bumpNormal, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Specular (como vector de R se usa el HalfAngleVec) - float3 HalfAngleVec = normalize(Vn + Ln); - float3 n_dot_h = dot(bumpNormal, HalfAngleVec); - float3 specularLight = n_dot_l <= 0.0 + float3 HalfAngleVec = normalize(Vn + Ln); + float3 n_dot_h = dot(bumpNormal, HalfAngleVec); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : ( intensity * lightColor * materialSpecularColor @@ -187,11 +187,11 @@ float4 ps_general(PS_INPUT input) : COLOR0 //Color final: modular (Emissive + Ambient + Diffuse) por el color de la textura, y luego sumar Specular. //El color Alpha sale del diffuse material - float4 finalColor = float4((materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight + (texelColor * reflectionColor * reflection), materialDiffuseColor.a); + float4 finalColor = float4((materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight + (texelColor * reflectionColor * reflection), materialDiffuseColor.a); //float4 finalColor = float4(reflectionColor, materialDiffuseColor.a); - return finalColor; + return finalColor; } /* @@ -199,11 +199,11 @@ float4 ps_general(PS_INPUT input) : COLOR0 */ technique EnvironmentMapTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_general(); - PixelShader = compile ps_2_0 ps_general(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_general(); + PixelShader = compile ps_3_0 ps_general(); + } } /**************************************************************************************/ @@ -213,75 +213,75 @@ technique EnvironmentMapTechnique //Output del Vertex Shader struct VS_OUTPUT_SIMPLE { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD1; - float3 WorldPosition : TEXCOORD2; - float3 WorldNormal : TEXCOORD3; - float3 LightVec : TEXCOORD4; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD1; + float3 WorldPosition : TEXCOORD2; + float3 WorldNormal : TEXCOORD3; + float3 LightVec : TEXCOORD4; }; //Vertex Shader VS_OUTPUT_SIMPLE vs_simple(VS_INPUT input) { - VS_OUTPUT_SIMPLE output; + VS_OUTPUT_SIMPLE output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Las Coordenadas de textura quedan igual - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; //Posicion pasada a World-Space - output.WorldPosition = mul(input.Position, matWorld).xyz; + output.WorldPosition = mul(input.Position, matWorld).xyz; //Pasar normal a World-Space - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //Vector desde el vertice hacia la luz - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_SIMPLE { - float2 Texcoord : TEXCOORD1; - float3 WorldPosition : TEXCOORD2; - float3 WorldNormal : TEXCOORD3; - float3 LightVec : TEXCOORD4; + float2 Texcoord : TEXCOORD1; + float3 WorldPosition : TEXCOORD2; + float3 WorldNormal : TEXCOORD3; + float3 LightVec : TEXCOORD4; }; //Pixel Shader float4 ps_simple(PS_INPUT_SIMPLE input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); //Obtener texel de la textura - float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); //Obtener texel de CubeMap - float3 Vn = normalize(eyePosition.xyz - input.WorldPosition); - float3 R = reflect(Vn, Nn); - float3 reflectionColor = texCUBE(cubeMap, R).rgb; + float3 Vn = normalize(eyePosition.xyz - input.WorldPosition); + float3 R = reflect(Vn, Nn); + float3 reflectionColor = texCUBE(cubeMap, R).rgb; //Calcular intensidad de luz, con atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; - float intensity = lightIntensity / distAtten; + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float intensity = lightIntensity / distAtten; //Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Diffuse (N dot L, usando normal de NormalMap) - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Specular (como vector de R se usa el HalfAngleVec) - float3 HalfAngleVec = normalize(Vn + Ln); - float3 n_dot_h = dot(Nn, HalfAngleVec); - float3 specularLight = n_dot_l <= 0.0 + float3 HalfAngleVec = normalize(Vn + Ln); + float3 n_dot_h = dot(Nn, HalfAngleVec); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : ( intensity * lightColor * materialSpecularColor @@ -290,11 +290,11 @@ float4 ps_simple(PS_INPUT_SIMPLE input) : COLOR0 //Color final: modular (Emissive + Ambient + Diffuse) por el color de la textura, y luego sumar Specular. //El color Alpha sale del diffuse material - float4 finalColor = float4((materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight + (texelColor * reflectionColor * reflection), materialDiffuseColor.a); + float4 finalColor = float4((materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight + (texelColor * reflectionColor * reflection), materialDiffuseColor.a); //float4 finalColor = float4(reflectionColor, materialDiffuseColor.a); - return finalColor; + return finalColor; } /* @@ -302,9 +302,9 @@ float4 ps_simple(PS_INPUT_SIMPLE input) : COLOR0 */ technique SimpleEnvironmentMapTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_simple(); - PixelShader = compile ps_2_0 ps_simple(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_simple(); + PixelShader = compile ps_3_0 ps_simple(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/EnvironmentMap_Integrador2.fx b/TGC.Examples/Shaders/EnvironmentMap_Integrador2.fx index aed3f3de..6da11bce 100644 --- a/TGC.Examples/Shaders/EnvironmentMap_Integrador2.fx +++ b/TGC.Examples/Shaders/EnvironmentMap_Integrador2.fx @@ -16,36 +16,36 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Textura utilizada para BumpMapping texture texNormalMap; sampler2D normalMap = sampler_state { - Texture = (texNormalMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texNormalMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Textura utilizada para EnvironmentMap texture texCubeMap; samplerCUBE cubeMap = sampler_state { - Texture = (texCubeMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texCubeMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Material del mesh @@ -77,143 +77,143 @@ float reflection; //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float3 Tangent : TANGENT0; - float3 Binormal : BINORMAL0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float3 Tangent : TANGENT0; + float3 Binormal : BINORMAL0; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD1; - float3 WorldPosition : TEXCOORD2; - float3 WorldNormal : TEXCOORD3; - float3 WorldTangent : TEXCOORD4; - float3 WorldBinormal : TEXCOORD5; - float3 LightVec1 : TEXCOORD6; - float3 LightVec2 : TEXCOORD7; - float3 LightVec3 : TEXCOORD8; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD1; + float3 WorldPosition : TEXCOORD2; + float3 WorldNormal : TEXCOORD3; + float3 WorldTangent : TEXCOORD4; + float3 WorldBinormal : TEXCOORD5; + float3 LightVec1 : TEXCOORD6; + float3 LightVec2 : TEXCOORD7; + float3 LightVec3 : TEXCOORD8; }; //Vertex Shader VS_OUTPUT vs_general(VS_INPUT input) { - VS_OUTPUT output; + VS_OUTPUT output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Las Coordenadas de textura quedan igual - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; //Posicion pasada a World-Space - output.WorldPosition = mul(input.Position, matWorld).xyz; + output.WorldPosition = mul(input.Position, matWorld).xyz; //Pasar normal, tangent y binormal a World-Space - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; - output.WorldTangent = mul(input.Tangent, matInverseTransposeWorld).xyz; - output.WorldBinormal = mul(input.Binormal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldTangent = mul(input.Tangent, matInverseTransposeWorld).xyz; + output.WorldBinormal = mul(input.Binormal, matInverseTransposeWorld).xyz; //Vector desde el vertice hacia la luz - output.LightVec1 = lightPosition[0].xyz - output.WorldPosition; - output.LightVec2 = lightPosition[1].xyz - output.WorldPosition; - output.LightVec3 = lightPosition[2].xyz - output.WorldPosition; + output.LightVec1 = lightPosition[0].xyz - output.WorldPosition; + output.LightVec2 = lightPosition[1].xyz - output.WorldPosition; + output.LightVec3 = lightPosition[2].xyz - output.WorldPosition; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT { - float2 Texcoord : TEXCOORD1; - float3 WorldPosition : TEXCOORD2; - float3 WorldNormal : TEXCOORD3; - float3 WorldTangent : TEXCOORD4; - float3 WorldBinormal : TEXCOORD5; - float3 LightVec1 : TEXCOORD6; - float3 LightVec2 : TEXCOORD7; - float3 LightVec3 : TEXCOORD8; + float2 Texcoord : TEXCOORD1; + float3 WorldPosition : TEXCOORD2; + float3 WorldNormal : TEXCOORD3; + float3 WorldTangent : TEXCOORD4; + float3 WorldBinormal : TEXCOORD5; + float3 LightVec1 : TEXCOORD6; + float3 LightVec2 : TEXCOORD7; + float3 LightVec3 : TEXCOORD8; }; //Resultado de computo de lighting struct LightingResult { - float3 ambientLight; - float3 diffuseLight; - float3 specularLight; + float3 ambientLight; + float3 diffuseLight; + float3 specularLight; }; //Calcular colores para una luz LightingResult computeLighting(int i, float3 WorldPosition, float3 Ln, float3 surfaceNormal, float3 Vn) { - LightingResult res; + LightingResult res; //Calcular intensidad de luz, con atenuacion por distancia - float distAtten = length(lightPosition[i].xyz - WorldPosition) * lightAttenuation[i]; - float intensity = lightIntensity[i] / distAtten; + float distAtten = length(lightPosition[i].xyz - WorldPosition) * lightAttenuation[i]; + float intensity = lightIntensity[i] / distAtten; //Ambient - res.ambientLight = intensity * lightColor[i] * materialAmbientColor; + res.ambientLight = intensity * lightColor[i] * materialAmbientColor; //Diffuse (N dot L) - float3 n_dot_l = dot(surfaceNormal, Ln); - res.diffuseLight = intensity * lightColor[i] * materialDiffuseColor.rgb * max(0.0, n_dot_l); + float3 n_dot_l = dot(surfaceNormal, Ln); + res.diffuseLight = intensity * lightColor[i] * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Specular (como vector de R se usa el HalfAngleVec) - float3 HalfAngleVec = normalize(Vn + Ln); - float3 n_dot_h = dot(surfaceNormal, HalfAngleVec); - res.specularLight = n_dot_l <= 0.0 + float3 HalfAngleVec = normalize(Vn + Ln); + float3 n_dot_h = dot(surfaceNormal, HalfAngleVec); + res.specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : ( intensity * lightColor[i] * materialSpecularColor * pow(max(0.0, n_dot_h), materialSpecularExp) ); - return res; + return res; } //Pixel Shader float4 ps_general(PS_INPUT input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Tn = normalize(input.WorldTangent); - float3 Bn = normalize(input.WorldBinormal); - float3 Ln1 = normalize(input.LightVec1); - float3 Ln2 = normalize(input.LightVec2); - float3 Ln3 = normalize(input.LightVec3); + float3 Nn = normalize(input.WorldNormal); + float3 Tn = normalize(input.WorldTangent); + float3 Bn = normalize(input.WorldBinormal); + float3 Ln1 = normalize(input.LightVec1); + float3 Ln2 = normalize(input.LightVec2); + float3 Ln3 = normalize(input.LightVec3); //Obtener texel de la textura - float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); //Obtener normal de normalMap y ajustar rango de [0, 1] a [-1, 1] - float3 bumpNormal = tex2D(normalMap, input.Texcoord).rgb; - bumpNormal = (bumpNormal * 2.0f) - 1.0f; + float3 bumpNormal = tex2D(normalMap, input.Texcoord).rgb; + bumpNormal = (bumpNormal * 2.0f) - 1.0f; //Suavizar con bumpiness - bumpNormal = lerp(BUMP_SMOOTH, bumpNormal, bumpiness); + bumpNormal = lerp(BUMP_SMOOTH, bumpNormal, bumpiness); //Pasar de Tangent-Space a World-Space - bumpNormal = Nn + bumpNormal.x * Tn + bumpNormal.y * Bn; - bumpNormal = normalize(bumpNormal); + bumpNormal = Nn + bumpNormal.x * Tn + bumpNormal.y * Bn; + bumpNormal = normalize(bumpNormal); //Obtener texel de CubeMap - float3 Vn = normalize(eyePosition.xyz - input.WorldPosition); - float3 R = reflect(Vn,Nn); - float3 reflectionColor = texCUBE(cubeMap, R).rgb; + float3 Vn = normalize(eyePosition.xyz - input.WorldPosition); + float3 R = reflect(Vn, Nn); + float3 reflectionColor = texCUBE(cubeMap, R).rgb; //Calcular iluminacion para las 3 luces - LightingResult res1 = computeLighting(0, input.WorldPosition, Ln1, bumpNormal, Vn); - LightingResult res2 = computeLighting(1, input.WorldPosition, Ln2, bumpNormal, Vn); - LightingResult res3 = computeLighting(2, input.WorldPosition, Ln3, bumpNormal, Vn); + LightingResult res1 = computeLighting(0, input.WorldPosition, Ln1, bumpNormal, Vn); + LightingResult res2 = computeLighting(1, input.WorldPosition, Ln2, bumpNormal, Vn); + LightingResult res3 = computeLighting(2, input.WorldPosition, Ln3, bumpNormal, Vn); //Color final: modular (Emissive + Ambient + Diffuse) por el color de la textura, y luego sumar Specular. //El color Alpha sale del diffuse material - float4 finalColor = float4( + float4 finalColor = float4( saturate( materialEmissiveColor + (res1.ambientLight + res2.ambientLight + res3.ambientLight) + @@ -223,7 +223,7 @@ float4 ps_general(PS_INPUT input) : COLOR0 (texelColor * reflectionColor * reflection), materialDiffuseColor.a); - return finalColor; + return finalColor; } /* @@ -231,9 +231,9 @@ float4 ps_general(PS_INPUT input) : COLOR0 */ technique ThreeLightsTechnique { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_general(); - PixelShader = compile ps_3_0 ps_general(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_general(); + PixelShader = compile ps_3_0 ps_general(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/GaussianBlur.fx b/TGC.Examples/Shaders/GaussianBlur.fx index 8ca527d9..cde6d7c4 100644 --- a/TGC.Examples/Shaders/GaussianBlur.fx +++ b/TGC.Examples/Shaders/GaussianBlur.fx @@ -10,10 +10,10 @@ texture texSceneRT; sampler SceneRT = sampler_state { - Texture = (texSceneRT); - MipFilter = POINT; - MinFilter = POINT; - MagFilter = POINT; + Texture = (texSceneRT); + MipFilter = POINT; + MinFilter = POINT; + MagFilter = POINT; }; //Offsets y weights de Gaussian Blur @@ -28,50 +28,50 @@ float gauss_weights[MAX_SAMPLES]; //Input del Vertex Shader struct VS_INPUT_DEFAULT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_DEFAULT { - float4 Position : POSITION0; - float2 ScreenPos : TEXCOORD0; + float4 Position : POSITION0; + float2 ScreenPos : TEXCOORD0; }; //Vertex Shader VS_OUTPUT_DEFAULT vs_default(VS_INPUT_DEFAULT Input) { - VS_OUTPUT_DEFAULT Output; + VS_OUTPUT_DEFAULT Output; //Proyectar posicion - Output.Position = float4(Input.Position.xy, 0, 1); + Output.Position = float4(Input.Position.xy, 0, 1); //La coordenada de textura del quad es la posicion en 2D - Output.ScreenPos = Input.Texcoord; + Output.ScreenPos = Input.Texcoord; - return(Output); + return (Output); } //Input del Pixel Shader struct PS_INPUT_DEFAULT { - float2 ScreenPos : TEXCOORD0; + float2 ScreenPos : TEXCOORD0; }; //Pixel Shader float4 ps_default(PS_INPUT_DEFAULT Input) : COLOR0 { - return tex2D(SceneRT, Input.ScreenPos); + return tex2D(SceneRT, Input.ScreenPos); } technique DefaultTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_default(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_default(); + } } /**************************************************************************************/ @@ -81,27 +81,27 @@ technique DefaultTechnique //Pasada de GaussianBlur horizontal o vertical float4 ps_gaussian_blur_pass(PS_INPUT_DEFAULT Input) : COLOR0 { - float4 vSample = 0.0f; - float4 vColor = 0.0f; + float4 vSample = 0.0f; + float4 vColor = 0.0f; - float2 vSamplePosition; + float2 vSamplePosition; // Perform a one-directional gaussian blur - for (int iSample = 0; iSample < MAX_SAMPLES; iSample++) - { - vSamplePosition = Input.ScreenPos + gauss_offsets[iSample]; - vColor = tex2D(SceneRT, vSamplePosition); - vSample += gauss_weights[iSample] * vColor; - } - - return vSample; + for (int iSample = 0; iSample < MAX_SAMPLES; iSample++) + { + vSamplePosition = Input.ScreenPos + gauss_offsets[iSample]; + vColor = tex2D(SceneRT, vSamplePosition); + vSample += gauss_weights[iSample] * vColor; + } + + return vSample; } technique GaussianBlurPass { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_gaussian_blur_pass(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_gaussian_blur_pass(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/HDR.fx b/TGC.Examples/Shaders/HDR.fx index 47bc2e0d..ae690211 100644 --- a/TGC.Examples/Shaders/HDR.fx +++ b/TGC.Examples/Shaders/HDR.fx @@ -16,12 +16,12 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Parametros de la Luz @@ -44,40 +44,40 @@ static const float BRIGHT_PASS_OFFSET = 10.0f; texture texSceneRT; sampler SceneRT = sampler_state { - Texture = (texSceneRT); - MipFilter = POINT; - MinFilter = POINT; - MagFilter = POINT; + Texture = (texSceneRT); + MipFilter = POINT; + MinFilter = POINT; + MagFilter = POINT; }; //Textura de 1x1 con valor de Luminance de la escena texture texLuminanceRT; sampler LuminanceRT = sampler_state { - Texture = (texLuminanceRT); - MipFilter = POINT; - MinFilter = POINT; - MagFilter = POINT; + Texture = (texLuminanceRT); + MipFilter = POINT; + MinFilter = POINT; + MagFilter = POINT; }; //Textura de BrightPass texture texBrightPassRT; sampler BrightPassRT = sampler_state { - Texture = (texBrightPassRT); - MipFilter = POINT; - MinFilter = POINT; - MagFilter = POINT; + Texture = (texBrightPassRT); + MipFilter = POINT; + MinFilter = POINT; + MagFilter = POINT; }; //Textura de Bloom texture texBloomRT; sampler BloomRT = sampler_state { - Texture = (texBloomRT); - MipFilter = POINT; - MinFilter = POINT; - MagFilter = POINT; + Texture = (texBloomRT); + MipFilter = POINT; + MinFilter = POINT; + MagFilter = POINT; }; //Offsets y weights de Gaussian Blur @@ -98,92 +98,92 @@ float middleGray; //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 WorldPosition : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; - float3 LightVec : TEXCOORD3; - float3 ViewVec : TEXCOORD4; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 WorldPosition : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; + float3 LightVec : TEXCOORD3; + float3 ViewVec : TEXCOORD4; }; //Vertex Shader para render inicial del mesh VS_OUTPUT_DIFFUSE_MAP vs_LightPass(VS_INPUT_DIFFUSE_MAP input) { - VS_OUTPUT_DIFFUSE_MAP output; + VS_OUTPUT_DIFFUSE_MAP output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; //Posicion pasada a World-Space (necesaria para atenuación por distancia) - output.WorldPosition = mul(input.Position, matWorld); + output.WorldPosition = mul(input.Position, matWorld); /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. Usado en Specular - output.ViewVec = eyePosition.xyz - output.WorldPosition; + output.ViewVec = eyePosition.xyz - output.WorldPosition; - return output; + return output; } //Input del Pixel Shader struct PS_DIFFUSE_MAP { - float2 Texcoord : TEXCOORD0; - float3 WorldPosition : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; - float3 LightVec : TEXCOORD3; - float3 ViewVec : TEXCOORD4; + float2 Texcoord : TEXCOORD0; + float3 WorldPosition : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; + float3 LightVec : TEXCOORD3; + float3 ViewVec : TEXCOORD4; }; //Pixel Shader para render inicial del mesh float4 ps_LightPass(PS_DIFFUSE_MAP input) : COLOR0 { //Obtener texel de la textura - float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); //Alpha-test - if (texelColor.a < 0.1f) - { - discard; - } + if (texelColor.a < 0.1f) + { + discard; + } //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Vn = normalize(input.ViewVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Vn = normalize(input.ViewVec); //Componente Diffuse: N dot L - float n_dot_l = max(0.0, dot(Nn, Ln)); - float fDiffuse = saturate(n_dot_l); + float n_dot_l = max(0.0, dot(Nn, Ln)); + float fDiffuse = saturate(n_dot_l); //Componente Specular: (N dot H)^exp - float3 vReflection = reflect(-Ln, Nn); - float n_dot_h = max(0.0, dot(Vn, vReflection)); - float fSpecular = pow(saturate(n_dot_h), materialSpecularExp); + float3 vReflection = reflect(-Ln, Nn); + float n_dot_h = max(0.0, dot(Vn, vReflection)); + float fSpecular = pow(saturate(n_dot_h), materialSpecularExp); //Final color - float3 lightIntensityColor = float3(lightIntensity, lightIntensity, lightIntensity); - float4 finalColor = float4((materialAmbientColor + (fDiffuse + fSpecular) * lightIntensityColor) * texelColor.rgb, 1); + float3 lightIntensityColor = float3(lightIntensity, lightIntensity, lightIntensity); + float4 finalColor = float4((materialAmbientColor + (fDiffuse + fSpecular) * lightIntensityColor) * texelColor.rgb, 1); - return finalColor; + return finalColor; } /* @@ -191,11 +191,11 @@ float4 ps_LightPass(PS_DIFFUSE_MAP input) : COLOR0 */ technique LightPass { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_LightPass(); - PixelShader = compile ps_3_0 ps_LightPass(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_LightPass(); + PixelShader = compile ps_3_0 ps_LightPass(); + } } /**************************************************************************************/ @@ -206,14 +206,14 @@ technique LightPass float4 vs_DrawLightSource(float4 position : POSITION0) : POSITION0 { //Solo proyectar posicion - return mul(position, matWorldViewProj); + return mul(position, matWorldViewProj); } //Pixel Shader renderizar la fuente de luz float4 ps_DrawLightSource() : COLOR0 { //Solo devolvemos el color de la intensidad de la luz - return float4(lightIntensity, lightIntensity, lightIntensity, 1); + return float4(lightIntensity, lightIntensity, lightIntensity, 1); } /* @@ -221,11 +221,11 @@ float4 ps_DrawLightSource() : COLOR0 */ technique DrawLightSource { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_DrawLightSource(); - PixelShader = compile ps_3_0 ps_DrawLightSource(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_DrawLightSource(); + PixelShader = compile ps_3_0 ps_DrawLightSource(); + } } /**************************************************************************************/ @@ -235,45 +235,45 @@ technique DrawLightSource //Input del Vertex Shader struct VS_INPUT_DEFAULT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_DEFAULT { - float4 Position : POSITION0; - float2 ScreenPos : TEXCOORD0; + float4 Position : POSITION0; + float2 ScreenPos : TEXCOORD0; }; //Vertex Shader VS_OUTPUT_DEFAULT vs_default(VS_INPUT_DEFAULT Input) { - VS_OUTPUT_DEFAULT Output; - Output.Position = float4(Input.Position.xy, 0, 1); - Output.ScreenPos = Input.Texcoord; - return Output; + VS_OUTPUT_DEFAULT Output; + Output.Position = float4(Input.Position.xy, 0, 1); + Output.ScreenPos = Input.Texcoord; + return Output; } //Input del Pixel Shader struct PS_INPUT_DEFAULT { - float2 ScreenPos : TEXCOORD0; + float2 ScreenPos : TEXCOORD0; }; //Pixel Shader float4 ps_default(PS_INPUT_DEFAULT Input) : COLOR0 { - return tex2D(SceneRT, Input.ScreenPos); + return tex2D(SceneRT, Input.ScreenPos); } technique DefaultTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_default(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_default(); + } } /**************************************************************************************/ @@ -282,22 +282,22 @@ technique DefaultTechnique float4 ps_DownScale4x4(PS_INPUT_DEFAULT Input) : COLOR { - float4 sample = 0.0f; + float4 sample = 0.0f; - for (int i = 0; i < 16; i++) - { - sample += tex2D(SceneRT, Input.ScreenPos + sampleOffsets[i]); - } - return sample / 16; + for (int i = 0; i < 16; i++) + { + sample += tex2D(SceneRT, Input.ScreenPos + sampleOffsets[i]); + } + return sample / 16; } technique DownScale4x4 { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_DownScale4x4(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_DownScale4x4(); + } } /**************************************************************************************/ @@ -307,28 +307,28 @@ technique DownScale4x4 //Hacer un downsampling de 3x3 con un promedio de log(luminance) float4 ps_SampleLumInitial(PS_INPUT_DEFAULT Input) : COLOR { - float3 vSample = 0.0f; - float fLogLumSum = 0.0f; + float3 vSample = 0.0f; + float fLogLumSum = 0.0f; - for (int iSample = 0; iSample < 9; iSample++) - { + for (int iSample = 0; iSample < 9; iSample++) + { // Compute the sum of log(luminance) throughout the sample points - vSample = tex2D(SceneRT, Input.ScreenPos + sampleOffsets[iSample]); - fLogLumSum += log(dot(vSample, LUMINANCE_VECTOR) + 0.0001f); - } + vSample = tex2D(SceneRT, Input.ScreenPos + sampleOffsets[iSample]); + fLogLumSum += log(dot(vSample, LUMINANCE_VECTOR) + 0.0001f); + } // Divide the sum to complete the average - fLogLumSum /= 9; - return float4(fLogLumSum, fLogLumSum, fLogLumSum, 1.0f); + fLogLumSum /= 9; + return float4(fLogLumSum, fLogLumSum, fLogLumSum, 1.0f); } technique SampleAvgLuminance_Init { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_SampleLumInitial(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_SampleLumInitial(); + } } /**************************************************************************************/ @@ -338,26 +338,26 @@ technique SampleAvgLuminance_Init //Downsampling de 4x4 de luminance float4 ps_SampleLumIterative(PS_INPUT_DEFAULT Input) : COLOR { - float fResampleSum = 0.0f; + float fResampleSum = 0.0f; - for (int iSample = 0; iSample < 16; iSample++) - { + for (int iSample = 0; iSample < 16; iSample++) + { // Compute the sum of luminance throughout the sample points - fResampleSum += tex2D(SceneRT, Input.ScreenPos + sampleOffsets[iSample]); - } + fResampleSum += tex2D(SceneRT, Input.ScreenPos + sampleOffsets[iSample]); + } // Divide the sum to complete the average - fResampleSum /= 16; - return float4(fResampleSum, fResampleSum, fResampleSum, 1.0f); + fResampleSum /= 16; + return float4(fResampleSum, fResampleSum, fResampleSum, 1.0f); } technique SampleAvgLuminance_Intermediate { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_SampleLumIterative(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_SampleLumIterative(); + } } /**************************************************************************************/ @@ -367,27 +367,27 @@ technique SampleAvgLuminance_Intermediate //Downsampling de 4x4 final y le aplicamos exp al resultado para obtener el luminance promedio de toda la escena float4 ps_SampleLumFinal(PS_INPUT_DEFAULT Input) : COLOR { - float fResampleSum = 0.0f; + float fResampleSum = 0.0f; - for (int iSample = 0; iSample < 16; iSample++) - { + for (int iSample = 0; iSample < 16; iSample++) + { // Compute the sum of luminance throughout the sample points - fResampleSum += tex2D(SceneRT, Input.ScreenPos + sampleOffsets[iSample]); - } + fResampleSum += tex2D(SceneRT, Input.ScreenPos + sampleOffsets[iSample]); + } // Divide the sum to complete the average, and perform an exp() to complete // the average luminance calculation - fResampleSum = exp(fResampleSum / 16); - return float4(fResampleSum, fResampleSum, fResampleSum, 1.0f); + fResampleSum = exp(fResampleSum / 16); + return float4(fResampleSum, fResampleSum, fResampleSum, 1.0f); } technique SampleAvgLuminance_End { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_SampleLumFinal(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_SampleLumFinal(); + } } /**************************************************************************************/ @@ -397,33 +397,32 @@ technique SampleAvgLuminance_End //Quedarse con los pixels que superan un umbral de brillo float4 ps_BrightPassFilter(PS_INPUT_DEFAULT Input) : COLOR { - float4 vSample = tex2D(SceneRT, Input.ScreenPos); - float fAdaptedLum = tex2D(LuminanceRT, float2(0.5f, 0.5f)); + float4 vSample = tex2D(SceneRT, Input.ScreenPos); + float fAdaptedLum = tex2D(LuminanceRT, float2(0.5f, 0.5f)); // Determine what the pixel's value will be after tone-mapping occurs - vSample.rgb *= middleGray / (fAdaptedLum + 0.001f); + vSample.rgb *= middleGray / (fAdaptedLum + 0.001f); // Subtract out dark pixels - vSample.rgb -= BRIGHT_PASS_THRESHOLD; + vSample.rgb -= BRIGHT_PASS_THRESHOLD; // Clamp to 0 - vSample = max(vSample, 0.0f); + vSample = max(vSample, 0.0f); // Map the resulting value into the 0 to 1 range. Higher values for - // BRIGHT_PASS_OFFSET will isolate lights from illuminated scene - // objects. - vSample.rgb /= (BRIGHT_PASS_OFFSET + vSample); + // BRIGHT_PASS_OFFSET will isolate lights from illuminated scene objects. + vSample.rgb /= (BRIGHT_PASS_OFFSET + vSample); - return vSample; + return vSample; } technique BrightPass { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_BrightPassFilter(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_BrightPassFilter(); + } } /**************************************************************************************/ @@ -433,29 +432,29 @@ technique BrightPass //Pasada de GaussianBlur horizontal o vertical para generar efecto de Bloom float4 ps_bloom_pass(PS_INPUT_DEFAULT Input) : COLOR0 { - float4 vSample = 0.0f; - float4 vColor = 0.0f; + float4 vSample = 0.0f; + float4 vColor = 0.0f; - float2 vSamplePosition; + float2 vSamplePosition; // Perform a one-directional gaussian blur - for (int iSample = 0; iSample < MAX_SAMPLES; iSample++) - { - vSamplePosition = Input.ScreenPos + gauss_offsets[iSample]; - vColor = tex2D(BloomRT, vSamplePosition); - vSample += gauss_weights[iSample] * vColor; - } - - return vSample; + for (int iSample = 0; iSample < MAX_SAMPLES; iSample++) + { + vSamplePosition = Input.ScreenPos + gauss_offsets[iSample]; + vColor = tex2D(BloomRT, vSamplePosition); + vSample += gauss_weights[iSample] * vColor; + } + + return vSample; } technique BloomPass { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_bloom_pass(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_bloom_pass(); + } } /**************************************************************************************/ @@ -465,37 +464,37 @@ technique BloomPass //Juntar todo en el render final float4 ps_finalPass(PS_INPUT_DEFAULT Input, uniform float toneMapping) : COLOR0 { - float4 origColor = tex2D(SceneRT, Input.ScreenPos); - float4 bloomColor = tex2D(BloomRT, Input.ScreenPos); - float avgLum = tex2D(LuminanceRT, float2(0.5f, 0.5f)); + float4 origColor = tex2D(SceneRT, Input.ScreenPos); + float4 bloomColor = tex2D(BloomRT, Input.ScreenPos); + float avgLum = tex2D(LuminanceRT, float2(0.5f, 0.5f)); //Tone mapping - if (toneMapping > 0) - { - origColor.rgb *= middleGray / (avgLum + 0.001f); - origColor.rgb /= (1.0f + origColor); - } + if (toneMapping > 0) + { + origColor.rgb *= middleGray / (avgLum + 0.001f); + origColor.rgb /= (1.0f + origColor); + } //Bloom - origColor += bloomColor; + origColor += bloomColor; - return origColor; + return origColor; } technique FinalRender { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_finalPass(1); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_finalPass(1); + } } technique FinalRenderNoToneMapping { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_finalPass(0); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_finalPass(0); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/MultiDiffuseLights.fx b/TGC.Examples/Shaders/MultiDiffuseLights.fx index c43e971d..069d0f7e 100644 --- a/TGC.Examples/Shaders/MultiDiffuseLights.fx +++ b/TGC.Examples/Shaders/MultiDiffuseLights.fx @@ -21,19 +21,19 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Textura para Lightmap texture texLightMap; sampler2D lightMap = sampler_state { - Texture = (texLightMap); + Texture = (texLightMap); }; //Material del mesh @@ -53,89 +53,89 @@ float lightAttenuation[4]; //Factor de atenuacion de las 4 luces //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 WorldPosition : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 WorldPosition : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; }; //Vertex Shader VS_OUTPUT vs_general(VS_INPUT input) { - VS_OUTPUT output; + VS_OUTPUT output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; //Posicion pasada a World-Space (necesaria para atenuación por distancia) - output.WorldPosition = mul(input.Position, matWorld); + output.WorldPosition = mul(input.Position, matWorld); /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT { - float2 Texcoord : TEXCOORD0; - float3 WorldPosition : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; + float2 Texcoord : TEXCOORD0; + float3 WorldPosition : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; }; //Funcion para calcular color RGB de Diffuse float3 computeDiffuseComponent(float3 surfacePosition, float3 N, int i) { //Calcular intensidad de luz, con atenuacion por distancia - float distAtten = length(lightPosition[i].xyz - surfacePosition); - float3 Ln = (lightPosition[i].xyz - surfacePosition) / distAtten; - distAtten = distAtten * lightAttenuation[i]; - float intensity = lightIntensity[i] / distAtten; //Dividimos intensidad sobre distancia + float distAtten = length(lightPosition[i].xyz - surfacePosition); + float3 Ln = (lightPosition[i].xyz - surfacePosition) / distAtten; + distAtten = distAtten * lightAttenuation[i]; + float intensity = lightIntensity[i] / distAtten; //Dividimos intensidad sobre distancia //Calcular Diffuse (N dot L) - return intensity * lightColor[i].rgb * materialDiffuseColor * max(0.0, dot(N, Ln)); + return intensity * lightColor[i].rgb * materialDiffuseColor * max(0.0, dot(N, Ln)); } //Pixel Shader para Point Light float4 point_light_ps(PS_INPUT input) : COLOR0 { - float3 Nn = normalize(input.WorldNormal); + float3 Nn = normalize(input.WorldNormal); //Emissive + Diffuse de 4 luces PointLight - float3 diffuseLighting = materialEmissiveColor; + float3 diffuseLighting = materialEmissiveColor; //Diffuse 0 - diffuseLighting += computeDiffuseComponent(input.WorldPosition, Nn, 0); + diffuseLighting += computeDiffuseComponent(input.WorldPosition, Nn, 0); //Diffuse 1 - diffuseLighting += computeDiffuseComponent(input.WorldPosition, Nn, 1); + diffuseLighting += computeDiffuseComponent(input.WorldPosition, Nn, 1); //Diffuse 2 - diffuseLighting += computeDiffuseComponent(input.WorldPosition, Nn, 2); + diffuseLighting += computeDiffuseComponent(input.WorldPosition, Nn, 2); //Diffuse 3 - diffuseLighting += computeDiffuseComponent(input.WorldPosition, Nn, 3); + diffuseLighting += computeDiffuseComponent(input.WorldPosition, Nn, 3); //Obtener texel de la textura - float4 texelColor = tex2D(diffuseMap, input.Texcoord); - texelColor.rgb *= diffuseLighting; + float4 texelColor = tex2D(diffuseMap, input.Texcoord); + texelColor.rgb *= diffuseLighting; - return texelColor; + return texelColor; } /* @@ -143,9 +143,9 @@ float4 point_light_ps(PS_INPUT input) : COLOR0 */ technique MultiDiffuseLightsTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_general(); - PixelShader = compile ps_2_0 point_light_ps(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_general(); + PixelShader = compile ps_3_0 point_light_ps(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/PostProcess.fx b/TGC.Examples/Shaders/PostProcess.fx index 24438e40..e6ea2801 100644 --- a/TGC.Examples/Shaders/PostProcess.fx +++ b/TGC.Examples/Shaders/PostProcess.fx @@ -9,61 +9,61 @@ //Input del Vertex Shader struct VS_INPUT_DEFAULT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_DEFAULT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; }; //Vertex Shader VS_OUTPUT_DEFAULT vs_default(VS_INPUT_DEFAULT Input) { - VS_OUTPUT_DEFAULT Output; + VS_OUTPUT_DEFAULT Output; //Proyectar posicion - Output.Position = float4(Input.Position.xy, 0, 1); + Output.Position = float4(Input.Position.xy, 0, 1); //Las Texcoord quedan igual - Output.Texcoord = Input.Texcoord; + Output.Texcoord = Input.Texcoord; - return(Output); + return (Output); } //Textura del Render target 2D texture render_target2D; sampler RenderTarget = sampler_state { - Texture = (render_target2D); - MipFilter = NONE; - MinFilter = NONE; - MagFilter = NONE; + Texture = (render_target2D); + MipFilter = NONE; + MinFilter = NONE; + MagFilter = NONE; }; //Input del Pixel Shader struct PS_INPUT_DEFAULT { - float2 Texcoord : TEXCOORD0; + float2 Texcoord : TEXCOORD0; }; //Pixel Shader float4 ps_default(PS_INPUT_DEFAULT Input) : COLOR0 { - float4 color = tex2D(RenderTarget, Input.Texcoord); - return color; + float4 color = tex2D(RenderTarget, Input.Texcoord); + return color; } technique DefaultTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_default(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_default(); + } } /**************************************************************************************/ @@ -76,22 +76,22 @@ float scaleFactor = 1; float4 ps_oscurecer(PS_INPUT_DEFAULT Input) : COLOR0 { //Obtener color segun textura - float4 color = tex2D(RenderTarget, Input.Texcoord); + float4 color = tex2D(RenderTarget, Input.Texcoord); //Escalar el color para oscurecerlo - float value = ((color.r + color.g + color.b) / 3) * scaleFactor; - color.rgb = color.rgb * (1 - scaleFactor) + value * scaleFactor; + float value = ((color.r + color.g + color.b) / 3) * scaleFactor; + color.rgb = color.rgb * (1 - scaleFactor) + value * scaleFactor; - return color; + return color; } technique OscurecerTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_oscurecer(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_oscurecer(); + } } /**************************************************************************************/ @@ -104,29 +104,29 @@ float alarmaScaleFactor = 0.1; texture textura_alarma; sampler sampler_alarma = sampler_state { - Texture = (textura_alarma); + Texture = (textura_alarma); }; //Pixel Shader de Alarma float4 ps_alarma(PS_INPUT_DEFAULT Input) : COLOR0 { //Obtener color segun textura - float4 color = tex2D(RenderTarget, Input.Texcoord); + float4 color = tex2D(RenderTarget, Input.Texcoord); //Obtener color de textura de alarma, escalado por un factor - float4 color2 = tex2D(sampler_alarma, Input.Texcoord) * alarmaScaleFactor; + float4 color2 = tex2D(sampler_alarma, Input.Texcoord) * alarmaScaleFactor; //Mezclar ambos texels - return color + color2; + return color + color2; } technique AlarmaTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_alarma(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_alarma(); + } } /**************************************************************************************/ @@ -140,20 +140,20 @@ float ondas_size; float4 ps_ondas(PS_INPUT_DEFAULT Input) : COLOR0 { //Alterar coordenadas de textura - Input.Texcoord.y = Input.Texcoord.y + (sin(Input.Texcoord.x * ondas_vertical_length) * ondas_size); + Input.Texcoord.y = Input.Texcoord.y + (sin(Input.Texcoord.x * ondas_vertical_length) * ondas_size); -//Obtener color de textura -float4 color = tex2D(RenderTarget, Input.Texcoord); -return color; + //Obtener color de textura + float4 color = tex2D(RenderTarget, Input.Texcoord); + return color; } technique OndasTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_ondas(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_ondas(); + } } /**************************************************************************************/ @@ -166,24 +166,24 @@ float blur_intensity; float4 ps_blur(PS_INPUT_DEFAULT Input) : COLOR0 { //Obtener color de textura - float4 color = tex2D(RenderTarget, Input.Texcoord); + float4 color = tex2D(RenderTarget, Input.Texcoord); //Tomar samples adicionales de texels vecinos y sumarlos (formamos una cruz) - color += tex2D(RenderTarget, float2(Input.Texcoord.x + blur_intensity, Input.Texcoord.y)); - color += tex2D(RenderTarget, float2(Input.Texcoord.x - blur_intensity, Input.Texcoord.y)); - color += tex2D(RenderTarget, float2(Input.Texcoord.x, Input.Texcoord.y + blur_intensity)); - color += tex2D(RenderTarget, float2(Input.Texcoord.x, Input.Texcoord.y - blur_intensity)); + color += tex2D(RenderTarget, float2(Input.Texcoord.x + blur_intensity, Input.Texcoord.y)); + color += tex2D(RenderTarget, float2(Input.Texcoord.x - blur_intensity, Input.Texcoord.y)); + color += tex2D(RenderTarget, float2(Input.Texcoord.x, Input.Texcoord.y + blur_intensity)); + color += tex2D(RenderTarget, float2(Input.Texcoord.x, Input.Texcoord.y - blur_intensity)); //Promediar todos - color = color / 5; - return color; + color = color / 5; + return color; } technique BlurTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_default(); - PixelShader = compile ps_2_0 ps_blur(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_default(); + PixelShader = compile ps_3_0 ps_blur(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/TerrainEditor/EditableTerrain.fx b/TGC.Examples/Shaders/TerrainEditor/EditableTerrain.fx index 32942a63..45d2ff3f 100644 --- a/TGC.Examples/Shaders/TerrainEditor/EditableTerrain.fx +++ b/TGC.Examples/Shaders/TerrainEditor/EditableTerrain.fx @@ -12,27 +12,27 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Input del Vertex Shader struct VS_INPUT_PositionColoredTextured { - float4 Position : POSITION0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Input del Pixel Shader struct PS_INPUT_PositionColoredTextured { - float2 Texcoord : TEXCOORD0; - float4 Color: COLOR0; + float2 Texcoord : TEXCOORD0; + float4 Color : COLOR0; }; /**************************************************************************************/ @@ -42,32 +42,32 @@ struct PS_INPUT_PositionColoredTextured //Vertex Shader VS_INPUT_PositionColoredTextured vs_PositionColoredTextured(VS_INPUT_PositionColoredTextured input) { - VS_INPUT_PositionColoredTextured output; + VS_INPUT_PositionColoredTextured output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; - output.Color = input.Color; + output.Color = input.Color; - return output; + return output; } //Pixel Shader float4 ps_PositionColoredTextured(PS_INPUT_PositionColoredTextured input) : COLOR0 { - return tex2D(diffuseMap, input.Texcoord); + return tex2D(diffuseMap, input.Texcoord); } technique PositionColoredTextured { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_PositionColoredTextured(); - PixelShader = compile ps_2_0 ps_PositionColoredTextured(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_PositionColoredTextured(); + PixelShader = compile ps_3_0 ps_PositionColoredTextured(); + } } /**************************************************************************************/ @@ -83,13 +83,13 @@ float brushHardness; //Pixel Shader float4 ps_PositionColoredTexturedWithBrush(PS_INPUT_PositionColoredTextured input) : COLOR0 { - float4 color = tex2D(diffuseMap, input.Texcoord); - float alpha = input.Color[3]; + float4 color = tex2D(diffuseMap, input.Texcoord); + float alpha = input.Color[3]; - color = input.Color*alpha + color*(1 - alpha); - color[3] = 1; + color = input.Color * alpha + color * (1 - alpha); + color[3] = 1; - return color; + return color; } /**************************************************************************************/ @@ -97,50 +97,54 @@ float4 ps_PositionColoredTexturedWithBrush(PS_INPUT_PositionColoredTextured inpu /**************************************************************************************/ VS_INPUT_PositionColoredTextured vs_PositionColoredTexturedWithRoundBrush(VS_INPUT_PositionColoredTextured input) { - VS_INPUT_PositionColoredTextured output; + VS_INPUT_PositionColoredTextured output; - float brushRadius2 = pow(brushRadius, 2); - float brushInnerRadius2 = pow(brushRadius*(brushHardness / 100), 2); + float brushRadius2 = pow(brushRadius, 2); + float brushInnerRadius2 = pow(brushRadius * (brushHardness / 100), 2); - output.Position = mul(input.Position, matWorld); + output.Position = mul(input.Position, matWorld); //Coloreo el vertice de acuerdo a la posicion y radio del pincel - float dx = output.Position[0] - brushPosition[0]; - float dz = output.Position[2] - brushPosition[1]; - - float dl2 = dx*dx + dz*dz; - - if (dl2 <= brushInnerRadius2) { - if (brushHardness < 100) - { - float alpha = dl2 / brushInnerRadius2; - output.Color = brushColor1*(1 - alpha) + brushColor2*(alpha); - } - else output.Color = brushColor1; - } - else output.Color = brushColor2; + float dx = output.Position[0] - brushPosition[0]; + float dz = output.Position[2] - brushPosition[1]; + + float dl2 = dx * dx + dz * dz; + + if (dl2 <= brushInnerRadius2) + { + if (brushHardness < 100) + { + float alpha = dl2 / brushInnerRadius2; + output.Color = brushColor1 * (1 - alpha) + brushColor2 * (alpha); + } + else + output.Color = brushColor1; + } + else + output.Color = brushColor2; //Cuanto mas lejos se encuentra del centro, mas traslucido. - output.Color[3] = 0.9*(1 - (dl2 / brushRadius2)); + output.Color[3] = 0.9 * (1 - (dl2 / brushRadius2)); - if (output.Color[3] < 0) output.Color[3] = 0; + if (output.Color[3] < 0) + output.Color[3] = 0; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; - return output; + return output; } technique PositionColoredTexturedWithRoundBrush { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_PositionColoredTexturedWithRoundBrush(); - PixelShader = compile ps_2_0 ps_PositionColoredTexturedWithBrush(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_PositionColoredTexturedWithRoundBrush(); + PixelShader = compile ps_3_0 ps_PositionColoredTexturedWithBrush(); + } } /**************************************************************************************/ @@ -149,41 +153,45 @@ technique PositionColoredTexturedWithRoundBrush VS_INPUT_PositionColoredTextured vs_PositionColoredTexturedWithSquareBrush(VS_INPUT_PositionColoredTextured input) { - VS_INPUT_PositionColoredTextured output; + VS_INPUT_PositionColoredTextured output; - float brushInnerRadius = brushRadius*(brushHardness / 100); + float brushInnerRadius = brushRadius * (brushHardness / 100); //Aplicar escala y desplazamiento - output.Position = mul(input.Position, matWorld); + output.Position = mul(input.Position, matWorld); //Coloreo el vertice de acuerdo a la posicion y radio del pincel - float dx = output.Position[0] - brushPosition[0]; - float dz = output.Position[2] - brushPosition[1]; - float maxD = max(abs(dx), abs(dz)); - - if (maxD <= brushRadius) { - if (maxD < brushInnerRadius) output.Color = brushColor1; - else output.Color = brushColor2; - - output.Color[3] = 0.35; - } - else output.Color[3] = 0; + float dx = output.Position[0] - brushPosition[0]; + float dz = output.Position[2] - brushPosition[1]; + float maxD = max(abs(dx), abs(dz)); + + if (maxD <= brushRadius) + { + if (maxD < brushInnerRadius) + output.Color = brushColor1; + else + output.Color = brushColor2; + + output.Color[3] = 0.35; + } + else + output.Color[3] = 0; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; - return output; + return output; } technique PositionColoredTexturedWithSquareBrush { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_PositionColoredTexturedWithSquareBrush(); - PixelShader = compile ps_2_0 ps_PositionColoredTexturedWithBrush(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_PositionColoredTexturedWithSquareBrush(); + PixelShader = compile ps_3_0 ps_PositionColoredTexturedWithBrush(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/TgcViewer/TgcFogShader.fx b/TGC.Examples/Shaders/TgcViewer/TgcFogShader.fx index 8fdc38d9..2e2470d2 100644 --- a/TGC.Examples/Shaders/TgcViewer/TgcFogShader.fx +++ b/TGC.Examples/Shaders/TgcViewer/TgcFogShader.fx @@ -12,12 +12,12 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; // variable de fogs @@ -30,67 +30,68 @@ float Density; //Input del Vertex Shader struct VS_INPUT_VERTEX { - float4 Position : POSITION0; - float3 Texture : TEXCOORD0; + float4 Position : POSITION0; + float3 Texture : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_VERTEX { - float4 Position : POSITION0; - float2 Texture: TEXCOORD0; - float4 PosView: COLOR0; + float4 Position : POSITION0; + float2 Texture : TEXCOORD0; + float4 PosView : COLOR0; }; //Vertex Shader VS_OUTPUT_VERTEX vs_main(VS_INPUT_VERTEX input) { - VS_OUTPUT_VERTEX output; + VS_OUTPUT_VERTEX output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); - output.Texture = input.Texture; - output.PosView = mul(input.Position, matWorldView); - return output; + output.Position = mul(input.Position, matWorldViewProj); + output.Texture = input.Texture; + output.PosView = mul(input.Position, matWorldView); + return output; } //Input del Pixel Shader struct PS_INPUT_PIXEL { - float2 Texture: TEXCOORD0; - float1 Fog: FOG; + float2 Texture : TEXCOORD0; + float1 Fog : FOG; }; //Pixel Shader - float4 ps_main(VS_OUTPUT_VERTEX input) : COLOR0 { - float zn = StartFogDistance; - float zf = EndFogDistance; + float zn = StartFogDistance; + float zf = EndFogDistance; - float4 fvBaseColor = tex2D(diffuseMap, input.Texture); - if (input.PosView.z < zn) - return fvBaseColor; - else if (input.PosView.z > zf) { - fvBaseColor = ColorFog; - return fvBaseColor; - } - else { + float4 fvBaseColor = tex2D(diffuseMap, input.Texture); + if (input.PosView.z < zn) + return fvBaseColor; + else if (input.PosView.z > zf) + { + fvBaseColor = ColorFog; + return fvBaseColor; + } + else + { // combino fog y textura - float1 total = zf - zn; - float1 resto = input.PosView.z - zn; - float1 proporcion = resto / total; - fvBaseColor = lerp(fvBaseColor, ColorFog, proporcion); - return fvBaseColor; - } + float1 total = zf - zn; + float1 resto = input.PosView.z - zn; + float1 proporcion = resto / total; + fvBaseColor = lerp(fvBaseColor, ColorFog, proporcion); + return fvBaseColor; + } } // ------------------------------------------------------------------ technique RenderScene { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_main(); - PixelShader = compile ps_3_0 ps_main(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_main(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/TgcViewer/TgcKeyFrameMeshShader.fx b/TGC.Examples/Shaders/TgcViewer/TgcKeyFrameMeshShader.fx index b600bd62..72d8d73e 100644 --- a/TGC.Examples/Shaders/TgcViewer/TgcKeyFrameMeshShader.fx +++ b/TGC.Examples/Shaders/TgcViewer/TgcKeyFrameMeshShader.fx @@ -19,12 +19,12 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; /**************************************************************************************/ @@ -34,41 +34,41 @@ sampler2D diffuseMap = sampler_state //Input del Vertex Shader struct VS_INPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float4 Color : COLOR; + float4 Position : POSITION0; + float4 Color : COLOR; }; //Output del Vertex Shader struct VS_OUTPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float4 Color : COLOR; + float4 Position : POSITION0; + float4 Color : COLOR; }; //Vertex Shader VS_OUTPUT_VERTEX_COLOR vs_VertexColor(VS_INPUT_VERTEX_COLOR input) { - VS_OUTPUT_VERTEX_COLOR output; + VS_OUTPUT_VERTEX_COLOR output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_VERTEX_COLOR { - float4 Color : COLOR0; + float4 Color : COLOR0; }; //Pixel Shader float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 { - return input.Color; + return input.Color; } /* @@ -76,11 +76,11 @@ float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 */ technique VERTEX_COLOR { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_VertexColor(); - PixelShader = compile ps_2_0 ps_VertexColor(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_VertexColor(); + PixelShader = compile ps_3_0 ps_VertexColor(); + } } /**************************************************************************************/ @@ -90,48 +90,48 @@ technique VERTEX_COLOR //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP vs_DiffuseMap(VS_INPUT_DIFFUSE_MAP input) { - VS_OUTPUT_DIFFUSE_MAP output; + VS_OUTPUT_DIFFUSE_MAP output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; - return output; + return output; } //Input del Pixel Shader struct PS_DIFFUSE_MAP { - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Pixel Shader float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 { //Modular color de la textura por color del mesh - return tex2D(diffuseMap, input.Texcoord) * input.Color; + return tex2D(diffuseMap, input.Texcoord) * input.Color; } /* @@ -139,9 +139,9 @@ float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 */ technique DIFFUSE_MAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_DiffuseMap(); - PixelShader = compile ps_2_0 ps_DiffuseMap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_DiffuseMap(); + PixelShader = compile ps_3_0 ps_DiffuseMap(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/TgcViewer/TgcMeshPhongShader.fx b/TGC.Examples/Shaders/TgcViewer/TgcMeshPhongShader.fx index fd9d05a2..e4c056ab 100644 --- a/TGC.Examples/Shaders/TgcViewer/TgcMeshPhongShader.fx +++ b/TGC.Examples/Shaders/TgcViewer/TgcMeshPhongShader.fx @@ -20,19 +20,19 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Textura para Lightmap texture texLightMap; sampler2D lightMap = sampler_state { - Texture = (texLightMap); + Texture = (texLightMap); }; //Parametros de la Luz @@ -50,81 +50,81 @@ float4 eyePosition; //Posicion de la camara //Input del Vertex Shader struct VS_INPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; }; //Output del Vertex Shader struct VS_OUTPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float4 Color : COLOR; - float3 WorldNormal : TEXCOORD0; - float3 LightVec : TEXCOORD1; - float3 HalfAngleVec : TEXCOORD2; + float4 Position : POSITION0; + float4 Color : COLOR; + float3 WorldNormal : TEXCOORD0; + float3 LightVec : TEXCOORD1; + float3 HalfAngleVec : TEXCOORD2; }; //Vertex Shader VS_OUTPUT_VERTEX_COLOR vs_VertexColor(VS_INPUT_VERTEX_COLOR input) { - VS_OUTPUT_VERTEX_COLOR output; + VS_OUTPUT_VERTEX_COLOR output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - float3 worldPosition = mul(input.Position, matWorld); - output.LightVec = lightPosition.xyz - worldPosition; + float3 worldPosition = mul(input.Position, matWorld); + output.LightVec = lightPosition.xyz - worldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - worldPosition; + float3 viewVector = eyePosition.xyz - worldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_VERTEX_COLOR { - float4 Color : COLOR0; - float3 WorldNormal : TEXCOORD0; - float3 LightVec : TEXCOORD1; - float3 HalfAngleVec : TEXCOORD2; + float4 Color : COLOR0; + float3 WorldNormal : TEXCOORD0; + float3 LightVec : TEXCOORD1; + float3 HalfAngleVec : TEXCOORD2; }; //Pixel Shader float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = diffuseColor * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = diffuseColor * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (specularColor * pow(max(0.0, n_dot_h), specularExp)); //Color final: modular (Ambient + Diffuse) por el color del mesh, y luego sumar Specular. - float4 finalColor = float4(saturate(ambientColor + diffuseLight) * input.Color.rgb + specularLight , input.Color.a); + float4 finalColor = float4(saturate(ambientColor + diffuseLight) * input.Color.rgb + specularLight, input.Color.a); - return finalColor; + return finalColor; } /* @@ -132,11 +132,11 @@ float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 */ technique VERTEX_COLOR { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_VertexColor(); - PixelShader = compile ps_2_0 ps_VertexColor(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_VertexColor(); + PixelShader = compile ps_3_0 ps_VertexColor(); + } } /**************************************************************************************/ @@ -146,85 +146,85 @@ technique VERTEX_COLOR //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 WorldNormal : TEXCOORD1; - float3 LightVec : TEXCOORD2; - float3 HalfAngleVec : TEXCOORD3; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 WorldNormal : TEXCOORD1; + float3 LightVec : TEXCOORD2; + float3 HalfAngleVec : TEXCOORD3; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP vs_DiffuseMap(VS_INPUT_DIFFUSE_MAP input) { - VS_OUTPUT_DIFFUSE_MAP output; + VS_OUTPUT_DIFFUSE_MAP output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - float3 worldPosition = mul(input.Position, matWorld); - output.LightVec = lightPosition.xyz - worldPosition; + float3 worldPosition = mul(input.Position, matWorld); + output.LightVec = lightPosition.xyz - worldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - worldPosition; + float3 viewVector = eyePosition.xyz - worldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_DIFFUSE_MAP { - float2 Texcoord : TEXCOORD0; - float3 WorldNormal : TEXCOORD1; - float3 LightVec : TEXCOORD2; - float3 HalfAngleVec : TEXCOORD3; + float2 Texcoord : TEXCOORD0; + float3 WorldNormal : TEXCOORD1; + float3 LightVec : TEXCOORD2; + float3 HalfAngleVec : TEXCOORD3; }; //Pixel Shader float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Obtener texel de la textura - float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = diffuseColor * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = diffuseColor * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : specularColor * pow(max(0.0, n_dot_h), specularExp); //Color final: modular (Ambient + Diffuse) por el color de la textura, y luego sumar Specular. - float4 finalColor = float4(saturate(ambientColor + diffuseLight) * texelColor + specularLight, texelColor.a); + float4 finalColor = float4(saturate(ambientColor + diffuseLight) * texelColor + specularLight, texelColor.a); - return finalColor; + return finalColor; } /* @@ -232,11 +232,11 @@ float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 */ technique DIFFUSE_MAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_DiffuseMap(); - PixelShader = compile ps_2_0 ps_DiffuseMap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_DiffuseMap(); + PixelShader = compile ps_3_0 ps_DiffuseMap(); + } } /**************************************************************************************/ @@ -246,98 +246,98 @@ technique DIFFUSE_MAP //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; - float3 LightVec : TEXCOORD3; - float3 HalfAngleVec : TEXCOORD4; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; + float3 LightVec : TEXCOORD3; + float3 HalfAngleVec : TEXCOORD4; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP vs_diffuseMapAndLightmap(VS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP input) { - VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP output; + VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; - output.TexcoordLightmap = input.TexcoordLightmap; + output.Texcoord = input.Texcoord; + output.TexcoordLightmap = input.TexcoordLightmap; /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - float3 worldPosition = mul(input.Position, matWorld); - output.LightVec = lightPosition.xyz - worldPosition; + float3 worldPosition = mul(input.Position, matWorld); + output.LightVec = lightPosition.xyz - worldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - worldPosition; + float3 viewVector = eyePosition.xyz - worldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; - float3 LightVec : TEXCOORD3; - float3 HalfAngleVec : TEXCOORD4; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; + float3 LightVec : TEXCOORD3; + float3 HalfAngleVec : TEXCOORD4; }; //Pixel Shader float4 ps_diffuseMapAndLightmap(PS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Obtener color de diffuseMap y de Lightmap - float4 texelColor = tex2D(diffuseMap, input.Texcoord); - float4 lightmapColor = tex2D(lightMap, input.TexcoordLightmap); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 lightmapColor = tex2D(lightMap, input.TexcoordLightmap); //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = diffuseColor * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = diffuseColor * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (specularColor * pow(max(0.0, n_dot_h), specularExp)); //Color final: modular (Ambient + Diffuse) por el color de la textura, y luego sumar Specular. - float4 finalColor = float4(saturate(ambientColor + diffuseLight) * (texelColor * lightmapColor) + specularLight, texelColor.a); + float4 finalColor = float4(saturate(ambientColor + diffuseLight) * (texelColor * lightmapColor) + specularLight, texelColor.a); - return finalColor; + return finalColor; } //technique DIFFUSE_MAP_AND_LIGHTMAP technique DIFFUSE_MAP_AND_LIGHTMAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_diffuseMapAndLightmap(); - PixelShader = compile ps_2_0 ps_diffuseMapAndLightmap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_diffuseMapAndLightmap(); + PixelShader = compile ps_3_0 ps_diffuseMapAndLightmap(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/TgcViewer/TgcMeshPointLightShader.fx b/TGC.Examples/Shaders/TgcViewer/TgcMeshPointLightShader.fx index eac8aa3a..38d8d06c 100644 --- a/TGC.Examples/Shaders/TgcViewer/TgcMeshPointLightShader.fx +++ b/TGC.Examples/Shaders/TgcViewer/TgcMeshPointLightShader.fx @@ -21,19 +21,19 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Textura para Lightmap texture texLightMap; sampler2D lightMap = sampler_state { - Texture = (texLightMap); + Texture = (texLightMap); }; //Material del mesh @@ -57,93 +57,93 @@ float lightAttenuation; //Factor de atenuacion de la luz //Input del Vertex Shader struct VS_INPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; }; //Output del Vertex Shader struct VS_OUTPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float4 Color : COLOR; - float3 WorldPosition : TEXCOORD0; - float3 WorldNormal : TEXCOORD1; - float3 LightVec : TEXCOORD2; - float3 HalfAngleVec : TEXCOORD3; + float4 Position : POSITION0; + float4 Color : COLOR; + float3 WorldPosition : TEXCOORD0; + float3 WorldNormal : TEXCOORD1; + float3 LightVec : TEXCOORD2; + float3 HalfAngleVec : TEXCOORD3; }; //Vertex Shader VS_OUTPUT_VERTEX_COLOR vs_VertexColor(VS_INPUT_VERTEX_COLOR input) { - VS_OUTPUT_VERTEX_COLOR output; + VS_OUTPUT_VERTEX_COLOR output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; //Posicion pasada a World-Space (necesaria para atenuación por distancia) - output.WorldPosition = mul(input.Position, matWorld); + output.WorldPosition = mul(input.Position, matWorld); /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - output.WorldPosition; + float3 viewVector = eyePosition.xyz - output.WorldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_VERTEX_COLOR { - float4 Color : COLOR0; - float3 WorldPosition : TEXCOORD0; - float3 WorldNormal : TEXCOORD1; - float3 LightVec : TEXCOORD2; - float3 HalfAngleVec : TEXCOORD3; + float4 Color : COLOR0; + float3 WorldPosition : TEXCOORD0; + float3 WorldNormal : TEXCOORD1; + float3 LightVec : TEXCOORD2; + float3 HalfAngleVec : TEXCOORD3; }; //Pixel Shader float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Calcular intensidad de luz, con atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; - float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) //Componente Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (intensity * lightColor * materialSpecularColor * pow(max(0.0, n_dot_h), materialSpecularExp)); /* Color final: modular (Emissive + Ambient + Diffuse) por el color del mesh, y luego sumar Specular. El color Alpha sale del diffuse material */ - float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * input.Color + specularLight , materialDiffuseColor.a); + float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * input.Color + specularLight, materialDiffuseColor.a); - return finalColor; + return finalColor; } /* @@ -151,11 +151,11 @@ float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 */ technique VERTEX_COLOR { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_VertexColor(); - PixelShader = compile ps_2_0 ps_VertexColor(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_VertexColor(); + PixelShader = compile ps_3_0 ps_VertexColor(); + } } /**************************************************************************************/ @@ -165,97 +165,97 @@ technique VERTEX_COLOR //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 WorldPosition : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; - float3 LightVec : TEXCOORD3; - float3 HalfAngleVec : TEXCOORD4; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 WorldPosition : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; + float3 LightVec : TEXCOORD3; + float3 HalfAngleVec : TEXCOORD4; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP vs_DiffuseMap(VS_INPUT_DIFFUSE_MAP input) { - VS_OUTPUT_DIFFUSE_MAP output; + VS_OUTPUT_DIFFUSE_MAP output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; //Posicion pasada a World-Space (necesaria para atenuación por distancia) - output.WorldPosition = mul(input.Position, matWorld); + output.WorldPosition = mul(input.Position, matWorld); /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - output.WorldPosition; + float3 viewVector = eyePosition.xyz - output.WorldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_DIFFUSE_MAP { - float2 Texcoord : TEXCOORD0; - float3 WorldPosition : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; - float3 LightVec : TEXCOORD3; - float3 HalfAngleVec : TEXCOORD4; + float2 Texcoord : TEXCOORD0; + float3 WorldPosition : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; + float3 LightVec : TEXCOORD3; + float3 HalfAngleVec : TEXCOORD4; }; //Pixel Shader float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Calcular intensidad de luz, con atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; - float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) //Obtener texel de la textura - float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); //Componente Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (intensity * lightColor * materialSpecularColor * pow(max(0.0, n_dot_h), materialSpecularExp)); /* Color final: modular (Emissive + Ambient + Diffuse) por el color de la textura, y luego sumar Specular. El color Alpha sale del diffuse material */ - float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight, materialDiffuseColor.a); + float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight, materialDiffuseColor.a); - return finalColor; + return finalColor; } /* @@ -263,11 +263,11 @@ float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 */ technique DIFFUSE_MAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_DiffuseMap(); - PixelShader = compile ps_2_0 ps_DiffuseMap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_DiffuseMap(); + PixelShader = compile ps_3_0 ps_DiffuseMap(); + } } /**************************************************************************************/ @@ -277,110 +277,110 @@ technique DIFFUSE_MAP //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; - float3 WorldPosition : TEXCOORD2; - float3 WorldNormal : TEXCOORD3; - float3 LightVec : TEXCOORD4; - float3 HalfAngleVec : TEXCOORD5; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; + float3 WorldPosition : TEXCOORD2; + float3 WorldNormal : TEXCOORD3; + float3 LightVec : TEXCOORD4; + float3 HalfAngleVec : TEXCOORD5; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP vs_diffuseMapAndLightmap(VS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP input) { - VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP output; + VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; - output.TexcoordLightmap = input.TexcoordLightmap; + output.Texcoord = input.Texcoord; + output.TexcoordLightmap = input.TexcoordLightmap; //Posicion pasada a World-Space (necesaria para atenuación por distancia) - output.WorldPosition = mul(input.Position, matWorld); + output.WorldPosition = mul(input.Position, matWorld); /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - output.WorldPosition; + float3 viewVector = eyePosition.xyz - output.WorldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; - float3 WorldPosition : TEXCOORD2; - float3 WorldNormal : TEXCOORD3; - float3 LightVec : TEXCOORD4; - float3 HalfAngleVec : TEXCOORD5; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; + float3 WorldPosition : TEXCOORD2; + float3 WorldNormal : TEXCOORD3; + float3 LightVec : TEXCOORD4; + float3 HalfAngleVec : TEXCOORD5; }; //Pixel Shader float4 ps_diffuseMapAndLightmap(PS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Calcular intensidad de luz, con atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; - float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) //Obtener color de diffuseMap y de Lightmap - float4 texelColor = tex2D(diffuseMap, input.Texcoord); - float4 lightmapColor = tex2D(lightMap, input.TexcoordLightmap); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 lightmapColor = tex2D(lightMap, input.TexcoordLightmap); //Componente Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (intensity * lightColor * materialSpecularColor * pow(max(0.0, n_dot_h), materialSpecularExp)); /* Color final: modular (Emissive + Ambient + Diffuse) por el color de la textura, y luego sumar Specular. El color Alpha sale del diffuse material */ - float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * (texelColor * lightmapColor) + specularLight, materialDiffuseColor.a); + float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * (texelColor * lightmapColor) + specularLight, materialDiffuseColor.a); - return finalColor; + return finalColor; } //technique DIFFUSE_MAP_AND_LIGHTMAP technique DIFFUSE_MAP_AND_LIGHTMAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_diffuseMapAndLightmap(); - PixelShader = compile ps_2_0 ps_diffuseMapAndLightmap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_diffuseMapAndLightmap(); + PixelShader = compile ps_3_0 ps_diffuseMapAndLightmap(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/TgcViewer/TgcMeshShader.fx b/TGC.Examples/Shaders/TgcViewer/TgcMeshShader.fx index 6c253599..bc470f4d 100644 --- a/TGC.Examples/Shaders/TgcViewer/TgcMeshShader.fx +++ b/TGC.Examples/Shaders/TgcViewer/TgcMeshShader.fx @@ -20,19 +20,19 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Textura para Lightmap texture texLightMap; sampler2D lightMap = sampler_state { - Texture = (texLightMap); + Texture = (texLightMap); }; /**************************************************************************************/ @@ -42,42 +42,42 @@ sampler2D lightMap = sampler_state //Input del Vertex Shader struct VS_INPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; }; //Output del Vertex Shader struct VS_OUTPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float4 Color : COLOR; + float4 Position : POSITION0; + float4 Color : COLOR; }; //Vertex Shader VS_OUTPUT_VERTEX_COLOR vs_VertexColor(VS_INPUT_VERTEX_COLOR input) { - VS_OUTPUT_VERTEX_COLOR output; + VS_OUTPUT_VERTEX_COLOR output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_VERTEX_COLOR { - float4 Color : COLOR0; + float4 Color : COLOR0; }; //Pixel Shader float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 { - return input.Color; + return input.Color; } /* @@ -85,11 +85,11 @@ float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 */ technique VERTEX_COLOR { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_VertexColor(); - PixelShader = compile ps_2_0 ps_VertexColor(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_VertexColor(); + PixelShader = compile ps_3_0 ps_VertexColor(); + } } /**************************************************************************************/ @@ -99,49 +99,49 @@ technique VERTEX_COLOR //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP vs_DiffuseMap(VS_INPUT_DIFFUSE_MAP input) { - VS_OUTPUT_DIFFUSE_MAP output; + VS_OUTPUT_DIFFUSE_MAP output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; - return output; + return output; } //Input del Pixel Shader struct PS_DIFFUSE_MAP { - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Pixel Shader float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 { //Modular color de la textura por color del mesh - return tex2D(diffuseMap, input.Texcoord) * input.Color; + return tex2D(diffuseMap, input.Texcoord) * input.Color; } /* @@ -149,11 +149,11 @@ float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 */ technique DIFFUSE_MAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_DiffuseMap(); - PixelShader = compile ps_2_0 ps_DiffuseMap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_DiffuseMap(); + PixelShader = compile ps_3_0 ps_DiffuseMap(); + } } /**************************************************************************************/ @@ -163,65 +163,65 @@ technique DIFFUSE_MAP //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float4 Position : POSITION0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; + float4 Position : POSITION0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP vs_diffuseMapAndLightmap(VS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP input) { - VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP output; + VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; - output.TexcoordLightmap = input.TexcoordLightmap; + output.Texcoord = input.Texcoord; + output.TexcoordLightmap = input.TexcoordLightmap; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; }; //Pixel Shader float4 ps_diffuseMapAndLightmap(PS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP input) : COLOR0 { //Obtener color de diffuseMap y de Lightmap - float4 albedo = tex2D(diffuseMap, input.Texcoord); - float4 lightmapColor = tex2D(lightMap, input.TexcoordLightmap); + float4 albedo = tex2D(diffuseMap, input.Texcoord); + float4 lightmapColor = tex2D(lightMap, input.TexcoordLightmap); //Modular ambos colores por color del mesh - return albedo * lightmapColor * input.Color; + return albedo * lightmapColor * input.Color; } //technique DIFFUSE_MAP_AND_LIGHTMAP technique DIFFUSE_MAP_AND_LIGHTMAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_diffuseMapAndLightmap(); - PixelShader = compile ps_2_0 ps_diffuseMapAndLightmap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_diffuseMapAndLightmap(); + PixelShader = compile ps_3_0 ps_diffuseMapAndLightmap(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/TgcViewer/TgcMeshSpotLightShader.fx b/TGC.Examples/Shaders/TgcViewer/TgcMeshSpotLightShader.fx index 11915941..fad643d6 100644 --- a/TGC.Examples/Shaders/TgcViewer/TgcMeshSpotLightShader.fx +++ b/TGC.Examples/Shaders/TgcViewer/TgcMeshSpotLightShader.fx @@ -21,19 +21,19 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Textura para Lightmap texture texLightMap; sampler2D lightMap = sampler_state { - Texture = (texLightMap); + Texture = (texLightMap); }; //Material del mesh @@ -62,101 +62,101 @@ float spotLightExponent; //Exponente de atenuacion dentro del cono de luz //Input del Vertex Shader struct VS_INPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; }; //Output del Vertex Shader struct VS_OUTPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float4 Color : COLOR; - float3 WorldPosition : TEXCOORD0; - float3 WorldNormal : TEXCOORD1; - float3 LightVec : TEXCOORD2; - float3 HalfAngleVec : TEXCOORD3; + float4 Position : POSITION0; + float4 Color : COLOR; + float3 WorldPosition : TEXCOORD0; + float3 WorldNormal : TEXCOORD1; + float3 LightVec : TEXCOORD2; + float3 HalfAngleVec : TEXCOORD3; }; //Vertex Shader VS_OUTPUT_VERTEX_COLOR vs_VertexColor(VS_INPUT_VERTEX_COLOR input) { - VS_OUTPUT_VERTEX_COLOR output; + VS_OUTPUT_VERTEX_COLOR output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; //Posicion pasada a World-Space (necesaria para atenuación por distancia) - output.WorldPosition = mul(input.Position, matWorld); + output.WorldPosition = mul(input.Position, matWorld); /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - output.WorldPosition; + float3 viewVector = eyePosition.xyz - output.WorldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_VERTEX_COLOR { - float4 Color : COLOR0; - float3 WorldPosition : TEXCOORD0; - float3 WorldNormal : TEXCOORD1; - float3 LightVec : TEXCOORD2; - float3 HalfAngleVec : TEXCOORD3; + float4 Color : COLOR0; + float3 WorldPosition : TEXCOORD0; + float3 WorldNormal : TEXCOORD1; + float3 LightVec : TEXCOORD2; + float3 HalfAngleVec : TEXCOORD3; }; //Pixel Shader float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Calcular atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; //Calcular atenuacion por Spot Light. Si esta fuera del angulo del cono tiene 0 intensidad. - float spotAtten = dot(-spotLightDir, Ln); - spotAtten = (spotAtten > spotLightAngleCos) + float spotAtten = dot(-spotLightDir, Ln); + spotAtten = (spotAtten > spotLightAngleCos) ? pow(spotAtten, spotLightExponent) : 0.0; //Calcular intensidad de la luz segun la atenuacion por distancia y si esta adentro o fuera del cono de luz - float intensity = lightIntensity * spotAtten / distAtten; + float intensity = lightIntensity * spotAtten / distAtten; //Componente Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (intensity * lightColor * materialSpecularColor * pow(max(0.0, n_dot_h), materialSpecularExp)); /* Color final: modular (Emissive + Ambient + Diffuse) por el color del mesh, y luego sumar Specular. El color Alpha sale del diffuse material */ - float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * input.Color + specularLight , materialDiffuseColor.a); + float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * input.Color + specularLight, materialDiffuseColor.a); - return finalColor; + return finalColor; } /* @@ -164,11 +164,11 @@ float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 */ technique VERTEX_COLOR { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_VertexColor(); - PixelShader = compile ps_2_0 ps_VertexColor(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_VertexColor(); + PixelShader = compile ps_3_0 ps_VertexColor(); + } } /**************************************************************************************/ @@ -178,105 +178,105 @@ technique VERTEX_COLOR //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 WorldPosition : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; - float3 LightVec : TEXCOORD3; - float3 HalfAngleVec : TEXCOORD4; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 WorldPosition : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; + float3 LightVec : TEXCOORD3; + float3 HalfAngleVec : TEXCOORD4; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP vs_DiffuseMap(VS_INPUT_DIFFUSE_MAP input) { - VS_OUTPUT_DIFFUSE_MAP output; + VS_OUTPUT_DIFFUSE_MAP output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; //Posicion pasada a World-Space (necesaria para atenuación por distancia) - output.WorldPosition = mul(input.Position, matWorld); + output.WorldPosition = mul(input.Position, matWorld); /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - output.WorldPosition; + float3 viewVector = eyePosition.xyz - output.WorldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_DIFFUSE_MAP { - float2 Texcoord : TEXCOORD0; - float3 WorldPosition : TEXCOORD1; - float3 WorldNormal : TEXCOORD2; - float3 LightVec : TEXCOORD3; - float3 HalfAngleVec : TEXCOORD4; + float2 Texcoord : TEXCOORD0; + float3 WorldPosition : TEXCOORD1; + float3 WorldNormal : TEXCOORD2; + float3 LightVec : TEXCOORD3; + float3 HalfAngleVec : TEXCOORD4; }; //Pixel Shader float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Calcular atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; //Calcular atenuacion por Spot Light. Si esta fuera del angulo del cono tiene 0 intensidad. - float spotAtten = dot(-spotLightDir, Ln); - spotAtten = (spotAtten > spotLightAngleCos) + float spotAtten = dot(-spotLightDir, Ln); + spotAtten = (spotAtten > spotLightAngleCos) ? pow(spotAtten, spotLightExponent) : 0.0; //Calcular intensidad de la luz segun la atenuacion por distancia y si esta adentro o fuera del cono de luz - float intensity = lightIntensity * spotAtten / distAtten; + float intensity = lightIntensity * spotAtten / distAtten; //Obtener texel de la textura - float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); //Componente Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (intensity * lightColor * materialSpecularColor * pow(max(0.0, n_dot_h), materialSpecularExp)); /* Color final: modular (Emissive + Ambient + Diffuse) por el color de la textura, y luego sumar Specular. El color Alpha sale del diffuse material */ - float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight, materialDiffuseColor.a); + float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight, materialDiffuseColor.a); - return finalColor; + return finalColor; } /* @@ -284,11 +284,11 @@ float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 */ technique DIFFUSE_MAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_DiffuseMap(); - PixelShader = compile ps_2_0 ps_DiffuseMap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_DiffuseMap(); + PixelShader = compile ps_3_0 ps_DiffuseMap(); + } } /**************************************************************************************/ @@ -298,118 +298,118 @@ technique DIFFUSE_MAP //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; - float3 WorldPosition : TEXCOORD2; - float3 WorldNormal : TEXCOORD3; - float3 LightVec : TEXCOORD4; - float3 HalfAngleVec : TEXCOORD5; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; + float3 WorldPosition : TEXCOORD2; + float3 WorldNormal : TEXCOORD3; + float3 LightVec : TEXCOORD4; + float3 HalfAngleVec : TEXCOORD5; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP vs_diffuseMapAndLightmap(VS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP input) { - VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP output; + VS_OUTPUT_DIFFUSE_MAP_AND_LIGHTMAP output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; - output.TexcoordLightmap = input.TexcoordLightmap; + output.Texcoord = input.Texcoord; + output.TexcoordLightmap = input.TexcoordLightmap; //Posicion pasada a World-Space (necesaria para atenuación por distancia) - output.WorldPosition = mul(input.Position, matWorld); + output.WorldPosition = mul(input.Position, matWorld); /* Pasar normal a World-Space Solo queremos rotarla, no trasladarla ni escalarla. Por eso usamos matInverseTransposeWorld en vez de matWorld */ - output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; + output.WorldNormal = mul(input.Normal, matInverseTransposeWorld).xyz; //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - output.WorldPosition; + float3 viewVector = eyePosition.xyz - output.WorldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP { - float2 Texcoord : TEXCOORD0; - float2 TexcoordLightmap : TEXCOORD1; - float3 WorldPosition : TEXCOORD2; - float3 WorldNormal : TEXCOORD3; - float3 LightVec : TEXCOORD4; - float3 HalfAngleVec : TEXCOORD5; + float2 Texcoord : TEXCOORD0; + float2 TexcoordLightmap : TEXCOORD1; + float3 WorldPosition : TEXCOORD2; + float3 WorldNormal : TEXCOORD3; + float3 LightVec : TEXCOORD4; + float3 HalfAngleVec : TEXCOORD5; }; //Pixel Shader float4 ps_diffuseMapAndLightmap(PS_INPUT_DIFFUSE_MAP_AND_LIGHTMAP input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Calcular atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; //Calcular atenuacion por Spot Light. Si esta fuera del angulo del cono tiene 0 intensidad. - float spotAtten = dot(-spotLightDir, Ln); - spotAtten = (spotAtten > spotLightAngleCos) + float spotAtten = dot(-spotLightDir, Ln); + spotAtten = (spotAtten > spotLightAngleCos) ? pow(spotAtten, spotLightExponent) : 0.0; //Calcular intensidad de la luz segun la atenuacion por distancia y si esta adentro o fuera del cono de luz - float intensity = lightIntensity * spotAtten / distAtten; + float intensity = lightIntensity * spotAtten / distAtten; //Obtener color de diffuseMap y de Lightmap - float4 texelColor = tex2D(diffuseMap, input.Texcoord); - float4 lightmapColor = tex2D(lightMap, input.TexcoordLightmap); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 lightmapColor = tex2D(lightMap, input.TexcoordLightmap); //Componente Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (intensity * lightColor * materialSpecularColor * pow(max(0.0, n_dot_h), materialSpecularExp)); /* Color final: modular (Emissive + Ambient + Diffuse) por el color de la textura, y luego sumar Specular. El color Alpha sale del diffuse material */ - float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * (texelColor * lightmapColor) + specularLight, materialDiffuseColor.a); + float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * (texelColor * lightmapColor) + specularLight, materialDiffuseColor.a); - return finalColor; + return finalColor; } //technique DIFFUSE_MAP_AND_LIGHTMAP technique DIFFUSE_MAP_AND_LIGHTMAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_diffuseMapAndLightmap(); - PixelShader = compile ps_2_0 ps_diffuseMapAndLightmap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_diffuseMapAndLightmap(); + PixelShader = compile ps_3_0 ps_diffuseMapAndLightmap(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/TgcViewer/TgcSkeletalMeshPointLightShader.fx b/TGC.Examples/Shaders/TgcViewer/TgcSkeletalMeshPointLightShader.fx index 81627125..4f08a981 100644 --- a/TGC.Examples/Shaders/TgcViewer/TgcSkeletalMeshPointLightShader.fx +++ b/TGC.Examples/Shaders/TgcViewer/TgcSkeletalMeshPointLightShader.fx @@ -20,12 +20,12 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Matrix Pallette para skinning @@ -53,124 +53,124 @@ float lightAttenuation; //Factor de atenuacion de la luz //Input del Vertex Shader struct VS_INPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float4 Color : COLOR; - float3 Normal : NORMAL0; - float3 Tangent : TANGENT0; - float3 Binormal : BINORMAL0; - float4 BlendWeights : BLENDWEIGHT; - float4 BlendIndices : BLENDINDICES; + float4 Position : POSITION0; + float4 Color : COLOR; + float3 Normal : NORMAL0; + float3 Tangent : TANGENT0; + float3 Binormal : BINORMAL0; + float4 BlendWeights : BLENDWEIGHT; + float4 BlendIndices : BLENDINDICES; }; //Output del Vertex Shader struct VS_OUTPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float4 Color : COLOR; - float3 WorldNormal : TEXCOORD0; - float3 WorldTangent : TEXCOORD1; - float3 WorldBinormal : TEXCOORD2; - float3 WorldPosition : TEXCOORD3; - float3 LightVec : TEXCOORD4; - float3 HalfAngleVec : TEXCOORD5; + float4 Position : POSITION0; + float4 Color : COLOR; + float3 WorldNormal : TEXCOORD0; + float3 WorldTangent : TEXCOORD1; + float3 WorldBinormal : TEXCOORD2; + float3 WorldPosition : TEXCOORD3; + float3 LightVec : TEXCOORD4; + float3 HalfAngleVec : TEXCOORD5; }; //Vertex Shader VS_OUTPUT_VERTEX_COLOR vs_VertexColor(VS_INPUT_VERTEX_COLOR input) { - VS_OUTPUT_VERTEX_COLOR output; + VS_OUTPUT_VERTEX_COLOR output; //Pasar indices de float4 a array de int - int BlendIndicesArray[4] = (int[4])input.BlendIndices; + int BlendIndicesArray[4] = (int[4]) input.BlendIndices; //Skinning de posicion - float3 skinPosition = mul(input.Position, bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x;; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + float3 skinPosition = mul(input.Position, bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x;; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; //Skinning de normal - float3 skinNormal = mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldNormal = normalize(skinNormal); + float3 skinNormal = mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldNormal = normalize(skinNormal); //Skinning de tangent - float3 skinTangent = mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldTangent = normalize(skinTangent); + float3 skinTangent = mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldTangent = normalize(skinTangent); //Skinning de binormal - float3 skinBinormal = mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldBinormal = normalize(skinBinormal); + float3 skinBinormal = mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldBinormal = normalize(skinBinormal); //Proyectar posicion (teniendo en cuenta lo que se hizo por skinning) - output.Position = mul(float4(skinPosition.xyz, 1.0), matWorldViewProj); + output.Position = mul(float4(skinPosition.xyz, 1.0), matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; //Posicion pasada a World-Space (necesaria para atenuación por distancia) - output.WorldPosition = mul(input.Position, matWorld); + output.WorldPosition = mul(input.Position, matWorld); //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - output.WorldPosition; + float3 viewVector = eyePosition.xyz - output.WorldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_VERTEX_COLOR { - float4 Color : COLOR0; - float3 WorldNormal : TEXCOORD0; - float3 WorldPosition : TEXCOORD3; - float3 LightVec : TEXCOORD4; - float3 HalfAngleVec : TEXCOORD5; + float4 Color : COLOR0; + float3 WorldNormal : TEXCOORD0; + float3 WorldPosition : TEXCOORD3; + float3 LightVec : TEXCOORD4; + float3 HalfAngleVec : TEXCOORD5; }; //Pixel Shader float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Calcular intensidad de luz, con atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; - float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) //Componente Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (intensity * lightColor * materialSpecularColor * pow(max(0.0, n_dot_h), materialSpecularExp)); /* Color final: modular (Emissive + Ambient + Diffuse) por el color del mesh, y luego sumar Specular. El color Alpha sale del diffuse material */ - float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * input.Color + specularLight , materialDiffuseColor.a); + float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * input.Color + specularLight, materialDiffuseColor.a); - return finalColor; + return finalColor; } /* @@ -178,11 +178,11 @@ float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 */ technique VERTEX_COLOR { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_VertexColor(); - PixelShader = compile ps_2_0 ps_VertexColor(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_VertexColor(); + PixelShader = compile ps_3_0 ps_VertexColor(); + } } /**************************************************************************************/ @@ -192,133 +192,133 @@ technique VERTEX_COLOR //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float3 Normal : NORMAL0; - float3 Tangent : TANGENT0; - float3 Binormal : BINORMAL0; - float4 BlendWeights : BLENDWEIGHT; - float4 BlendIndices : BLENDINDICES; + float4 Position : POSITION0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float3 Normal : NORMAL0; + float3 Tangent : TANGENT0; + float3 Binormal : BINORMAL0; + float4 BlendWeights : BLENDWEIGHT; + float4 BlendIndices : BLENDINDICES; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float4 Color : COLOR0; - float2 Texcoord : TEXCOORD0; - float3 WorldNormal : TEXCOORD1; - float3 WorldTangent : TEXCOORD2; - float3 WorldBinormal : TEXCOORD3; - float3 WorldPosition : TEXCOORD4; - float3 LightVec : TEXCOORD5; - float3 HalfAngleVec : TEXCOORD6; + float4 Position : POSITION0; + float4 Color : COLOR0; + float2 Texcoord : TEXCOORD0; + float3 WorldNormal : TEXCOORD1; + float3 WorldTangent : TEXCOORD2; + float3 WorldBinormal : TEXCOORD3; + float3 WorldPosition : TEXCOORD4; + float3 LightVec : TEXCOORD5; + float3 HalfAngleVec : TEXCOORD6; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP vs_DiffuseMap(VS_INPUT_DIFFUSE_MAP input) { - VS_OUTPUT_DIFFUSE_MAP output; + VS_OUTPUT_DIFFUSE_MAP output; //Pasar indices de float4 a array de int - int BlendIndicesArray[4] = (int[4])input.BlendIndices; + int BlendIndicesArray[4] = (int[4]) input.BlendIndices; //Skinning de posicion - float3 skinPosition = mul(input.Position, bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x;; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + float3 skinPosition = mul(input.Position, bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x;; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; //Skinning de normal - float3 skinNormal = mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldNormal = normalize(skinNormal); + float3 skinNormal = mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldNormal = normalize(skinNormal); //Skinning de tangent - float3 skinTangent = mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldTangent = normalize(skinTangent); + float3 skinTangent = mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldTangent = normalize(skinTangent); //Skinning de binormal - float3 skinBinormal = mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldBinormal = normalize(skinBinormal); + float3 skinBinormal = mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldBinormal = normalize(skinBinormal); //Proyectar posicion (teniendo en cuenta lo que se hizo por skinning) - output.Position = mul(float4(skinPosition.xyz, 1.0), matWorldViewProj); + output.Position = mul(float4(skinPosition.xyz, 1.0), matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; //Posicion pasada a World-Space (necesaria para atenuación por distancia) - output.WorldPosition = mul(input.Position, matWorld); + output.WorldPosition = mul(input.Position, matWorld); //LightVec (L): vector que va desde el vertice hacia la luz. Usado en Diffuse y Specular - output.LightVec = lightPosition.xyz - output.WorldPosition; + output.LightVec = lightPosition.xyz - output.WorldPosition; //ViewVec (V): vector que va desde el vertice hacia la camara. - float3 viewVector = eyePosition.xyz - output.WorldPosition; + float3 viewVector = eyePosition.xyz - output.WorldPosition; //HalfAngleVec (H): vector de reflexion simplificado de Phong-Blinn (H = |V + L|). Usado en Specular - output.HalfAngleVec = viewVector + output.LightVec; + output.HalfAngleVec = viewVector + output.LightVec; - return output; + return output; } //Input del Pixel Shader struct PS_DIFFUSE_MAP { - float4 Color : COLOR0; - float2 Texcoord : TEXCOORD0; - float3 WorldNormal : TEXCOORD1; - float3 WorldPosition : TEXCOORD4; - float3 LightVec : TEXCOORD5; - float3 HalfAngleVec : TEXCOORD6; + float4 Color : COLOR0; + float2 Texcoord : TEXCOORD0; + float3 WorldNormal : TEXCOORD1; + float3 WorldPosition : TEXCOORD4; + float3 LightVec : TEXCOORD5; + float3 HalfAngleVec : TEXCOORD6; }; //Pixel Shader float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 { //Normalizar vectores - float3 Nn = normalize(input.WorldNormal); - float3 Ln = normalize(input.LightVec); - float3 Hn = normalize(input.HalfAngleVec); + float3 Nn = normalize(input.WorldNormal); + float3 Ln = normalize(input.LightVec); + float3 Hn = normalize(input.HalfAngleVec); //Calcular intensidad de luz, con atenuacion por distancia - float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; - float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) + float distAtten = length(lightPosition.xyz - input.WorldPosition) * lightAttenuation; + float intensity = lightIntensity / distAtten; //Dividimos intensidad sobre distancia (lo hacemos lineal pero tambien podria ser i/d^2) //Obtener texel de la textura - float4 texelColor = tex2D(diffuseMap, input.Texcoord); + float4 texelColor = tex2D(diffuseMap, input.Texcoord); //Componente Ambient - float3 ambientLight = intensity * lightColor * materialAmbientColor; + float3 ambientLight = intensity * lightColor * materialAmbientColor; //Componente Diffuse: N dot L - float3 n_dot_l = dot(Nn, Ln); - float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo + float3 n_dot_l = dot(Nn, Ln); + float3 diffuseLight = intensity * lightColor * materialDiffuseColor.rgb * max(0.0, n_dot_l); //Controlamos que no de negativo //Componente Specular: (N dot H)^exp - float3 n_dot_h = dot(Nn, Hn); - float3 specularLight = n_dot_l <= 0.0 + float3 n_dot_h = dot(Nn, Hn); + float3 specularLight = n_dot_l <= 0.0 ? float3(0.0, 0.0, 0.0) : (intensity * lightColor * materialSpecularColor * pow(max(0.0, n_dot_h), materialSpecularExp)); /* Color final: modular (Emissive + Ambient + Diffuse) por el color de la textura, y luego sumar Specular. El color Alpha sale del diffuse material */ - float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight, materialDiffuseColor.a); + float4 finalColor = float4(saturate(materialEmissiveColor + ambientLight + diffuseLight) * texelColor + specularLight, materialDiffuseColor.a); - return finalColor; + return finalColor; } /* @@ -326,9 +326,9 @@ float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 */ technique DIFFUSE_MAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_DiffuseMap(); - PixelShader = compile ps_2_0 ps_DiffuseMap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_DiffuseMap(); + PixelShader = compile ps_3_0 ps_DiffuseMap(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/TgcViewer/TgcSkeletalMeshShader.fx b/TGC.Examples/Shaders/TgcViewer/TgcSkeletalMeshShader.fx index 0316ff7a..9df68f61 100644 --- a/TGC.Examples/Shaders/TgcViewer/TgcSkeletalMeshShader.fx +++ b/TGC.Examples/Shaders/TgcViewer/TgcSkeletalMeshShader.fx @@ -19,12 +19,12 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Matrix Pallette para skinning @@ -38,79 +38,79 @@ float4x3 bonesMatWorldArray[MAX_MATRICES]; //Input del Vertex Shader struct VS_INPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float4 Color : COLOR; - float3 Normal : NORMAL0; - float3 Tangent : TANGENT0; - float3 Binormal : BINORMAL0; - float4 BlendWeights : BLENDWEIGHT; - float4 BlendIndices : BLENDINDICES; + float4 Position : POSITION0; + float4 Color : COLOR; + float3 Normal : NORMAL0; + float3 Tangent : TANGENT0; + float3 Binormal : BINORMAL0; + float4 BlendWeights : BLENDWEIGHT; + float4 BlendIndices : BLENDINDICES; }; //Output del Vertex Shader struct VS_OUTPUT_VERTEX_COLOR { - float4 Position : POSITION0; - float4 Color : COLOR; - float3 WorldNormal : TEXCOORD1; - float3 WorldTangent : TEXCOORD2; - float3 WorldBinormal : TEXCOORD3; + float4 Position : POSITION0; + float4 Color : COLOR; + float3 WorldNormal : TEXCOORD1; + float3 WorldTangent : TEXCOORD2; + float3 WorldBinormal : TEXCOORD3; }; //Vertex Shader VS_OUTPUT_VERTEX_COLOR vs_VertexColor(VS_INPUT_VERTEX_COLOR input) { - VS_OUTPUT_VERTEX_COLOR output; + VS_OUTPUT_VERTEX_COLOR output; //Pasar indices de float4 a array de int - int BlendIndicesArray[4] = (int[4])input.BlendIndices; + int BlendIndicesArray[4] = (int[4]) input.BlendIndices; //Skinning de posicion - float3 skinPosition = mul(input.Position, bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x;; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + float3 skinPosition = mul(input.Position, bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x;; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; //Skinning de normal - float3 skinNormal = mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldNormal = normalize(skinNormal); + float3 skinNormal = mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldNormal = normalize(skinNormal); //Skinning de tangent - float3 skinTangent = mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldTangent = normalize(skinTangent); + float3 skinTangent = mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldTangent = normalize(skinTangent); //Skinning de binormal - float3 skinBinormal = mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldBinormal = normalize(skinBinormal); + float3 skinBinormal = mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldBinormal = normalize(skinBinormal); //Proyectar posicion (teniendo en cuenta lo que se hizo por skinning) - output.Position = mul(float4(skinPosition.xyz, 1.0), matWorldViewProj); + output.Position = mul(float4(skinPosition.xyz, 1.0), matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_VERTEX_COLOR { - float4 Color : COLOR0; + float4 Color : COLOR0; }; //Pixel Shader float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 { - return input.Color; + return input.Color; } /* @@ -118,11 +118,11 @@ float4 ps_VertexColor(PS_INPUT_VERTEX_COLOR input) : COLOR0 */ technique VERTEX_COLOR { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_VertexColor(); - PixelShader = compile ps_2_0 ps_VertexColor(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_VertexColor(); + PixelShader = compile ps_3_0 ps_VertexColor(); + } } /**************************************************************************************/ @@ -132,86 +132,86 @@ technique VERTEX_COLOR //Input del Vertex Shader struct VS_INPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; - float3 Normal : NORMAL0; - float3 Tangent : TANGENT0; - float3 Binormal : BINORMAL0; - float4 BlendWeights : BLENDWEIGHT; - float4 BlendIndices : BLENDINDICES; + float4 Position : POSITION0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; + float3 Normal : NORMAL0; + float3 Tangent : TANGENT0; + float3 Binormal : BINORMAL0; + float4 BlendWeights : BLENDWEIGHT; + float4 BlendIndices : BLENDINDICES; }; //Output del Vertex Shader struct VS_OUTPUT_DIFFUSE_MAP { - float4 Position : POSITION0; - float4 Color : COLOR0; - float2 Texcoord : TEXCOORD0; - float3 WorldNormal : TEXCOORD1; - float3 WorldTangent : TEXCOORD2; - float3 WorldBinormal : TEXCOORD3; + float4 Position : POSITION0; + float4 Color : COLOR0; + float2 Texcoord : TEXCOORD0; + float3 WorldNormal : TEXCOORD1; + float3 WorldTangent : TEXCOORD2; + float3 WorldBinormal : TEXCOORD3; }; //Vertex Shader VS_OUTPUT_DIFFUSE_MAP vs_DiffuseMap(VS_INPUT_DIFFUSE_MAP input) { - VS_OUTPUT_DIFFUSE_MAP output; + VS_OUTPUT_DIFFUSE_MAP output; //Pasar indices de float4 a array de int - int BlendIndicesArray[4] = (int[4])input.BlendIndices; + int BlendIndicesArray[4] = (int[4]) input.BlendIndices; //Skinning de posicion - float3 skinPosition = mul(input.Position, bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x;; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + float3 skinPosition = mul(input.Position, bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x;; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinPosition += mul(input.Position, bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; //Skinning de normal - float3 skinNormal = mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinNormal += mul(input.Normal, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldNormal = normalize(skinNormal); + float3 skinNormal = mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinNormal += mul(input.Normal, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldNormal = normalize(skinNormal); //Skinning de tangent - float3 skinTangent = mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinTangent += mul(input.Tangent, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldTangent = normalize(skinTangent); + float3 skinTangent = mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinTangent += mul(input.Tangent, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldTangent = normalize(skinTangent); //Skinning de binormal - float3 skinBinormal = mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; - skinBinormal += mul(input.Binormal, (float3x3)bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; - output.WorldBinormal = normalize(skinBinormal); + float3 skinBinormal = mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[0]]) * input.BlendWeights.x; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[1]]) * input.BlendWeights.y; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[2]]) * input.BlendWeights.z; + skinBinormal += mul(input.Binormal, (float3x3) bonesMatWorldArray[BlendIndicesArray[3]]) * input.BlendWeights.w; + output.WorldBinormal = normalize(skinBinormal); //Proyectar posicion (teniendo en cuenta lo que se hizo por skinning) - output.Position = mul(float4(skinPosition.xyz, 1.0), matWorldViewProj); + output.Position = mul(float4(skinPosition.xyz, 1.0), matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; - return output; + return output; } //Input del Pixel Shader struct PS_DIFFUSE_MAP { - float4 Color : COLOR0; - float2 Texcoord : TEXCOORD0; + float4 Color : COLOR0; + float2 Texcoord : TEXCOORD0; }; //Pixel Shader float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 { //Modular color de la textura por color del mesh - return tex2D(diffuseMap, input.Texcoord) * input.Color; + return tex2D(diffuseMap, input.Texcoord) * input.Color; } /* @@ -219,9 +219,9 @@ float4 ps_DiffuseMap(PS_DIFFUSE_MAP input) : COLOR0 */ technique DIFFUSE_MAP { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_DiffuseMap(); - PixelShader = compile ps_2_0 ps_DiffuseMap(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_DiffuseMap(); + PixelShader = compile ps_3_0 ps_DiffuseMap(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/TgcViewer/Varios.fx b/TGC.Examples/Shaders/TgcViewer/Varios.fx index c3753748..7ae293e8 100644 --- a/TGC.Examples/Shaders/TgcViewer/Varios.fx +++ b/TGC.Examples/Shaders/TgcViewer/Varios.fx @@ -22,12 +22,12 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Factor de translucidez @@ -40,47 +40,47 @@ float alphaValue = 1; //Input del Vertex Shader struct VS_INPUT_PositionColoredTextured { - float4 Position : POSITION0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_PositionColoredTextured { - float4 Position : POSITION0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Vertex Shader VS_OUTPUT_PositionColoredTextured vs_PositionColoredTextured(VS_INPUT_PositionColoredTextured input) { - VS_OUTPUT_PositionColoredTextured output; + VS_OUTPUT_PositionColoredTextured output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_PositionColoredTextured { - float4 Color : COLOR0; - float2 Texcoord : TEXCOORD0; + float4 Color : COLOR0; + float2 Texcoord : TEXCOORD0; }; //Pixel Shader float4 ps_PositionColoredTextured(PS_INPUT_PositionColoredTextured input) : COLOR0 { - return input.Color * tex2D(diffuseMap, input.Texcoord); + return input.Color * tex2D(diffuseMap, input.Texcoord); } /* @@ -88,11 +88,11 @@ float4 ps_PositionColoredTextured(PS_INPUT_PositionColoredTextured input) : COLO */ technique PositionColoredTextured { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_PositionColoredTextured(); - PixelShader = compile ps_2_0 ps_PositionColoredTextured(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_PositionColoredTextured(); + PixelShader = compile ps_3_0 ps_PositionColoredTextured(); + } } /**************************************************************************************/ @@ -102,41 +102,41 @@ technique PositionColoredTextured //Input del Vertex Shader struct VS_INPUT_PositionTextured { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT_PositionTextured { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; }; //Vertex Shader VS_OUTPUT_PositionTextured vs_PositionTextured(VS_INPUT_PositionTextured input) { - VS_OUTPUT_PositionTextured output; + VS_OUTPUT_PositionTextured output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar Texcoord directamente - output.Texcoord = input.Texcoord; + output.Texcoord = input.Texcoord; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_PositionTextured { - float2 Texcoord : TEXCOORD0; + float2 Texcoord : TEXCOORD0; }; //Pixel Shader float4 ps_PositionTextured(PS_INPUT_PositionTextured input) : COLOR0 { - return tex2D(diffuseMap, input.Texcoord); + return tex2D(diffuseMap, input.Texcoord); } /* @@ -144,11 +144,11 @@ float4 ps_PositionTextured(PS_INPUT_PositionTextured input) : COLOR0 */ technique PositionTextured { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_PositionTextured(); - PixelShader = compile ps_2_0 ps_PositionTextured(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_PositionTextured(); + PixelShader = compile ps_3_0 ps_PositionTextured(); + } } /**************************************************************************************/ @@ -158,41 +158,41 @@ technique PositionTextured //Input del Vertex Shader struct VS_INPUT_PositionColored { - float4 Position : POSITION0; - float4 Color : COLOR0; + float4 Position : POSITION0; + float4 Color : COLOR0; }; //Output del Vertex Shader struct VS_OUTPUT_PositionColored { - float4 Position : POSITION0; - float4 Color : COLOR0; + float4 Position : POSITION0; + float4 Color : COLOR0; }; //Vertex Shader VS_OUTPUT_PositionColored vs_PositionColored(VS_INPUT_PositionColored input) { - VS_OUTPUT_PositionColored output; + VS_OUTPUT_PositionColored output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_PositionColored { - float4 Color : COLOR0; + float4 Color : COLOR0; }; //Pixel Shader float4 ps_PositionColored(PS_INPUT_PositionColored input) : COLOR0 { - return input.Color; + return input.Color; } /* @@ -200,11 +200,11 @@ float4 ps_PositionColored(PS_INPUT_PositionColored input) : COLOR0 */ technique PositionColored { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_PositionColored(); - PixelShader = compile ps_2_0 ps_PositionColored(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_PositionColored(); + PixelShader = compile ps_3_0 ps_PositionColored(); + } } /**************************************************************************************/ @@ -214,41 +214,41 @@ technique PositionColored //Input del Vertex Shader struct VS_INPUT_PositionColoredAlpha { - float4 Position : POSITION0; - float4 Color : COLOR0; + float4 Position : POSITION0; + float4 Color : COLOR0; }; //Output del Vertex Shader struct VS_OUTPUT_PositionColoredAlpha { - float4 Position : POSITION0; - float4 Color : COLOR0; + float4 Position : POSITION0; + float4 Color : COLOR0; }; //Vertex Shader VS_OUTPUT_PositionColoredAlpha vs_PositionColoredAlpha(VS_INPUT_PositionColoredAlpha input) { - VS_OUTPUT_PositionColoredAlpha output; + VS_OUTPUT_PositionColoredAlpha output; //Proyectar posicion - output.Position = mul(input.Position, matWorldViewProj); + output.Position = mul(input.Position, matWorldViewProj); //Enviar color directamente - output.Color = input.Color; + output.Color = input.Color; - return output; + return output; } //Input del Pixel Shader struct PS_INPUT_PositionColoredAlpha { - float4 Color : COLOR0; + float4 Color : COLOR0; }; //Pixel Shader float4 ps_PositionColoredAlpha(PS_INPUT_PositionColoredAlpha input) : COLOR0 { - return float4(input.Color.rgb, alphaValue); + return float4(input.Color.rgb, alphaValue); } /* @@ -256,9 +256,9 @@ float4 ps_PositionColoredAlpha(PS_INPUT_PositionColoredAlpha input) : COLOR0 */ technique PositionColoredAlpha { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_PositionColoredAlpha(); - PixelShader = compile ps_2_0 ps_PositionColoredAlpha(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_PositionColoredAlpha(); + PixelShader = compile ps_3_0 ps_PositionColoredAlpha(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/WorkshopShaders/BasicShader.fx b/TGC.Examples/Shaders/WorkshopShaders/BasicShader.fx index 7d42aad2..ea778081 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/BasicShader.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/BasicShader.fx @@ -12,16 +12,19 @@ float4x4 matWorldView; //Matriz World * View float4x4 matWorldViewProj; //Matriz World * View * Projection float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) +float screen_dx = 1024; +float screen_dy = 768; + //Textura para DiffuseMap texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; float time = 0; @@ -33,40 +36,45 @@ float time = 0; //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float4 Color : COLOR0; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float4 Color : COLOR0; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float4 Color : COLOR0; + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float2 RealPos : TEXCOORD1; + float4 Color : COLOR0; }; //Vertex Shader VS_OUTPUT vs_main(VS_INPUT Input) { - VS_OUTPUT Output; - //Proyectar posicion - Output.Position = mul(Input.Position, matWorldViewProj); + VS_OUTPUT Output; + Output.RealPos = Input.Position; + //Proyectar posicion + Output.Position = mul(Input.Position, matWorldViewProj); + //Propago las coordenadas de textura - Output.Texcoord = Input.Texcoord; + Output.Texcoord = Input.Texcoord; //Propago el color x vertice - Output.Color = Input.Color; + Output.Color = Input.Color; - return(Output); + return (Output); } // Ejemplo de un vertex shader que anima la posicion de los vertices // ------------------------------------------------------------------ VS_OUTPUT vs_main2(VS_INPUT Input) { - VS_OUTPUT Output; + VS_OUTPUT Output; + + Output.RealPos = Input.Position; // Animar posicion /*Input.Position.x += sin(time)*30*sign(Input.Position.x); @@ -75,44 +83,62 @@ VS_OUTPUT vs_main2(VS_INPUT Input) */ // Animar posicion - float Y = Input.Position.y; - float Z = Input.Position.z; - Input.Position.y = Y * cos(time) - Z * sin(time); - Input.Position.z = Z * cos(time) + Y * sin(time); + float Y = Input.Position.y; + float Z = Input.Position.z; + Input.Position.y = Y * cos(time) - Z * sin(time); + Input.Position.z = Z * cos(time) + Y * sin(time); //Proyectar posicion - Output.Position = mul(Input.Position, matWorldViewProj); + Output.Position = mul(Input.Position, matWorldViewProj); //Propago las coordenadas de textura - Output.Texcoord = Input.Texcoord; + Output.Texcoord = Input.Texcoord; // Animar color - Input.Color.r = abs(sin(time)); - Input.Color.g = abs(cos(time)); + Input.Color.r = abs(sin(time)); + Input.Color.g = abs(cos(time)); //Propago el color x vertice - Output.Color = Input.Color; + Output.Color = Input.Color; - return(Output); + return (Output); } +float frecuencia = 10; //Pixel Shader -float4 ps_main(float2 Texcoord: TEXCOORD0, float4 Color : COLOR0) : COLOR0 +float4 ps_main(VS_OUTPUT Input) : COLOR0 +{ + float y = Input.Texcoord.y * screen_dy + cos(time * frecuencia); + Input.Texcoord.y = y / screen_dy; + return tex2D(diffuseMap, Input.Texcoord); +} + +//Pixel Shader +float4 ps_main2(float2 Texcoord : TEXCOORD0, float4 Color : COLOR0) : COLOR0 { // Obtener el texel de textura // diffuseMap es el sampler, Texcoord son las coordenadas interpoladas - float4 fvBaseColor = tex2D(diffuseMap, Texcoord); + float4 fvBaseColor = tex2D(diffuseMap, Texcoord); // combino color y textura // en este ejemplo combino un 80% el color de la textura y un 20%el del vertice - return 0.8*fvBaseColor + 0.2*Color; + return 0.8 * fvBaseColor + 0.2 * Color; } // ------------------------------------------------------------------ technique RenderScene { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_main2(); - PixelShader = compile ps_2_0 ps_main(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_main(); + } +} + +technique RenderScene2 +{ + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main2(); + PixelShader = compile ps_3_0 ps_main2(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/WorkshopShaders/Demo.fx b/TGC.Examples/Shaders/WorkshopShaders/Demo.fx index 3e906d5d..4d3f2bf6 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/Demo.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/Demo.fx @@ -16,12 +16,12 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; float3 fvLightPosition = float3(-100.00, 100.00, -100.00); @@ -39,49 +39,49 @@ float canoa_x = 0; float canoa_y = 0; float fHeightMapScale = 0.2; -float k_la = 0.7; // luz ambiente global -float k_ld = 0.4; // luz difusa -float k_ls = 1.0; // luz specular +float k_la = 0.7; // luz ambiente global +float k_ld = 0.4; // luz difusa +float k_ls = 1.0; // luz specular float fSpecularPower = 16.84; float4x4 g_mViewLightProj; float4x4 g_mProjLight; -float3 g_vLightPos; // posicion de la luz (en World Space) = pto que representa patch emisor Bj -float3 g_vLightDir; // Direcion de la luz (en World Space) = normal al patch Bj +float3 g_vLightPos; // posicion de la luz (en World Space) = pto que representa patch emisor Bj +float3 g_vLightDir; // Direcion de la luz (en World Space) = normal al patch Bj // Textura auxiliar: texture aux_Tex; sampler2D auxMap = sampler_state { - Texture = (aux_Tex); - ADDRESSU = MIRROR; - ADDRESSV = MIRROR; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (aux_Tex); + ADDRESSU = MIRROR; + ADDRESSV = MIRROR; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; // enviroment map -texture g_txCubeMap; +texture g_txCubeMap; samplerCUBE g_samCubeMap = sampler_state { - Texture = ; - MinFilter = Linear; - MagFilter = Linear; - MipFilter = Linear; + Texture = ; + MinFilter = Linear; + MagFilter = Linear; + MipFilter = Linear; }; // enviroment map -texture g_txCubeMapAgua; +texture g_txCubeMapAgua; samplerCUBE g_samCubeMapAgua = sampler_state { - Texture = ; - MinFilter = Linear; - MagFilter = Linear; - MipFilter = Linear; + Texture = ; + MinFilter = Linear; + MagFilter = Linear; + MipFilter = Linear; }; // ------------------------------------ @@ -89,16 +89,16 @@ sampler_state #define SMAP_SIZE 512 #define EPSILON 0.000005f -texture g_txShadow; // textura para el shadow map +texture g_txShadow; // textura para el shadow map sampler2D g_samShadow = sampler_state { - Texture = ; - MinFilter = Point; - MagFilter = Point; - MipFilter = Point; - AddressU = Clamp; - AddressV = Clamp; + Texture = ; + MinFilter = Point; + MagFilter = Point; + MipFilter = Point; + AddressU = Clamp; + AddressV = Clamp; }; /**************************************************************************************/ @@ -108,68 +108,67 @@ sampler_state //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 Norm : TEXCOORD1; // Normales - float3 Pos : TEXCOORD2; // Posicion real 3d + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float3 Pos : TEXCOORD2; // Posicion real 3d }; //Vertex Shader -VS_OUTPUT vs_main(float4 Pos:POSITION, float3 Normal : NORMAL, float2 Texcoord : TEXCOORD0) +VS_OUTPUT vs_main(float4 Pos : POSITION, float3 Normal : NORMAL, float2 Texcoord : TEXCOORD0) { - VS_OUTPUT Output; + VS_OUTPUT Output; //Proyectar posicion - Output.Position = mul(Pos, matWorldViewProj); + Output.Position = mul(Pos, matWorldViewProj); //Propago las coord. de textura - Output.Texcoord = Texcoord; + Output.Texcoord = Texcoord; // Calculo la posicion real - Output.Pos = mul(Pos, matWorld).xyz; + Output.Pos = mul(Pos, matWorld).xyz; // Transformo la normal y la normalizo - Output.Norm = normalize(mul(Normal, matInverseTransposeWorld)); + Output.Norm = normalize(mul(Normal, matInverseTransposeWorld)); //Output.Norm = normalize(mul(Normal,matWorld)); - return(Output); + return (Output); } //Pixel Shader -float4 ps_main(float2 Texcoord: TEXCOORD0, float3 N : TEXCOORD1, - float3 Pos : TEXCOORD2) : COLOR0 +float4 ps_main(float2 Texcoord : TEXCOORD0, float3 N : TEXCOORD1, float3 Pos : TEXCOORD2) : COLOR0 { - float ld = 0; // luz difusa - float le = 0; // luz specular + float ld = 0; // luz difusa + float le = 0; // luz specular // corrijo la normal - float aux = N.y; - N.y = N.z; - N.z = aux; - N = normalize(N); + float aux = N.y; + N.y = N.z; + N.z = aux; + N = normalize(N); // for(int =0;i 0.001) -{ + // combino con el shadow map + float I = 0.7; + float3 vLight = normalize(float3(wsPos - g_vLightPos)); + float cono = dot(vLight, g_vLightDir); + if (cono > 0.001) + { // coordenada de textura CT - float2 CT = 0.5 * vPosLight.xy / vPosLight.w + float2(0.5, 0.5); - CT.y = 1.0f - CT.y; + float2 CT = 0.5 * vPosLight.xy / vPosLight.w + float2(0.5, 0.5); + CT.y = 1.0f - CT.y; //I = (tex2D( g_samShadow, CT) + EPSILON < vPosLight.z / vPosLight.w)? 0.0f: 1.0f; - float2 vecino = frac(CT*SMAP_SIZE); - float prof = vPosLight.z / vPosLight.w; - float s0 = (tex2D(g_samShadow, float2(CT)) + EPSILON < prof) ? 0.0f : 1.0f; - float s1 = (tex2D(g_samShadow, float2(CT)+float2(1.0 / SMAP_SIZE,0)) + float2 vecino = frac(CT * SMAP_SIZE); + float prof = vPosLight.z / vPosLight.w; + float s0 = (tex2D(g_samShadow, float2(CT)) + EPSILON < prof) ? 0.0f : 1.0f; + float s1 = (tex2D(g_samShadow, float2(CT) + float2(1.0 / SMAP_SIZE, 0)) + EPSILON < prof) ? 0.0f : 1.0f; - float s2 = (tex2D(g_samShadow, float2(CT)+float2(0,1.0 / SMAP_SIZE)) + float s2 = (tex2D(g_samShadow, float2(CT) + float2(0, 1.0 / SMAP_SIZE)) + EPSILON < prof) ? 0.0f : 1.0f; - float s3 = (tex2D(g_samShadow, float2(CT)+float2(1.0 / SMAP_SIZE,1.0 / SMAP_SIZE)) + float s3 = (tex2D(g_samShadow, float2(CT) + float2(1.0 / SMAP_SIZE, 1.0 / SMAP_SIZE)) + EPSILON < prof) ? 0.0f : 1.0f; - I += 0.3*lerp(lerp(s0, s1, vecino.x),lerp(s2, s3, vecino.x),vecino.y); -} + I += 0.3 * lerp(lerp(s0, s1, vecino.x), lerp(s2, s3, vecino.x), vecino.y); + } -fvBaseColor.rgb *= I; + fvBaseColor.rgb *= I; -return fvBaseColor; -//return color_reflejado; -//return color_refractado; -//return float4(Fresnel,Fresnel,Fresnel,1); + return fvBaseColor; + //return color_reflejado; + //return color_refractado; + //return float4(Fresnel,Fresnel,Fresnel,1); } technique RenderAgua { - pass p0 - { - VertexShader = compile vs_3_0 VSAgua(); - PixelShader = compile ps_3_0 PSAgua(); - } + pass p0 + { + VertexShader = compile vs_3_0 VSAgua(); + PixelShader = compile ps_3_0 PSAgua(); + } } /**************************************************************************************/ @@ -457,11 +455,11 @@ void VertShadow(float4 Pos : POSITION, out float2 Depth : TEXCOORD0) { // transformacion estandard - oPos = mul(Pos, matWorld); // uso el del mesh - oPos = mul(oPos, g_mViewLightProj); // pero visto desde la pos. de la luz + oPos = mul(Pos, matWorld); // uso el del mesh + oPos = mul(oPos, g_mViewLightProj); // pero visto desde la pos. de la luz // devuelvo: profundidad = z/w - Depth.xy = oPos.zw; + Depth.xy = oPos.zw; } //----------------------------------------------------------------------------- @@ -472,16 +470,16 @@ void PixShadow(float2 Depth : TEXCOORD0, out float4 Color : COLOR) // parche para ver el shadow map //float k = Depth.x/Depth.y; //Color = (1-k)*500; - Color = Depth.x / Depth.y; + Color = Depth.x / Depth.y; } technique RenderShadow { - pass p0 - { - VertexShader = compile vs_3_0 VertShadow(); - PixelShader = compile ps_3_0 PixShadow(); - } + pass p0 + { + VertexShader = compile vs_3_0 VertShadow(); + PixelShader = compile ps_3_0 PixShadow(); + } } //----------------------------------------------------------------------------- @@ -498,18 +496,18 @@ void VertSceneShadows(float4 iPos : POSITION, ) { // transformo al screen space - oPos = mul(iPos, matWorldViewProj); + oPos = mul(iPos, matWorldViewProj); // propago coordenadas de textura - Tex = iTex; + Tex = iTex; // propago la normal - vNormal = mul(iNormal, (float3x3)matWorldView); + vNormal = mul(iNormal, (float3x3) matWorldView); // propago la posicion del vertice en World space - vPos = mul(iPos, matWorld); + vPos = mul(iPos, matWorld); // propago la posicion del vertice en el espacio de proyeccion de la luz - vPosLight = mul(vPos, g_mViewLightProj); + vPosLight = mul(vPos, g_mViewLightProj); } //----------------------------------------------------------------------------- @@ -519,39 +517,39 @@ float4 PixSceneShadows(float2 Tex : TEXCOORD0, float4 vPos : TEXCOORD1, float3 vNormal : TEXCOORD2, float4 vPosLight : TEXCOORD3 -) :COLOR +) : COLOR { - float3 vLight = normalize(float3(vPos - g_vLightPos)); - float cono = dot(vLight, g_vLightDir); - float4 K = 0.0; - if (cono > 0.1) - { + float3 vLight = normalize(float3(vPos - g_vLightPos)); + float cono = dot(vLight, g_vLightDir); + float4 K = 0.0; + if (cono > 0.1) + { // coordenada de textura CT - float2 CT = 0.5 * vPosLight.xy / vPosLight.w + float2(0.5, 0.5); - CT.y = 1.0f - CT.y; + float2 CT = 0.5 * vPosLight.xy / vPosLight.w + float2(0.5, 0.5); + CT.y = 1.0f - CT.y; - float2 vecino = frac(CT*SMAP_SIZE); - float prof = vPosLight.z / vPosLight.w; - float s0 = (tex2D(g_samShadow, float2(CT)) + EPSILON < prof) ? 0.0f : 1.0f; - float s1 = (tex2D(g_samShadow, float2(CT)+float2(1.0 / SMAP_SIZE,0)) + float2 vecino = frac(CT * SMAP_SIZE); + float prof = vPosLight.z / vPosLight.w; + float s0 = (tex2D(g_samShadow, float2(CT)) + EPSILON < prof) ? 0.0f : 1.0f; + float s1 = (tex2D(g_samShadow, float2(CT) + float2(1.0 / SMAP_SIZE, 0)) + EPSILON < prof) ? 0.0f : 1.0f; - float s2 = (tex2D(g_samShadow, float2(CT)+float2(0,1.0 / SMAP_SIZE)) + float s2 = (tex2D(g_samShadow, float2(CT) + float2(0, 1.0 / SMAP_SIZE)) + EPSILON < prof) ? 0.0f : 1.0f; - float s3 = (tex2D(g_samShadow, float2(CT)+float2(1.0 / SMAP_SIZE,1.0 / SMAP_SIZE)) + float s3 = (tex2D(g_samShadow, float2(CT) + float2(1.0 / SMAP_SIZE, 1.0 / SMAP_SIZE)) + EPSILON < prof) ? 0.0f : 1.0f; - K = lerp(lerp(s0, s1, vecino.x),lerp(s2, s3, vecino.x),vecino.y); - } + K = lerp(lerp(s0, s1, vecino.x), lerp(s2, s3, vecino.x), vecino.y); + } - float4 color_base = tex2D(diffuseMap, Tex); - color_base.rgb *= 0.7 + 0.3*K; - return color_base; + float4 color_base = tex2D(diffuseMap, Tex); + color_base.rgb *= 0.7 + 0.3 * K; + return color_base; } technique RenderSceneShadows { - pass p0 - { - VertexShader = compile vs_3_0 VertSceneShadows(); - PixelShader = compile ps_3_0 PixSceneShadows(); - } + pass p0 + { + VertexShader = compile vs_3_0 VertSceneShadows(); + PixelShader = compile ps_3_0 PixSceneShadows(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/WorkshopShaders/EnvMap.fx b/TGC.Examples/Shaders/WorkshopShaders/EnvMap.fx index f59e9a09..ef949492 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/EnvMap.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/EnvMap.fx @@ -16,12 +16,12 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; float3 fvLightPosition = float3(-100.00, 100.00, -100.00); @@ -31,13 +31,13 @@ float FBias = 0.4; int FPower = 1; float FEscala = 0.5; -float k_la = 0.7; // luz ambiente global -float k_ld = 0.4; // luz difusa -float k_ls = 1.0; // luz specular +float k_la = 0.7; // luz ambiente global +float k_ld = 0.4; // luz difusa +float k_ls = 1.0; // luz specular float fSpecularPower = 16.84; -float kx = 0.5; // coef. de reflexion -float kc = 0.5; // coef. de refraccion +float kx = 0.5; // coef. de reflexion +float kc = 0.5; // coef. de refraccion bool usar_fresnel = 1; // Textura auxiliar: @@ -45,23 +45,23 @@ texture aux_Tex; sampler2D auxMap = sampler_state { - Texture = (aux_Tex); - ADDRESSU = MIRROR; - ADDRESSV = MIRROR; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (aux_Tex); + ADDRESSU = MIRROR; + ADDRESSV = MIRROR; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; // enviroment map -texture g_txCubeMap; +texture g_txCubeMap; samplerCUBE g_samCubeMap = sampler_state { - Texture = ; - MinFilter = Linear; - MagFilter = Linear; - MipFilter = Linear; + Texture = ; + MinFilter = Linear; + MagFilter = Linear; + MipFilter = Linear; }; /**************************************************************************************/ @@ -71,68 +71,67 @@ sampler_state //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 Norm : TEXCOORD1; // Normales - float3 Pos : TEXCOORD2; // Posicion real 3d + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float3 Pos : TEXCOORD2; // Posicion real 3d }; //Vertex Shader -VS_OUTPUT vs_main(float4 Pos:POSITION, float3 Normal : NORMAL, float2 Texcoord : TEXCOORD0) +VS_OUTPUT vs_main(float4 Pos : POSITION, float3 Normal : NORMAL, float2 Texcoord : TEXCOORD0) { - VS_OUTPUT Output; + VS_OUTPUT Output; //Proyectar posicion - Output.Position = mul(Pos, matWorldViewProj); + Output.Position = mul(Pos, matWorldViewProj); //Propago las coord. de textura - Output.Texcoord = Texcoord; + Output.Texcoord = Texcoord; // Calculo la posicion real - Output.Pos = mul(Pos, matWorld).xyz; + Output.Pos = mul(Pos, matWorld).xyz; // Transformo la normal y la normalizo - Output.Norm = normalize(mul(Normal, matInverseTransposeWorld)); + Output.Norm = normalize(mul(Normal, matInverseTransposeWorld)); //Output.Norm = normalize(mul(Normal,matWorld)); - return(Output); + return (Output); } //Pixel Shader -float4 ps_main(float2 Texcoord: TEXCOORD0, float3 N : TEXCOORD1, - float3 Pos : TEXCOORD2) : COLOR0 +float4 ps_main(float2 Texcoord : TEXCOORD0, float3 N : TEXCOORD1, float3 Pos : TEXCOORD2) : COLOR0 { - float ld = 0; // luz difusa - float le = 0; // luz specular + float ld = 0; // luz difusa + float le = 0; // luz specular // corrijo la normal - float aux = N.y; - N.y = N.z; - N.z = aux; - N = normalize(N); + float aux = N.y; + N.y = N.z; + N.z = aux; + N = normalize(N); // for(int =0;i; - ADDRESSU = CLAMP; - ADDRESSV = CLAMP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 Norm : TEXCOORD1; // Normales - float3 Pos : TEXCOORD2; // Posicion real 3d + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float3 Pos : TEXCOORD2; // Posicion real 3d }; //Vertex Shader VS_OUTPUT vs_main(VS_INPUT Input) { - VS_OUTPUT Output; + VS_OUTPUT Output; //Proyectar posicion - Output.Position = mul(Input.Position, matWorldViewProj); + Output.Position = mul(Input.Position, matWorldViewProj); //Las Texcoord quedan igual - Output.Texcoord = Input.Texcoord; + Output.Texcoord = Input.Texcoord; // Calculo la posicion real - float4 pos_real = mul(Input.Position, matWorld); - Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); + float4 pos_real = mul(Input.Position, matWorld); + Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); // Transformo la normal y la normalizo //Output.Norm = normalize(mul(Input.Normal,matInverseTransposeWorld)); - Output.Norm = normalize(mul(Input.Normal, matWorld)); - return(Output); + Output.Norm = normalize(mul(Input.Normal, matWorld)); + return (Output); } //Pixel Shader -float4 ps_main(float3 Texcoord: TEXCOORD0, float3 N : TEXCOORD1, +float4 ps_main(float3 Texcoord : TEXCOORD0, float3 N : TEXCOORD1, float3 Pos : TEXCOORD2) : COLOR0 { //Obtener el texel de textura - float4 fvBaseColor = tex2D(diffuseMap, Texcoord); - return fvBaseColor; + float4 fvBaseColor = tex2D(diffuseMap, Texcoord); + return fvBaseColor; } technique DefaultTechnique { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_main(); - PixelShader = compile ps_3_0 ps_main(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_main(); + } } void VSCopy(float4 vPos : POSITION, float2 vTex : TEXCOORD0, out float4 oPos : POSITION, out float2 oScreenPos : TEXCOORD0) { - oPos = vPos; - oScreenPos = vTex; - oPos.w = 1; + oPos = vPos; + oScreenPos = vTex; + oPos.w = 1; } float4 PSPostProcess(in float2 Tex : TEXCOORD0, in float2 vpos : VPOS) : COLOR0 { - float4 ColorBase = tex2D(RenderTarget, Tex); + float4 ColorBase = tex2D(RenderTarget, Tex); // float4 ColorBase = tex2D(RenderTarget, Tex + float2(34*sin(time+Tex.x*15)/screen_dx,25*cos(time+Tex.y*15)/screen_dy)); - return ColorBase; + return ColorBase; // gray scale // Y = 0.2126 R + 0.7152 G + 0.0722 B @@ -113,23 +113,194 @@ static const int kernel_r = 6; static const int kernel_size = 13; static const float Kernel[kernel_size] = { - 0.002216, 0.008764, 0.026995, 0.064759, 0.120985, 0.176033, 0.199471, 0.176033, 0.120985, 0.064759, 0.026995, 0.008764, 0.002216, + 0.002216, 0.008764, 0.026995, 0.064759, 0.120985, 0.176033, 0.199471, 0.176033, 0.120985, 0.064759, 0.026995, 0.008764, 0.002216, }; -void Blur(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) +void Blur(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) { - Color = 0; - for (int i = 0; i < kernel_size; ++i) - for (int j = 0; j < kernel_size; ++j) - Color += tex2D(RenderTarget, screen_pos + float2((float)(i - kernel_r) / screen_dx, (float)(j - kernel_r) / screen_dy)) * Kernel[i] * Kernel[j]; - Color.a = 1; + Color = 0; + for (int i = 0; i < kernel_size; ++i) + for (int j = 0; j < kernel_size; ++j) + Color += tex2D(RenderTarget, screen_pos + float2((float) (i - kernel_r) / screen_dx, (float) (j - kernel_r) / screen_dy)) * Kernel[i] * Kernel[j]; + Color.a = 1; } technique PostProcess { - pass Pass_0 - { - VertexShader = compile vs_3_0 VSCopy(); - PixelShader = compile ps_3_0 PSPostProcess(); - } -} \ No newline at end of file + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSPostProcess(); + } +} + +// Distorciones, fuente: +// http://en.wikipedia.org/wiki/Distortion_(optics)#Software_correction + +// Factor de distorcion del ojo de pez +float fish_kU = 0.25f; +float fish_kV = 0.25f; + +bool grid = false; +float4 PSOjoPez(in float2 Tex : TEXCOORD0, in float2 vpos : VPOS) : COLOR0 +{ + // Transformo las coordinates de (0.0 - 1.0) a (-0.5 - 0.5) + float X = Tex.x - 0.5f; + float Y = Tex.y - 0.5f; + // Computa la distorcion ojo de pez + float r = pow(X, 2) + pow(Y, 2); + float U = pow(r, fish_kU) * X + 0.5f; + float V = pow(r, fish_kV) * Y + 0.5f; + float4 rta; + int pos_x = round(U * screen_dx); + int pos_y = round(V * screen_dy); + if (grid && (pos_x % 50 == 1 || pos_y % 50 == 1)) + rta = float4(1, 1, 1, 1); + else + rta = tex2D(RenderTarget, float2(U, V)); + return rta; +} + +float4 PSPincusion(in float2 Tex : TEXCOORD0, in float2 vpos : VPOS) : COLOR0 +{ + float2 center = float2(0.5, 0.5); + float dist = distance(center, Tex); + Tex -= center; + float percent = 1.0 - ((0.5 - dist) / 0.5) * fish_kU; + Tex *= percent; + Tex += center; + float4 rta; + int pos_x = round(Tex.x * screen_dx); + int pos_y = round(Tex.y * screen_dy); + if (grid && (pos_x % 50 == 1 || pos_y % 50 == 1)) + rta = float4(1, 1, 1, 1); + else + rta = tex2D(RenderTarget, Tex); + return rta; + +} + +float4 PSBarrel(in float2 Tex : TEXCOORD0, in float2 vpos : VPOS) : COLOR0 +{ + float2 center = float2(0.5, 0.5); + float dist = distance(center, Tex); + Tex -= center; + float percent = 1.0 + ((0.5 - dist) / 0.5) * fish_kU; + Tex *= percent; + Tex += center; + float4 rta; + int pos_x = round(Tex.x * screen_dx); + int pos_y = round(Tex.y * screen_dy); + if (grid && (pos_x % 50 == 1 || pos_y % 50 == 1)) + rta = float4(1, 1, 1, 1); + else + rta = tex2D(RenderTarget, Tex); + return rta; + +} + + +technique OjoPez +{ + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSOjoPez(); + } + +} + + +technique Pincusion +{ + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSPincusion(); + } + +} + +technique Barrel +{ + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSBarrel(); + } + +} + +float4 PSCopy(in float2 Tex : TEXCOORD0) : COLOR0 +{ + return tex2D(RenderTarget, Tex); +} + + +technique ScreenCopy +{ + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSCopy(); + } + +} + + +// Traducidas del SDK del OCULUS RIFF +/* +"vec2 HmdWarp(vec2 in01)\n" + "{\n" + " vec2 theta = (in01 - LensCenter) * ScaleIn;\n" // Scales to [-1, 1] + " float rSq = theta.x * theta.x + theta.y * theta.y;\n" + " vec2 theta1 = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + " + " HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n" + " return LensCenter + Scale * theta1;\n" + "}\n" + "void main()\n" + "{\n" + " vec2 tc = HmdWarp(oTexCoord);\n" + " if (!all(equal(clamp(tc, ScreenCenter-vec2(0.25,0.5), ScreenCenter+vec2(0.25,0.5)), tc)))\n" + " gl_FragColor = vec4(0);\n" + " else\n" + " gl_FragColor = texture2D(Texture0, tc);\n" + "}\n"; + */ + +float2 LensCenter = float2(0.5, 0.5); +float ScaleIn = 1.5; +float Scale = 0.1; +float4 HmdWarpParam = float4(1.0f, 0.22f, 0.24f, 0.041f); + +float2 HmdWarp(float2 in01) +{ + float2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1] + float rSq = theta.x * theta.x + theta.y * theta.y; + float2 theta1 = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq); + + return LensCenter + Scale * theta1; +} + + +float4 ps_oculus(in float2 Tex : TEXCOORD0) : COLOR0 +{ + float2 tc = HmdWarp(Tex); + float4 rta; + if (tc.x >= 0 && tc.x <= 1 && tc.y >= 0 && tc.y <= 1) + rta = tex2D(RenderTarget, tc); + else + rta = float4(0, 0, 0.5, 1); + return rta; +} + +technique OculusRift +{ + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 ps_oculus(); + } + +} diff --git a/TGC.Examples/Shaders/WorkshopShaders/GPUAttack.fx b/TGC.Examples/Shaders/WorkshopShaders/GPUAttack.fx index 657d053a..d0ecbafc 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/GPUAttack.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/GPUAttack.fx @@ -1,6 +1,6 @@ #define MAX_DS 512 -texture g_RenderTarget; // Render target +texture g_RenderTarget; // Render target int a = 33; int c = 213; @@ -11,43 +11,43 @@ int4 hash_buscado; sampler RenderTarget = sampler_state { - Texture = ; - MipFilter = NONE; - MinFilter = NONE; - MagFilter = NONE; + Texture = ; + MipFilter = NONE; + MinFilter = NONE; + MagFilter = NONE; }; void Hash(int4 clave, out int4 buffer) { - int k = (clave[0] + clave[1] + clave[2] + clave[3]) % 256; - for (int i = 0; i < 4; ++i) - { - k = round(round(a*k + c) % m); - buffer[i] = k; - k = round(k + clave[i]); - } + int k = (clave[0] + clave[1] + clave[2] + clave[3]) % 256; + for (int i = 0; i < 4; ++i) + { + k = round(round(a * k + c) % m); + buffer[i] = k; + k = round(k + clave[i]); + } } float4 PSComputeHash(float2 pos : VPOS) : COLOR0 { - int4 hash; - int4 clave; - int group_x = floor((float)pos.x / 32.0); - int x = floor((float)pos.x % 32.0); - int group_y = floor((float)pos.y / 32.0); - int y = floor((float)pos.y % 32.0); - - clave[0] = 'A' + group_x; - clave[1] = 'A' + group_y; - clave[2] = 'A' + x; - clave[3] = 'A' + y; - Hash(clave,hash); + int4 hash; + int4 clave; + int group_x = floor((float) pos.x / 32.0); + int x = floor((float) pos.x % 32.0); + int group_y = floor((float) pos.y / 32.0); + int y = floor((float) pos.y % 32.0); + + clave[0] = 'A' + group_x; + clave[1] = 'A' + group_y; + clave[2] = 'A' + x; + clave[3] = 'A' + y; + Hash(clave, hash); // compara con el hash buscado - if (distance(hash,hash_buscado) == 0) - return float4(1,1,1,1); - else - return float4(0,0,0,1); + if (distance(hash, hash_buscado) == 0) + return float4(1, 1, 1, 1); + else + return float4(0, 0, 0, 1); // retorna el hash pp dicho //return float4((float)hash[0]/255.0,(float)hash[1]/255.0,(float)hash[2]/255.0,(float)hash[3]/255.0); @@ -55,29 +55,29 @@ float4 PSComputeHash(float2 pos : VPOS) : COLOR0 void vs_copy(float4 vPos : POSITION, float2 vTex : TEXCOORD0, out float4 oPos : POSITION, out float2 oScreenPos : TEXCOORD0) { - oPos = vPos; - oScreenPos = vTex; - oPos.w = 1; + oPos = vPos; + oScreenPos = vTex; + oPos.w = 1; } technique ComputeHash { - pass P0 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 PSComputeHash(); - } + pass P0 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 PSComputeHash(); + } } void Hash6(int clave[6], out int buffer[6]) { - int k = round(clave[0] + clave[1] + clave[2] + clave[3] + clave[4] + clave[5]) % 256; - for (int i = 0; i < 6; ++i) - { - k = round(round(a*k + c) % m); - buffer[i] = k; - k = round(k + clave[i]); - } + int k = round(clave[0] + clave[1] + clave[2] + clave[3] + clave[4] + clave[5]) % 256; + for (int i = 0; i < 6; ++i) + { + k = round(round(a * k + c) % m); + buffer[i] = k; + k = round(k + clave[i]); + } } int prefix_x = 0; @@ -86,30 +86,30 @@ int hash_buscado6[6]; float4 PSComputeHash6(float2 pos : VPOS) : COLOR0 { - int hash[6]; - int clave[6]; - int group_x = floor((float)pos.x / 32.0); - int x = floor((float)pos.x % 32.0); - int group_y = floor((float)pos.y / 32.0); - int y = floor((float)pos.y % 32.0); - - clave[0] = 'A' + prefix_x; - clave[1] = 'A' + prefix_y; - clave[2] = 'A' + group_x; - clave[3] = 'A' + group_y; - clave[4] = 'A' + x; - clave[5] = 'A' + y; - Hash6(clave,hash); + int hash[6]; + int clave[6]; + int group_x = floor((float) pos.x / 32.0); + int x = floor((float) pos.x % 32.0); + int group_y = floor((float) pos.y / 32.0); + int y = floor((float) pos.y % 32.0); + + clave[0] = 'A' + prefix_x; + clave[1] = 'A' + prefix_y; + clave[2] = 'A' + group_x; + clave[3] = 'A' + group_y; + clave[4] = 'A' + x; + clave[5] = 'A' + y; + Hash6(clave, hash); // compara con el hash buscado - float dist = 0; - for (int i = 0; i < 6; ++i) - dist += abs(hash[i] - hash_buscado6[i]); + float dist = 0; + for (int i = 0; i < 6; ++i) + dist += abs(hash[i] - hash_buscado6[i]); - if (dist < 0.01) - return float4(1,1,1,1); - else - return float4(0,0,0,1); + if (dist < 0.01) + return float4(1, 1, 1, 1); + else + return float4(0, 0, 0, 1); /* clave[0] = 'A'; clave[1] = 'A'; @@ -124,9 +124,9 @@ float4 PSComputeHash6(float2 pos : VPOS) : COLOR0 technique ComputeHash6 { - pass P0 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 PSComputeHash6(); - } + pass P0 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 PSComputeHash6(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/WorkshopShaders/GPUcompute.fx b/TGC.Examples/Shaders/WorkshopShaders/GPUcompute.fx index 6b14e824..ef8a97fd 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/GPUcompute.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/GPUcompute.fx @@ -4,7 +4,7 @@ float3 fvLightPosition = float3(-100.00, 100.00, -100.00); float3 fvEyePosition = float3(0.00, 0.00, -100.00); float4x4 matViewProjection; -float screen_dx; // tamaño de la pantalla en pixels +float screen_dx; // tamaño de la pantalla en pixels float screen_dy; float4x4 matWorld; @@ -12,9 +12,9 @@ float4x4 matWorldView; float4x4 matWorldViewProj; float4x4 matInverseTransposeWorld; -float k_la = 0.3; // luz ambiente global -float k_ld = 0.9; // luz difusa -float k_ls = 0.4; // luz specular +float k_la = 0.3; // luz ambiente global +float k_ld = 0.9; // luz difusa +float k_ls = 0.4; // luz specular float fSpecularPower = 16.84; float elapsedTime = 0; @@ -26,12 +26,12 @@ float Kp = 1; texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = MIRROR; - ADDRESSV = MIRROR; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = MIRROR; + ADDRESSV = MIRROR; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; // mapa de Velocidad @@ -39,10 +39,10 @@ texture g_pVelocidad; sampler Velocidad = sampler_state { - Texture = ; - MipFilter = NONE; - MinFilter = NONE; - MagFilter = NONE; + Texture = ; + MipFilter = NONE; + MinFilter = NONE; + MagFilter = NONE; }; // mapa de Posiciones @@ -50,10 +50,10 @@ texture g_pPos; sampler Posicion = sampler_state { - Texture = ; - MipFilter = NONE; - MinFilter = NONE; - MagFilter = NONE; + Texture = ; + MipFilter = NONE; + MinFilter = NONE; + MagFilter = NONE; }; // Height map @@ -61,10 +61,10 @@ texture height_map; sampler2D heightMap = sampler_state { - Texture = ; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = NONE; + Texture = ; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = NONE; }; float currentScaleXZ = 100; @@ -73,93 +73,93 @@ float currentScaleY = 10; // ------------------------------------ struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 Norm : TEXCOORD1; // Normales - float3 Pos : TEXCOORD2; // Posicion real 3d + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float3 Pos : TEXCOORD2; // Posicion real 3d }; //Vertex Shader Trivial: VS_OUTPUT vs_main(VS_INPUT Input) { - VS_OUTPUT Output; + VS_OUTPUT Output; //Proyectar posicion - Output.Position = mul(Input.Position, matWorldViewProj); + Output.Position = mul(Input.Position, matWorldViewProj); //Las Texcoord quedan igual - Output.Texcoord = Input.Texcoord; + Output.Texcoord = Input.Texcoord; // Calculo la posicion real - float4 pos_real = mul(Input.Position, matWorld); - Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); + float4 pos_real = mul(Input.Position, matWorld); + Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); // Transformo la normal y la normalizo - Output.Norm = normalize(mul(Input.Normal, matInverseTransposeWorld)); - return(Output); + Output.Norm = normalize(mul(Input.Normal, matInverseTransposeWorld)); + return (Output); } //Pixel Shader -float4 ps_main(float3 Texcoord: TEXCOORD0, float3 N : TEXCOORD1, +float4 ps_main(float3 Texcoord : TEXCOORD0, float3 N : TEXCOORD1, float3 Pos : TEXCOORD2) : COLOR0 { - float ld = 0; // luz difusa - float le = 0; // luz specular + float ld = 0; // luz difusa + float le = 0; // luz specular - N = normalize(N); + N = normalize(N); // 1- calculo la luz diffusa - float3 LD = normalize(fvLightPosition - float3(Pos.x,Pos.y,Pos.z)); - ld += saturate(dot(N, LD))*k_ld; + float3 LD = normalize(fvLightPosition - float3(Pos.x, Pos.y, Pos.z)); + ld += saturate(dot(N, LD)) * k_ld; // 2- calcula la reflexion specular - float3 D = normalize(float3(Pos.x,Pos.y,Pos.z) - fvEyePosition); - float ks = saturate(dot(reflect(LD,N), D)); - ks = pow(ks,fSpecularPower); - le += ks*k_ls; + float3 D = normalize(float3(Pos.x, Pos.y, Pos.z) - fvEyePosition); + float ks = saturate(dot(reflect(LD, N), D)); + ks = pow(ks, fSpecularPower); + le += ks * k_ls; //Obtener el texel de textura - float4 fvBaseColor = tex2D(diffuseMap, Texcoord); + float4 fvBaseColor = tex2D(diffuseMap, Texcoord); // suma luz diffusa, ambiente y especular - float4 RGBColor = 0; - RGBColor.rgb = saturate(fvBaseColor*(saturate(k_la + ld)) + le); - return RGBColor; + float4 RGBColor = 0; + RGBColor.rgb = saturate(fvBaseColor * (saturate(k_la + ld)) + le); + return RGBColor; } technique DefaultTechnique { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_main(); - PixelShader = compile ps_3_0 ps_main(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_main(); + } } // ----------------------------------------------- struct PS_OUTPUT { - float4 Velocity : COLOR0; - float4 Position : COLOR1; + float4 Velocity : COLOR0; + float4 Position : COLOR1; }; float CalcularAltura(float x, float y) { - float u = y / (currentScaleXZ*map_size) + 0.5; - float v = x / (currentScaleXZ*map_size) + 0.5; - float3 T0 = tex2D(heightMap, float2(u + map_desf, v + map_desf)); - float H0 = T0.r*0.299 + T0.g*0.587 + T0.b*0.114; - return 255 * H0*currentScaleY; + float u = y / (currentScaleXZ * map_size) + 0.5; + float v = x / (currentScaleXZ * map_size) + 0.5; + float3 T0 = tex2D(heightMap, float2(u + map_desf, v + map_desf)); + float H0 = T0.r * 0.299 + T0.g * 0.587 + T0.b * 0.114; + return 255 * H0 * currentScaleY; } -PS_OUTPUT PSInitVel(float2 Texcoord: TEXCOORD0) +PS_OUTPUT PSInitVel(float2 Texcoord : TEXCOORD0) { - PS_OUTPUT Output; - Output.Velocity = float4(0, 0, 0, 0); + PS_OUTPUT Output; + Output.Velocity = float4(0, 0, 0, 0); /* float x0 = 0.2 + 0.6*(Texcoord.x-0.5)*currentScaleXZ*map_size; @@ -167,91 +167,91 @@ PS_OUTPUT PSInitVel(float2 Texcoord: TEXCOORD0) Output.Position = float4(x0,z0,220+CalcularAltura(x0, z0),0); */ - float an = 200 * Texcoord.x*3.1415; - float z0 = 0.1*(Texcoord.y - 0.5)*currentScaleXZ*map_size; - Output.Position = float4(sin(an) * 20, cos(an) * 20 - 1000, 2000 + z0 * 50, 0); + float an = 200 * Texcoord.x * 3.1415; + float z0 = 0.1 * (Texcoord.y - 0.5) * currentScaleXZ * map_size; + Output.Position = float4(sin(an) * 20, cos(an) * 20 - 1000, 2000 + z0 * 50, 0); - return Output; + return Output; } -PS_OUTPUT PSComputeVel(float2 Texcoord: TEXCOORD0) +PS_OUTPUT PSComputeVel(float2 Texcoord : TEXCOORD0) { - PS_OUTPUT Output; - - float4 Vel = tex2D(Velocidad, Texcoord); - float vel_x = Vel.x; - float vel_z = Vel.y; - - float4 Pos = tex2D(Posicion, Texcoord); - float x0 = Pos.x; - float z0 = Pos.y; - float H = CalcularAltura(x0, z0); - float ddx, ddz, alfa; - if (Pos.z > H + 10) - { - H = Pos.z - elapsedTime * 500; - ddx = ddz = 0; - alfa = 0; - } - else - { - float dt = 20; - ddx = (CalcularAltura(x0 + dt, z0) - H) / dt; - ddz = (CalcularAltura(x0, z0 + dt) - H) / dt; - vel_x -= elapsedTime * ddx * 150; - vel_z -= elapsedTime * ddz * 150; + PS_OUTPUT Output; + + float4 Vel = tex2D(Velocidad, Texcoord); + float vel_x = Vel.x; + float vel_z = Vel.y; + + float4 Pos = tex2D(Posicion, Texcoord); + float x0 = Pos.x; + float z0 = Pos.y; + float H = CalcularAltura(x0, z0); + float ddx, ddz, alfa; + if (Pos.z > H + 10) + { + H = Pos.z - elapsedTime * 500; + ddx = ddz = 0; + alfa = 0; + } + else + { + float dt = 20; + ddx = (CalcularAltura(x0 + dt, z0) - H) / dt; + ddz = (CalcularAltura(x0, z0 + dt) - H) / dt; + vel_x -= elapsedTime * ddx * 150; + vel_z -= elapsedTime * ddz * 150; // rozamiento - vel_x *= 1 - elapsedTime / 25; - vel_z *= 1 - elapsedTime / 25; + vel_x *= 1 - elapsedTime / 25; + vel_z *= 1 - elapsedTime / 25; - x0 += elapsedTime * vel_x; - z0 += elapsedTime * vel_z; + x0 += elapsedTime * vel_x; + z0 += elapsedTime * vel_z; // calculo el angulo rodado: - float dx = x0 - Pos.x; - float dz = z0 - Pos.y; - alfa = sqrt(dx*dx + dz*dz) / Kp; - } + float dx = x0 - Pos.x; + float dz = z0 - Pos.y; + alfa = sqrt(dx * dx + dz * dz) / Kp; + } - Output.Velocity = float4(vel_x, vel_z, ddx, ddz); - Output.Position = float4(x0, z0, H, alfa); + Output.Velocity = float4(vel_x, vel_z, ddx, ddz); + Output.Position = float4(x0, z0, H, alfa); - return Output; + return Output; } -float4 PSPreview(float2 Texcoord: TEXCOORD0) : COLOR0 +float4 PSPreview(float2 Texcoord : TEXCOORD0) : COLOR0 { - float4 fvVelPos = tex2D(Velocidad, Texcoord); - float2 vel = fvVelPos.xy; - float2 pos = fvVelPos.zw; - return float4(1,1,1,1); + float4 fvVelPos = tex2D(Velocidad, Texcoord); + float2 vel = fvVelPos.xy; + float2 pos = fvVelPos.zw; + return float4(1, 1, 1, 1); } void vs_copy(float4 vPos : POSITION, float2 vTex : TEXCOORD0, out float4 oPos : POSITION, out float2 oScreenPos : TEXCOORD0) { - oPos = vPos; - oScreenPos = vTex; - oPos.w = 1; + oPos = vPos; + oScreenPos = vTex; + oPos.w = 1; } // Genera el mapa de velocidad technique ComputeVel { - pass P0 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 PSInitVel(); - } - pass P1 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 PSComputeVel(); - } - - pass P2 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 PSPreview(); - } + pass P0 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 PSInitVel(); + } + pass P1 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 PSComputeVel(); + } + + pass P2 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 PSPreview(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/WorkshopShaders/GaussianBlur.fx b/TGC.Examples/Shaders/WorkshopShaders/GaussianBlur.fx index 8d63ac18..11128449 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/GaussianBlur.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/GaussianBlur.fx @@ -16,119 +16,165 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; -float screen_dx; // tamaño de la pantalla en pixels +float screen_dx; // tamaño de la pantalla en pixels float screen_dy; +float KLum = 1; // factor de luminancia //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; texture g_RenderTarget; sampler RenderTarget = sampler_state { - Texture = ; - ADDRESSU = CLAMP; - ADDRESSV = CLAMP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; texture g_GlowMap; sampler GlowMap = sampler_state { - Texture = ; - ADDRESSU = CLAMP; - ADDRESSV = CLAMP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; +}; + + +// textura de 1 x 1 que tiene el valor promedio de luminance +texture g_Luminance; +sampler Luminance = +sampler_state +{ + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = POINT; + MAGFILTER = POINT; + MIPFILTER = POINT; +}; + +// textura de 1 x 1 que tiene el valor promedio de luminance +texture g_Luminance_ant; +sampler Luminance_ant = +sampler_state +{ + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = POINT; + MAGFILTER = POINT; + MIPFILTER = POINT; +}; + +// Depth of field +float zn = 1; // near plane +float zf = 10000; // far plane +float zfoco = 300; // focus plane +float blur_k = 0.5; // factor de desenfoque + +texture g_BlurFactor; +sampler BlurFactor = +sampler_state +{ + Texture = ; + MipFilter = Point; + MinFilter = Point; + MagFilter = Point; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 Norm : TEXCOORD1; // Normales - float3 Pos : TEXCOORD2; // Posicion real 3d + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float3 Pos : TEXCOORD2; // Posicion real 3d }; //Vertex Shader VS_OUTPUT vs_main(VS_INPUT Input) { - VS_OUTPUT Output; + VS_OUTPUT Output; //Proyectar posicion - Output.Position = mul(Input.Position, matWorldViewProj); + Output.Position = mul(Input.Position, matWorldViewProj); //Las Texcoord quedan igual - Output.Texcoord = Input.Texcoord; + Output.Texcoord = Input.Texcoord; // Calculo la posicion real - float4 pos_real = mul(Input.Position, matWorld); - Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); + float4 pos_real = mul(Input.Position, matWorld); + Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); // Transformo la normal y la normalizo //Output.Norm = normalize(mul(Input.Normal,matInverseTransposeWorld)); - Output.Norm = normalize(mul(Input.Normal, matWorld)); - return(Output); + Output.Norm = normalize(mul(Input.Normal, matWorld)); + return (Output); } //Pixel Shader -float4 ps_main(float3 Texcoord: TEXCOORD0, float3 N : TEXCOORD1, +float4 ps_main(float3 Texcoord : TEXCOORD0, float3 N : TEXCOORD1, float3 Pos : TEXCOORD2) : COLOR0 { //Obtener el texel de textura - float4 fvBaseColor = tex2D(diffuseMap, Texcoord); - return fvBaseColor; + float4 fvBaseColor = tex2D(diffuseMap, Texcoord); + // aplico el factor de luminancia + fvBaseColor.rgb *= KLum; + return fvBaseColor; } technique DefaultTechnique { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_main(); - PixelShader = compile ps_3_0 ps_main(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_main(); + } } // dibuja negro (tiene que ocultar lo que esta oscuro) -float4 PSOscuros(float3 Texcoord: TEXCOORD0) : COLOR0 +float4 PSOscuros(float3 Texcoord : TEXCOORD0) : COLOR0 { - float4 fvBaseColor = tex2D(diffuseMap, Texcoord); - return float4(0,0,0,fvBaseColor.a); + float4 fvBaseColor = tex2D(diffuseMap, Texcoord); + return float4(0, 0, 0, fvBaseColor.a); } technique DibujarObjetosOscuros { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_main(); - PixelShader = compile ps_3_0 PSOscuros(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 PSOscuros(); + } } void VSCopy(float4 vPos : POSITION, float2 vTex : TEXCOORD0, out float4 oPos : POSITION, out float2 oScreenPos : TEXCOORD0) { - oPos = vPos; - oScreenPos = vTex; - oPos.w = 1; + oPos = vPos; + oScreenPos = vTex; + oPos.w = 1; } // Gaussian Blur @@ -137,97 +183,255 @@ static const int kernel_r = 6; static const int kernel_size = 13; static const float Kernel[kernel_size] = { - 0.002216, 0.008764, 0.026995, 0.064759, 0.120985, 0.176033, 0.199471, 0.176033, 0.120985, 0.064759, 0.026995, 0.008764, 0.002216, + 0.002216, 0.008764, 0.026995, 0.064759, 0.120985, 0.176033, 0.199471, 0.176033, 0.120985, 0.064759, 0.026995, 0.008764, 0.002216, }; -void Blur(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) +void Blur(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) { - Color = 0; - for (int i = 0; i < kernel_size; ++i) - for (int j = 0; j < kernel_size; ++j) - Color += tex2D(RenderTarget, screen_pos + float2((float)(i - kernel_r) / screen_dx, (float)(j - kernel_r) / screen_dy)) * Kernel[i] * Kernel[j]; - Color.a = 1; + Color = 0; + for (int i = 0; i < kernel_size; ++i) + for (int j = 0; j < kernel_size; ++j) + Color += tex2D(RenderTarget, screen_pos + float2((float) (i - kernel_r) / screen_dx, (float) (j - kernel_r) / screen_dy)) * Kernel[i] * Kernel[j]; + Color.a = 1; } technique GaussianBlur { - pass Pass_0 - { - VertexShader = compile vs_3_0 VSCopy(); - PixelShader = compile ps_3_0 Blur(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 Blur(); + } } -void BlurH(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) +void BlurH(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) { - Color = 0; - for (int i = 0; i < kernel_size; ++i) - Color += tex2D(RenderTarget, screen_pos + float2((float)(i - kernel_r) / screen_dx, 0)) * Kernel[i]; - Color.a = 1; + Color = 0; + for (int i = 0; i < kernel_size; ++i) + Color += tex2D(RenderTarget, screen_pos + float2((float) (i - kernel_r) / screen_dx, 0)) * Kernel[i]; + Color.a = 1; } -void BlurV(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) +void BlurV(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) { - Color = 0; - for (int i = 0; i < kernel_size; ++i) - Color += tex2D(RenderTarget, screen_pos + float2(0, (float)(i - kernel_r) / screen_dy)) * Kernel[i]; - Color.a = 1; + Color = 0; + for (int i = 0; i < kernel_size; ++i) + Color += tex2D(RenderTarget, screen_pos + float2(0, (float) (i - kernel_r) / screen_dy)) * Kernel[i]; + Color.a = 1; } technique GaussianBlurSeparable { - pass Pass_0 - { - VertexShader = compile vs_3_0 VSCopy(); - PixelShader = compile ps_3_0 BlurH(); - } - pass Pass_1 - { - VertexShader = compile vs_3_0 VSCopy(); - PixelShader = compile ps_3_0 BlurV(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 BlurH(); + } + pass Pass_1 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 BlurV(); + } } float4 PSDownFilter4(in float2 Tex : TEXCOORD0) : COLOR0 { - float4 Color = 0; - for (int i = 0; i < 4; i++) - for (int j = 0; j < 4; j++) - Color += tex2D(RenderTarget, Tex + float2((float)i / screen_dx,(float)j / screen_dy)); + float4 Color = 0; + for (int i = 0; i < 4; i++) + for (int j = 0; j < 4; j++) + Color += tex2D(RenderTarget, Tex + float2((float) i / screen_dx, (float) j / screen_dy)); - return Color / 16; + return Color / 16; } technique DownFilter4 { - pass Pass_0 - { - VertexShader = compile vs_3_0 VSCopy(); - PixelShader = compile ps_3_0 PSDownFilter4(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSDownFilter4(); + } } float4 PSGrayScale(in float2 Tex : TEXCOORD0, in float2 vpos : VPOS) : COLOR0 { - float4 ColorBase = tex2D(RenderTarget, Tex); - float4 ColorBrillante = tex2D(GlowMap, Tex + float2((float)16 / screen_dx,(float)16 / screen_dy)); + float4 ColorBase = tex2D(RenderTarget, Tex); + float4 ColorBrillante = tex2D(GlowMap, Tex + float2((float) 16 / screen_dx, (float) 16 / screen_dy)); // Y = 0.2126 R + 0.7152 G + 0.0722 B - float Yb = 0.2126*ColorBase.r + 0.7152*ColorBase.g + 0.0722*ColorBase.b; - float Yk = 0.2126*ColorBrillante.r + 0.7152*ColorBrillante.g + 0.0722*ColorBrillante.b; - if (round(vpos.y / 2) % 2 == 0) - { - Yb *= 0.85; - Yk *= 0.85; - } + float Yb = 0.2126 * ColorBase.r + 0.7152 * ColorBase.g + 0.0722 * ColorBase.b; + float Yk = 0.2126 * ColorBrillante.r + 0.7152 * ColorBrillante.g + 0.0722 * ColorBrillante.b; + if (round(vpos.y / 2) % 2 == 0) + { + Yb *= 0.85; + Yk *= 0.85; + } - return float4(Yk*0.75,Yb*0.6 + Yk * 4,Yk*0.75,1); + return float4(Yk * 0.75, Yb * 0.6 + Yk * 4, Yk * 0.75, 1); } technique GrayScale { - pass Pass_0 - { - VertexShader = compile vs_3_0 VSCopy(); - PixelShader = compile ps_3_0 PSGrayScale(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSGrayScale(); + } + +} + +static const float4 LUM_VECTOR = float4(.299, .587, .114, 0); +static const float MIDDLE_GRAY = 0.72f; +static const float LUM_WHITE = 1.5f; +float pupila_time = 0; +bool glow = true; +int tone_mapping_izq = 1; +int tone_mapping_der = 0; +bool pantalla_completa = true; + +float4 PSToneMapping(in float2 Tex : TEXCOORD0, in float2 vpos : VPOS) : COLOR0 +{ + int tone_mapping; + if (vpos.x < screen_dx / 2) + { + // Pantalla izquierda + tone_mapping = tone_mapping_izq; + } + else + { + // Pantalla derecha + if (pantalla_completa) + { + // Pantalla completa, + tone_mapping = tone_mapping_izq; + } + else + { + // Pantalla dividida + tone_mapping = tone_mapping_der; + Tex.x -= 0.5; + } + } + + float vLum = dot(tex2D(Luminance, float2(0, 0)), LUM_VECTOR); + float vLumAnt = dot(tex2D(Luminance_ant, float2(0, 0)), LUM_VECTOR); + float Yk = lerp(vLumAnt, vLum, pupila_time); + float4 ColorBase = tex2D(RenderTarget, Tex); + float4 ColorBrillante = glow && tone_mapping ? tex2D(GlowMap, Tex + float2((float) 16 / screen_dx, (float) 16 / screen_dy)) : 0; + + + // Tone mapping + if (tone_mapping == 1) + { + // Reinhard + ColorBase.rgb = ColorBase.rgb / (1 + ColorBase.rgb); + ColorBase.rgb *= MIDDLE_GRAY / (Yk + 0.001f); + } + else if (tone_mapping == 2) + { + // Modified Reinhard + Yk *= 1.5; + ColorBase.rgb = (ColorBase.rgb * (1 + ColorBase.rgb / Yk * Yk)) / (1 + ColorBase.rgb); + ColorBase.rgb *= MIDDLE_GRAY / (Yk + 0.001f); + } + else if (tone_mapping == 3) + { + // logaritmico + ColorBase.rgb = log(ColorBase.rgb + 1) / log(1.2 * Yk + 1); + } + else if (tone_mapping == 4) + { + // falta averiguar el nombre + ColorBase.rgb *= MIDDLE_GRAY / (Yk + 0.001f); + ColorBase.rgb *= (1.0f + ColorBase / LUM_WHITE); + ColorBase.rgb /= (1.0f + ColorBase); + } + + // combino con glow + float4 rta = float4(ColorBase.rgb + 2.6 * ColorBrillante.rgb, 1); + return rta; +} + + +technique ToneMapping +{ + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSToneMapping(); + } + +} + +// -------------------------------------------------------------------------------- +struct VS_OUTPUT2 +{ + float4 Position : POSITION; // vertex position + float4 Pos : TEXCOORD0; // distancia a la camara +}; + +VS_OUTPUT2 BlurFactorVS(float4 vPos : POSITION, float3 vNormal : NORMAL, + float4 vTexCoord0 : TEXCOORD0) +{ + VS_OUTPUT2 Output; + Output.Pos = Output.Position = mul(vPos, matWorldViewProj); + return Output; +} + +// Pixel shader que genera el blur map +float4 BlurFactorPS(float4 Pos : TEXCOORD0) : COLOR0 +{ + float4 color = float4(0, 0, 0, 1); + float z = Pos.w; + float k = clamp(blur_k * abs(z - zfoco) / (zf - zn), 0, 1); + color.rgb = k; + return color; +} + +// +technique RenderBlurFactor +{ + pass P0 + { + VertexShader = compile vs_3_0 BlurFactorVS(); + PixelShader = compile ps_3_0 BlurFactorPS(); + } +} + +// Gaussian blur +float4 PSBlur(float2 TextureUV : TEXCOORD0) : COLOR0 +{ + int blur_factor = tex2Dlod(BlurFactor, float4(TextureUV.xy, 0, 0)).r * 255; + int r = clamp(blur_factor, 0, 5); + float4 p = 0; + int cant_muestras = 0; + for (int i = -r; i <= r; ++i) + for (int j = -r; j <= r; ++j) + { + // Obtengo el blur factor de la muestra + float4 CT = float4((TextureUV + float2(i / screen_dx, j / screen_dy)).xy, 0, 0); + int blur_factor_muestra = tex2Dlod(BlurFactor, CT).r * 255; + int rm = clamp(blur_factor_muestra, 0, 5); + + // Para poder utilizar este punto como muestra valida, su radio de influencia + // tiene que ser mayor o igual a la distancia con respecto al centro + if (rm * rm >= i * i + j * j) + { + // tomo el color de la muestra: + p += tex2Dlod(RenderTarget, CT); + ++cant_muestras; + } + } + + p /= (float) cant_muestras; + + return float4(p.xyz, 1); +} + +technique DepthOfField +{ + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSBlur(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/WorkshopShaders/ImageProccesing.fx b/TGC.Examples/Shaders/WorkshopShaders/ImageProccesing.fx index cf54674d..bcf55d11 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/ImageProccesing.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/ImageProccesing.fx @@ -1,6 +1,6 @@ -float screen_dx; // tamaño de la pantalla en pixels +float screen_dx; // tamaño de la pantalla en pixels float screen_dy; -float screen_inc_x; // 1/screen_dx +float screen_inc_x; // 1/screen_dx float screen_inc_y; int cant = 0; float time = 0; @@ -10,83 +10,83 @@ texture base_Tex; sampler2D baseMap = sampler_state { - Texture = (base_Tex); - ADDRESSU = MIRROR; - ADDRESSV = MIRROR; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (base_Tex); + ADDRESSU = MIRROR; + ADDRESSV = MIRROR; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; -texture g_RenderTarget; // Render target -texture g_RenderTarget_ant; // Render target anterior +texture g_RenderTarget; // Render target +texture g_RenderTarget_ant; // Render target anterior sampler RenderTarget = sampler_state { - Texture = ; - MipFilter = NONE; - MinFilter = NONE; - MagFilter = NONE; + Texture = ; + MipFilter = NONE; + MinFilter = NONE; + MagFilter = NONE; }; sampler RenderTargetAnt = sampler_state { - Texture = ; - MipFilter = NONE; - MinFilter = NONE; - MagFilter = NONE; + Texture = ; + MipFilter = NONE; + MinFilter = NONE; + MagFilter = NONE; }; void vs_copy(float4 vPos : POSITION, float2 vTex : TEXCOORD0, out float4 oPos : POSITION, out float2 oScreenPos : TEXCOORD0) { - oPos = vPos; - oScreenPos = vTex; - oPos.w = 1; + oPos = vPos; + oScreenPos = vTex; + oPos.w = 1; } float4 PSGaussianBlur(float2 vPos : VPOS, float2 TextureUV : TEXCOORD0) : COLOR0 { - float3 color11 = tex2D(baseMap, TextureUV + float2(-2 * screen_inc_x,-2 * screen_inc_y)).rgb; - float3 color12 = tex2D(baseMap, TextureUV + float2(-2 * screen_inc_x,-screen_inc_y)).rgb; - float3 color13 = tex2D(baseMap, TextureUV + float2(-2 * screen_inc_x,0)).rgb; - float3 color14 = tex2D(baseMap, TextureUV + float2(-2 * screen_inc_x,screen_inc_y)).rgb; - float3 color15 = tex2D(baseMap, TextureUV + float2(-2 * screen_inc_x,2 * screen_inc_y)).rgb; - - float3 color21 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,-2 * screen_inc_y)).rgb; - float3 color22 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,-screen_inc_y)).rgb; - float3 color23 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,0)).rgb; - float3 color24 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,screen_inc_y)).rgb; - float3 color25 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,2 * screen_inc_y)).rgb; - - float3 color31 = tex2D(baseMap, TextureUV + float2(0,-2 * screen_inc_y)).rgb; - float3 color32 = tex2D(baseMap, TextureUV + float2(0,-screen_inc_y)).rgb; - float3 color33 = tex2D(baseMap, TextureUV + float2(0,0)).rgb; - float3 color34 = tex2D(baseMap, TextureUV + float2(0,screen_inc_y)).rgb; - float3 color35 = tex2D(baseMap, TextureUV + float2(0,2 * screen_inc_y)).rgb; - - float3 color41 = tex2D(baseMap, TextureUV + float2(screen_inc_x,-2 * screen_inc_y)).rgb; - float3 color42 = tex2D(baseMap, TextureUV + float2(screen_inc_x,-screen_inc_y)).rgb; - float3 color43 = tex2D(baseMap, TextureUV + float2(screen_inc_x,0)).rgb; - float3 color44 = tex2D(baseMap, TextureUV + float2(screen_inc_x,screen_inc_y)).rgb; - float3 color45 = tex2D(baseMap, TextureUV + float2(screen_inc_x,2 * screen_inc_y)).rgb; - - float3 color51 = tex2D(baseMap, TextureUV + float2(2 * screen_inc_x,-2 * screen_inc_y)).rgb; - float3 color52 = tex2D(baseMap, TextureUV + float2(2 * screen_inc_x,-screen_inc_y)).rgb; - float3 color53 = tex2D(baseMap, TextureUV + float2(2 * screen_inc_x,0)).rgb; - float3 color54 = tex2D(baseMap, TextureUV + float2(2 * screen_inc_x,screen_inc_y)).rgb; - float3 color55 = tex2D(baseMap, TextureUV + float2(2 * screen_inc_x,2 * screen_inc_y)).rgb; - - float3 T = 0; - T += 2 * color11 + 4 * color12 + 5 * color13 + 4 * color14 + 2 * color15; - T += 4 * color21 + 9 * color22 + 12 * color23 + 9 * color24 + 4 * color25; - T += 5 * color31 + 12 * color32 + 15 * color33 + 12 * color34 + 5 * color35; - T += 4 * color41 + 9 * color42 + 12 * color43 + 9 * color44 + 4 * color45; - T += 2 * color51 + 4 * color52 + 5 * color53 + 4 * color54 + 2 * color55; - T /= 159.0; - - return float4(T,1); + float3 color11 = tex2D(baseMap, TextureUV + float2(-2 * screen_inc_x, -2 * screen_inc_y)).rgb; + float3 color12 = tex2D(baseMap, TextureUV + float2(-2 * screen_inc_x, -screen_inc_y)).rgb; + float3 color13 = tex2D(baseMap, TextureUV + float2(-2 * screen_inc_x, 0)).rgb; + float3 color14 = tex2D(baseMap, TextureUV + float2(-2 * screen_inc_x, screen_inc_y)).rgb; + float3 color15 = tex2D(baseMap, TextureUV + float2(-2 * screen_inc_x, 2 * screen_inc_y)).rgb; + + float3 color21 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, -2 * screen_inc_y)).rgb; + float3 color22 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, -screen_inc_y)).rgb; + float3 color23 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, 0)).rgb; + float3 color24 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, screen_inc_y)).rgb; + float3 color25 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, 2 * screen_inc_y)).rgb; + + float3 color31 = tex2D(baseMap, TextureUV + float2(0, -2 * screen_inc_y)).rgb; + float3 color32 = tex2D(baseMap, TextureUV + float2(0, -screen_inc_y)).rgb; + float3 color33 = tex2D(baseMap, TextureUV + float2(0, 0)).rgb; + float3 color34 = tex2D(baseMap, TextureUV + float2(0, screen_inc_y)).rgb; + float3 color35 = tex2D(baseMap, TextureUV + float2(0, 2 * screen_inc_y)).rgb; + + float3 color41 = tex2D(baseMap, TextureUV + float2(screen_inc_x, -2 * screen_inc_y)).rgb; + float3 color42 = tex2D(baseMap, TextureUV + float2(screen_inc_x, -screen_inc_y)).rgb; + float3 color43 = tex2D(baseMap, TextureUV + float2(screen_inc_x, 0)).rgb; + float3 color44 = tex2D(baseMap, TextureUV + float2(screen_inc_x, screen_inc_y)).rgb; + float3 color45 = tex2D(baseMap, TextureUV + float2(screen_inc_x, 2 * screen_inc_y)).rgb; + + float3 color51 = tex2D(baseMap, TextureUV + float2(2 * screen_inc_x, -2 * screen_inc_y)).rgb; + float3 color52 = tex2D(baseMap, TextureUV + float2(2 * screen_inc_x, -screen_inc_y)).rgb; + float3 color53 = tex2D(baseMap, TextureUV + float2(2 * screen_inc_x, 0)).rgb; + float3 color54 = tex2D(baseMap, TextureUV + float2(2 * screen_inc_x, screen_inc_y)).rgb; + float3 color55 = tex2D(baseMap, TextureUV + float2(2 * screen_inc_x, 2 * screen_inc_y)).rgb; + + float3 T = 0; + T += 2 * color11 + 4 * color12 + 5 * color13 + 4 * color14 + 2 * color15; + T += 4 * color21 + 9 * color22 + 12 * color23 + 9 * color24 + 4 * color25; + T += 5 * color31 + 12 * color32 + 15 * color33 + 12 * color34 + 5 * color35; + T += 4 * color41 + 9 * color42 + 12 * color43 + 9 * color44 + 4 * color45; + T += 2 * color51 + 4 * color52 + 5 * color53 + 4 * color54 + 2 * color55; + T /= 159.0; + + return float4(T, 1); } float4 PSIntensidad(float2 vPos : VPOS, float2 TextureUV : TEXCOORD0) : COLOR0 @@ -94,100 +94,100 @@ float4 PSIntensidad(float2 vPos : VPOS, float2 TextureUV : TEXCOORD0) : COLOR0 // Red 0.212 // Green 0.701 // Blue 0.087 - float3 color = tex2D(baseMap, TextureUV).rgb; - float K = color.r*0.212 + color.g*0.701 + color.b*0.087; - return float4(K,K,K,1); + float3 color = tex2D(baseMap, TextureUV).rgb; + float K = color.r * 0.212 + color.g * 0.701 + color.b * 0.087; + return float4(K, K, K, 1); } float4 PSErotionFilter(float2 vPos : VPOS, float2 TextureUV : TEXCOORD0) : COLOR0 { - float color11 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,-screen_inc_y)).r; - float color12 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,0)).r; - float color13 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,screen_inc_y)).r; - - float color21 = tex2D(baseMap, TextureUV + float2(0,-screen_inc_y)).r; - float color22 = tex2D(baseMap, TextureUV + float2(0,0)).r; - float color23 = tex2D(baseMap, TextureUV + float2(0,screen_inc_y)).r; - - float color31 = tex2D(baseMap, TextureUV + float2(screen_inc_x,-screen_inc_y)).r; - float color32 = tex2D(baseMap, TextureUV + float2(screen_inc_x,0)).r; - float color33 = tex2D(baseMap, TextureUV + float2(screen_inc_x,screen_inc_y)).r; - - float min1 = min(color11,min(color12,color13)); - float min2 = min(color21,min(color22,color23)); - float min3 = min(color31,min(color32,color33)); - float K = min(min1,min(min2,min3)); - return float4(K,K,K,1); + float color11 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, -screen_inc_y)).r; + float color12 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, 0)).r; + float color13 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, screen_inc_y)).r; + + float color21 = tex2D(baseMap, TextureUV + float2(0, -screen_inc_y)).r; + float color22 = tex2D(baseMap, TextureUV + float2(0, 0)).r; + float color23 = tex2D(baseMap, TextureUV + float2(0, screen_inc_y)).r; + + float color31 = tex2D(baseMap, TextureUV + float2(screen_inc_x, -screen_inc_y)).r; + float color32 = tex2D(baseMap, TextureUV + float2(screen_inc_x, 0)).r; + float color33 = tex2D(baseMap, TextureUV + float2(screen_inc_x, screen_inc_y)).r; + + float min1 = min(color11, min(color12, color13)); + float min2 = min(color21, min(color22, color23)); + float min3 = min(color31, min(color32, color33)); + float K = min(min1, min(min2, min3)); + return float4(K, K, K, 1); } float4 PSSobelOperator(float2 vPos : VPOS, float2 TextureUV : TEXCOORD0) : COLOR0 { - float color11 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,-screen_inc_y)).r; - float color12 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,0)).r; - float color13 = tex2D(baseMap, TextureUV + float2(-screen_inc_x,screen_inc_y)).r; - - float color21 = tex2D(baseMap, TextureUV + float2(0,-screen_inc_y)).r; - float color22 = tex2D(baseMap, TextureUV + float2(0,0)).r; - float color23 = tex2D(baseMap, TextureUV + float2(0,screen_inc_y)).r; - - float color31 = tex2D(baseMap, TextureUV + float2(screen_inc_x,-screen_inc_y)).r; - float color32 = tex2D(baseMap, TextureUV + float2(screen_inc_x,0)).r; - float color33 = tex2D(baseMap, TextureUV + float2(screen_inc_x,screen_inc_y)).r; - - float Gx = -color11 + color13 - 2 * color22 + 2 * color23 - color31 + color33; - float Gy = -color11 - 2 * color21 - color13 + color31 + 2 * color32 + color33; - float gradiente = sqrt(Gx*Gx + Gy*Gy); - float angulo = atan2(Gy,Gx); - return float4(gradiente,gradiente,gradiente,1); + float color11 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, -screen_inc_y)).r; + float color12 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, 0)).r; + float color13 = tex2D(baseMap, TextureUV + float2(-screen_inc_x, screen_inc_y)).r; + + float color21 = tex2D(baseMap, TextureUV + float2(0, -screen_inc_y)).r; + float color22 = tex2D(baseMap, TextureUV + float2(0, 0)).r; + float color23 = tex2D(baseMap, TextureUV + float2(0, screen_inc_y)).r; + + float color31 = tex2D(baseMap, TextureUV + float2(screen_inc_x, -screen_inc_y)).r; + float color32 = tex2D(baseMap, TextureUV + float2(screen_inc_x, 0)).r; + float color33 = tex2D(baseMap, TextureUV + float2(screen_inc_x, screen_inc_y)).r; + + float Gx = -color11 + color13 - 2 * color22 + 2 * color23 - color31 + color33; + float Gy = -color11 - 2 * color21 - color13 + color31 + 2 * color32 + color33; + float gradiente = sqrt(Gx * Gx + Gy * Gy); + float angulo = atan2(Gy, Gx); + return float4(gradiente, gradiente, gradiente, 1); } technique ImageFilter { - pass p0 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 PSIntensidad(); - } - pass p1 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 PSErotionFilter(); - } - - pass p2 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 PSSobelOperator(); - } - - pass p3 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 PSGaussianBlur(); - } + pass p0 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 PSIntensidad(); + } + pass p1 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 PSErotionFilter(); + } + + pass p2 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 PSSobelOperator(); + } + + pass p3 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 PSGaussianBlur(); + } } float4 PSMotionDetect(float2 vPos : VPOS, float2 TextureUV : TEXCOORD0) : COLOR0 { - return tex2D(RenderTarget,TextureUV); - -/* -float t = distance(tex2D(RenderTarget, TextureUV) , tex2D(RenderTargetAnt,TextureUV)); -if(t>0.5) - t = 1; -else - t = 0; -//return float4(t,t,t,1); - -return tex2D(baseMap, TextureUV) + float4(0,t,t,1); -*/ + return tex2D(RenderTarget, TextureUV); + + /* + float t = distance(tex2D(RenderTarget, TextureUV) , tex2D(RenderTargetAnt,TextureUV)); + if(t>0.5) + t = 1; + else + t = 0; + //return float4(t,t,t,1); + + return tex2D(baseMap, TextureUV) + float4(0,t,t,1); + */ } technique motionDetect { - pass p0 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 PSMotionDetect(); - } + pass p0 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 PSMotionDetect(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/WorkshopShaders/MotionBlur.fx b/TGC.Examples/Shaders/WorkshopShaders/MotionBlur.fx index 0f73ea5f..fc96e953 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/MotionBlur.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/MotionBlur.fx @@ -11,196 +11,227 @@ float4x4 matWorld; //Matriz de transformacion World float4x4 matWorldView; //Matriz World * View float4x4 matWorldViewProj; //Matriz World * View * Projection float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) -float4x4 matWorldViewProjAnt; //Matriz World * View * Proj anterior +float4x4 matWorldViewProjAnt; //Matriz World * View * Proj anterior +float4x4 matView; //Matriz View actual +float4x4 matProj; //Matriz Projection actual +float4x4 matViewAnt; //Matriz View anterior //Textura para DiffuseMap texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = MIRROR; - ADDRESSV = MIRROR; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = MIRROR; + ADDRESSV = MIRROR; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; -float screen_dx; // tamaño de la pantalla en pixels +float screen_dx; // tamaño de la pantalla en pixels float screen_dy; //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; texture g_RenderTarget; sampler RenderTarget = sampler_state { - Texture = ; - ADDRESSU = CLAMP; - ADDRESSV = CLAMP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; texture texVelocityMap; sampler2D velocityMap = sampler_state { - Texture = (texVelocityMap); - MinFilter = POINT; - MagFilter = POINT; - AddressU = Clamp; - AddressV = Clamp; + Texture = (texVelocityMap); + MinFilter = POINT; + MagFilter = POINT; + AddressU = Clamp; + AddressV = Clamp; }; texture texVelocityMapAnt; sampler2D velocityMapAnt = sampler_state { - Texture = (texVelocityMapAnt); - MinFilter = POINT; - MagFilter = POINT; - AddressU = Clamp; - AddressV = Clamp; + Texture = (texVelocityMapAnt); + MinFilter = POINT; + MagFilter = POINT; + AddressU = Clamp; + AddressV = Clamp; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 Norm : TEXCOORD1; // Normales - float3 Pos : TEXCOORD2; // Posicion real 3d - float2 Vel : TEXCOORD3; // velocidad por pixel + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float4 vPosActual : TEXCOORD2; // Posicion actual + float4 vPosAnterior : TEXCOORD3; // Posicion anterior + //float2 Vel : TEXCOORD3; // velocidad por pixel + }; //Vertex Shader VS_OUTPUT vs_main(VS_INPUT Input) { - VS_OUTPUT Output; + VS_OUTPUT Output; //Proyectar posicion - Output.Position = mul(Input.Position, matWorldViewProj); - + Output.Position = mul(Input.Position, matWorldViewProj); + //Las Texcoord quedan igual - Output.Texcoord = Input.Texcoord; - - // Calculo la posicion real - float4 pos_real = mul(Input.Position, matWorld); - Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); + Output.Texcoord = Input.Texcoord; // Transformo la normal y la normalizo - Output.Norm = normalize(mul(Input.Normal, matWorld)); + Output.Norm = normalize(mul(Input.Normal, matWorld)); + /* // Computo la velocidad del vertice // posicion actual float4 vPosActual = Output.Position; // posicion anterior - float4 vPosAnterior = mul(Input.Position, matWorldViewProjAnt); + float4 vPosAnterior = mul( Input.Position,matWorld * matViewAnt * matProj); vPosActual /= vPosActual.w; vPosAnterior /= vPosAnterior.w; - float2 velocity = vPosActual - vPosAnterior; - // lo propago - Output.Vel = velocity; + float2 velocity = vPosActual - vPosAnterior; + // lo propago + Output.Vel = velocity;*/ - return(Output); + // posicion actual + Output.vPosActual = Output.Position; + // posicion anterior + Output.vPosAnterior = mul(Input.Position, matWorld * matViewAnt * matProj); + + return (Output); + } //Pixel Shader -float4 ps_main(float3 Texcoord: TEXCOORD0) : COLOR0 +float4 ps_main(float3 Texcoord : TEXCOORD0) : COLOR0 { - float4 fvBaseColor = tex2D(diffuseMap, Texcoord); - if (fvBaseColor.a < 0.1) - discard; - return fvBaseColor; + float4 fvBaseColor = tex2D(diffuseMap, Texcoord); + if (fvBaseColor.a < 0.1) + discard; + return fvBaseColor; } //Pixel Shader Velocity -float4 ps_velocity(float3 Texcoord: TEXCOORD0, float2 Vel : TEXCOORD3) : COLOR0 +float4 ps_velocity(float3 Texcoord : TEXCOORD0, float4 vPosActual : TEXCOORD2, float4 vPosAnterior : TEXCOORD3) : COLOR0 { //Obtener el texel de textura - float4 fvBaseColor = tex2D(diffuseMap, Texcoord); - if (fvBaseColor.a < 0.1) - discard; - return float4(Vel.x,Vel.y,0.0f,1.0f); + float4 fvBaseColor = tex2D(diffuseMap, Texcoord); + if (fvBaseColor.a < 0.1) + discard; + + + vPosActual /= vPosActual.w; + vPosAnterior /= vPosAnterior.w; + float2 Vel = vPosActual - vPosAnterior; + + return float4(Vel.x, Vel.y, 0.0f, 1.0f); } technique DefaultTechnique { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_main(); - PixelShader = compile ps_3_0 ps_main(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_main(); + } } technique VelocityMap { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_main(); - PixelShader = compile ps_3_0 ps_velocity(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_velocity(); + } + } void vs_copy(float4 vPos : POSITION, float2 vTex : TEXCOORD0, out float4 oPos : POSITION, out float2 oScreenPos : TEXCOORD0) { - oPos = vPos; - oScreenPos = vTex; - oPos.w = 1; + oPos = vPos; + oScreenPos = vTex; + oPos.w = 1; } -float PixelBlurConst = 400; +float PixelBlurConst = 0.05f; static const float NumberOfPostProcessSamples = 12.0f; float4 ps_motion_blur(in float2 Tex : TEXCOORD0) : COLOR0 { - float4 curFramePixelVelocity = tex2D(velocityMap, Tex); - float4 lastFramePixelVelocity = tex2D(velocityMapAnt, Tex); - - float2 pixelVelocity; - float curVelocitySqMag = curFramePixelVelocity.r * curFramePixelVelocity.r + - curFramePixelVelocity.g * curFramePixelVelocity.g; - float lastVelocitySqMag = lastFramePixelVelocity.r * lastFramePixelVelocity.r + - lastFramePixelVelocity.g * lastFramePixelVelocity.g; - - if (lastVelocitySqMag > curVelocitySqMag) - { - pixelVelocity.x = lastFramePixelVelocity.r * PixelBlurConst; - pixelVelocity.y = -lastFramePixelVelocity.g * PixelBlurConst; - } - else - { - pixelVelocity.x = curFramePixelVelocity.r * PixelBlurConst; - pixelVelocity.y = -curFramePixelVelocity.g * PixelBlurConst; - } - - //= curFramePixelVelocity.rg* PixelBlurConst; - //pixelVelocity.y *= -1; - - float3 Blurred = 0; - for (float i = 0; i < NumberOfPostProcessSamples; i++) - { - float2 lookup = pixelVelocity * i / NumberOfPostProcessSamples + Tex; - float4 Current = tex2D(RenderTarget, lookup); - Blurred += Current.rgb; - } - return float4(Blurred / NumberOfPostProcessSamples, 1.0f); - + float4 curFramePixelVelocity = tex2D(velocityMap, Tex); + float4 lastFramePixelVelocity = tex2D(velocityMapAnt, Tex); + + float2 pixelVelocity; + float curVelocitySqMag = curFramePixelVelocity.r * curFramePixelVelocity.r + + curFramePixelVelocity.g * curFramePixelVelocity.g; + float lastVelocitySqMag = lastFramePixelVelocity.r * lastFramePixelVelocity.r + + lastFramePixelVelocity.g * lastFramePixelVelocity.g; + + if (lastVelocitySqMag > curVelocitySqMag) + { + pixelVelocity.x = lastFramePixelVelocity.r * PixelBlurConst; + pixelVelocity.y = -lastFramePixelVelocity.g * PixelBlurConst; + } + else + { + pixelVelocity.x = curFramePixelVelocity.r * PixelBlurConst; + pixelVelocity.y = -curFramePixelVelocity.g * PixelBlurConst; + } + + + float3 Blurred = 0; + for (float i = 0; i < NumberOfPostProcessSamples; i++) + { + float2 lookup = pixelVelocity * i / NumberOfPostProcessSamples + Tex; + float4 Current = tex2D(RenderTarget, lookup); + Blurred += Current.rgb; + } + + return float4(Blurred / NumberOfPostProcessSamples, 1.0f); // return tex2D(velocityMap,Tex) ; // return tex2D(RenderTarget,Tex) ; } technique PostProcessMotionBlur { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 ps_motion_blur(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 ps_motion_blur(); + } +} + +float4 ps_draw_grid(in float2 Tex : TEXCOORD0, float2 vPos : VPOS) : COLOR0 +{ + int x = round(vPos.x / 4); + int y = round(vPos.y / 4); + if (x % 5 != 0 || y % 5 != 0) + discard; + return float4(1, 1, 1, 1); +} + +technique DrawGrid +{ + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 ps_draw_grid(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/WorkshopShaders/OutRun.fx b/TGC.Examples/Shaders/WorkshopShaders/OutRun.fx index af633337..888285c5 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/OutRun.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/OutRun.fx @@ -16,154 +16,155 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = MIRROR; - ADDRESSV = MIRROR; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = MIRROR; + ADDRESSV = MIRROR; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; -float screen_dx; // tamaño de la pantalla en pixels +float screen_dx; // tamaño de la pantalla en pixels float screen_dy; //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; texture g_RenderTarget; sampler RenderTarget = sampler_state { - Texture = ; - ADDRESSU = CLAMP; - ADDRESSV = CLAMP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; texture g_RenderTarget2; sampler RenderTarget2 = sampler_state { - Texture = ; - ADDRESSU = CLAMP; - ADDRESSV = CLAMP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; texture g_RenderTarget3; sampler RenderTarget3 = sampler_state { - Texture = ; - ADDRESSU = CLAMP; - ADDRESSV = CLAMP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; texture g_RenderTarget4; sampler RenderTarget4 = sampler_state { - Texture = ; - ADDRESSU = CLAMP; - ADDRESSV = CLAMP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; texture g_RenderTarget5; sampler RenderTarget5 = sampler_state { - Texture = ; - ADDRESSU = CLAMP; - ADDRESSV = CLAMP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 Norm : TEXCOORD1; // Normales - float3 Pos : TEXCOORD2; // Posicion real 3d + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float3 Pos : TEXCOORD2; // Posicion real 3d }; //Vertex Shader VS_OUTPUT vs_main(VS_INPUT Input) { - VS_OUTPUT Output; + VS_OUTPUT Output; //Proyectar posicion - Output.Position = mul(Input.Position, matWorldViewProj); - + Output.Position = mul(Input.Position, matWorldViewProj); + //Las Texcoord quedan igual - Output.Texcoord = Input.Texcoord; + Output.Texcoord = Input.Texcoord; // Calculo la posicion real - float4 pos_real = mul(Input.Position, matWorld); - Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); - + float4 pos_real = mul(Input.Position, matWorld); + Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); + // Transformo la normal y la normalizo //Output.Norm = normalize(mul(Input.Normal,matInverseTransposeWorld)); - Output.Norm = normalize(mul(Input.Normal, matWorld)); - return(Output); + Output.Norm = normalize(mul(Input.Normal, matWorld)); + return (Output); + } //Pixel Shader -float4 ps_main(float3 Texcoord: TEXCOORD0, float3 N : TEXCOORD1, +float4 ps_main(float3 Texcoord : TEXCOORD0, float3 N : TEXCOORD1, float3 Pos : TEXCOORD2) : COLOR0 { //Obtener el texel de textura - float4 fvBaseColor = tex2D(diffuseMap, Texcoord); - if (fvBaseColor.a < 0.1) - discard; - return fvBaseColor; + float4 fvBaseColor = tex2D(diffuseMap, Texcoord); + if (fvBaseColor.a < 0.1) + discard; + return fvBaseColor; } technique DefaultTechnique { - pass Pass_0 - { - VertexShader = compile vs_3_0 vs_main(); - PixelShader = compile ps_3_0 ps_main(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_main(); + } } void VSCopy(float4 vPos : POSITION, float2 vTex : TEXCOORD0, out float4 oPos : POSITION, out float2 oScreenPos : TEXCOORD0) { - oPos = vPos; - oScreenPos = vTex; - oPos.w = 1; + oPos = vPos; + oScreenPos = vTex; + oPos.w = 1; } float4 PSFrameCombine(in float2 Tex : TEXCOORD0, in float2 vpos : VPOS) : COLOR0 { - return (tex2D(RenderTarget,Tex) + tex2D(RenderTarget2,Tex) + tex2D(RenderTarget3,Tex) - + +tex2D(RenderTarget4,Tex) + +tex2D(RenderTarget5,Tex)) *0.2; + return (tex2D(RenderTarget, Tex) + tex2D(RenderTarget2, Tex) + tex2D(RenderTarget3, Tex) + + +tex2D(RenderTarget4, Tex) + +tex2D(RenderTarget5, Tex)) * 0.2; } technique FrameMotionBlur { - pass Pass_0 - { - VertexShader = compile vs_3_0 VSCopy(); - PixelShader = compile ps_3_0 PSFrameCombine(); - } -} \ No newline at end of file + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSFrameCombine(); + } +} diff --git a/TGC.Examples/Shaders/WorkshopShaders/Parallax.fx b/TGC.Examples/Shaders/WorkshopShaders/Parallax.fx index 207c6d86..2c562fd4 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/Parallax.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/Parallax.fx @@ -3,10 +3,11 @@ float time = 0; float3 g_LightDir = float3(0, -1, 0); float3 fvEyePosition = float3(0.00, 0.00, -100.00); float g_fSpecularExponent = 3; -float k_ld = 0.5; // luz difusa -float k_le = 0.6; // luz specular -float k_la = 0.4; // luz ambiente +float k_ld = 0.5; // luz difusa +float k_le = 0.6; // luz specular +float k_la = 0.4; // luz ambiente bool phong_lighting = true; +float k_alpha = 1; // float min_cant_samples = 10; float max_cant_samples = 50; @@ -24,12 +25,12 @@ float fTexScale = 10; texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; // Textura basica: @@ -37,20 +38,20 @@ texture base_Tex; sampler2D baseMap = sampler_state { - Texture = (base_Tex); - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (base_Tex); + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; texture aux_Tex; sampler2D auxMap = sampler_state { - Texture = ; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; // Heighmap @@ -58,183 +59,381 @@ texture height_map; sampler2D heightMap = sampler_state { - Texture = ; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = ; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; // calcula la iluminaciond dinamica float4 Phong(float2 texCoord, float3 vLightTS, float3 vViewTS, float dx, float dy) { // Color Basico - float4 cBaseColor = tex2Dgrad(auxMap, texCoord, dx, dy); - if (phong_lighting) - { + float4 cBaseColor = tex2Dgrad(auxMap, texCoord, dx, dy); + if (phong_lighting) + { // Busco el vector normal en la textura Normal-Height Map (esta en Tangent Space) - float3 vNormalTS = normalize(tex2Dgrad(heightMap, texCoord, dx, dy) * 2 - 1); - + float3 vNormalTS = normalize(tex2Dgrad(heightMap, texCoord, dx, dy) * 2 - 1); + + // tomo el abs() del dot product, porque la normal a veces viene al reves // Color difuso - float3 vLightTSAdj = float3(vLightTS.x, -vLightTS.y, vLightTS.z); - float cDiffuse = saturate(dot(vNormalTS, vLightTSAdj)) * k_ld; - + float3 vLightTSAdj = float3(vLightTS.x, -vLightTS.y, vLightTS.z); + float cDiffuse = saturate(abs(dot(vNormalTS, vLightTSAdj))) * k_ld; + // Color specular - float4 cSpecular = 0; - float3 vReflectionTS = normalize(2 * dot(vViewTS, vNormalTS) * vNormalTS - vViewTS); - float fRdotL = saturate(dot(vReflectionTS, vLightTSAdj)); - cSpecular = saturate(pow(fRdotL, g_fSpecularExponent))*k_le; + float4 cSpecular = 0; + float3 vReflectionTS = normalize(2 * dot(vViewTS, vNormalTS) * vNormalTS - vViewTS); + float fRdotL = saturate(abs(dot(vReflectionTS, vLightTSAdj))); + cSpecular = saturate(pow(fRdotL, g_fSpecularExponent)) * k_le; // Retorno color difuso + luz especular - cBaseColor = (k_la + cDiffuse)*cBaseColor + cSpecular; - } - return cBaseColor; + cBaseColor = (k_la + cDiffuse) * cBaseColor + cSpecular; + } + return cBaseColor; +} + + +// vertex shader con la normal fija +void RenderSceneVSNormalFija(float4 Pos : POSITION, + float2 Texcoord : TEXCOORD0, + float3 normal : NORMAL, + out float4 oPos : POSITION, + out float2 Tex : TEXCOORD0, + out float3 tsView : TEXCOORD1, + out float3 tsLight : TEXCOORD3, + out float3 wsNormal : TEXCOORD2, + out float3 wsView : TEXCOORD4 + ) +{ + // Vector View = desde el ojo a la pos del vertice + float4 VertexPositionWS = mul(Pos, matWorld); + wsView = fvEyePosition.xyz - VertexPositionWS.xyz; + + // la normal esta fija + normal = float3(0, -1, 0); + float3 tangent = float3(-1, 0, 0); + float3 binormal = float3(0, 0, -1); + + float3x3 tangentToWorldSpace; + tangentToWorldSpace[0] = mul(tangent, matWorld); + tangentToWorldSpace[1] = mul(binormal, matWorld); + tangentToWorldSpace[2] = mul(normal, matWorld); + + // tangentToWorldSpace es una matriz ortogonal, su inversa = a su transpuesta + // A es OrtoNorm <=> A-1 == At + float3x3 worldToTangentSpace = transpose(tangentToWorldSpace); + + // proyecto + oPos = mul(Pos, matWorldViewProj); + //Propago la textura + Tex = Texcoord * fTexScale; + + tsView = mul(wsView, worldToTangentSpace); // Vector View en TangentSpace + tsLight = mul(g_LightDir, worldToTangentSpace); // Vector Light en TangentSpace + + // propago el vector normal en Worldspace + wsNormal = normal; + } + +// VS standard, la normal viene en el vertice, y computo la binormal y la tangente void RenderSceneVS(float4 Pos : POSITION, - float2 Texcoord : TEXCOORD0, - float3 normal : NORMAL, - out float4 oPos : POSITION, - out float2 Tex : TEXCOORD0, - out float3 tsView : TEXCOORD1, - out float3 tsLight : TEXCOORD3, - out float3 wsNormal : TEXCOORD2, - out float3 wsView : TEXCOORD4 -) + float2 Texcoord : TEXCOORD0, + float3 normal : NORMAL, + out float4 oPos : POSITION, + out float2 Tex : TEXCOORD0, + out float3 tsView : TEXCOORD1, + out float3 tsLight : TEXCOORD3, + out float3 wsNormal : TEXCOORD2, + out float3 wsView : TEXCOORD4 + ) { + // Vector View = desde el ojo a la pos del vertice - float4 VertexPositionWS = mul(Pos, matWorld); - wsView = fvEyePosition.xyz - VertexPositionWS.xyz; + float4 VertexPositionWS = mul(Pos, matWorld); + wsView = fvEyePosition.xyz - VertexPositionWS.xyz; + // calculo la tg y la binormal ? - float3 up = float3(0, 0, 1); - if (abs(normal.z - 1) <= 0.0001) - up = float3(0, 1, 0); - float3 tangent = cross(normal, up); - float3 binormal = cross(normal, tangent); - - /* - // o la dejo fija? - normal = float3(0,1,0); - float3 tangent = float3(1,0,0); - float3 binormal = float3(0,0,1); - */ - - float3x3 tangentToWorldSpace; - tangentToWorldSpace[0] = mul(tangent, matWorld); - tangentToWorldSpace[1] = mul(binormal, matWorld); - tangentToWorldSpace[2] = mul(normal, matWorld); + float3 up = float3(0, 0, 1); + if (abs(normal.z - 1) <= 0.0001) + up = float3(0, 1, 0); + float3 tangent = cross(normal, up); + float3 binormal = cross(tangent, normal); + + float3x3 tangentToWorldSpace; + tangentToWorldSpace[0] = mul(tangent, matWorld); + tangentToWorldSpace[1] = mul(binormal, matWorld); + tangentToWorldSpace[2] = mul(normal, matWorld); // tangentToWorldSpace es una matriz ortogonal, su inversa = a su transpuesta // A es OrtoNorm <=> A-1 == At - float3x3 worldToTangentSpace = transpose(tangentToWorldSpace); + float3x3 worldToTangentSpace = transpose(tangentToWorldSpace); + + // proyecto + oPos = mul(Pos, matWorldViewProj); + //Propago la textura + Tex = Texcoord * fTexScale; + + tsView = mul(wsView, worldToTangentSpace); // Vector View en TangentSpace + tsLight = mul(g_LightDir, worldToTangentSpace); // Vector Light en TangentSpace + + // propago el vector normal en Worldspace + wsNormal = normal; + +} + + + +float3 g_normal = float3(0, 1, 0); +float3 g_tangent = float3(1, 0, 0); +float3 g_binormal = float3(0, 0, 1); + +// Vertex shader con parche para las normales +void RenderSceneVS2(float4 Pos : POSITION, + float2 Texcoord : TEXCOORD0, + out float4 oPos : POSITION, + out float2 Tex : TEXCOORD0, + out float3 tsView : TEXCOORD1, + out float3 tsLight : TEXCOORD3, + out float3 wsNormal : TEXCOORD2, + out float3 wsView : TEXCOORD4 + ) +{ + + // Vector View = desde el ojo a la pos del vertice + float4 VertexPositionWS = mul(Pos, matWorld); + wsView = fvEyePosition.xyz - VertexPositionWS.xyz; + + + float3 normal = g_normal; + float3 tangent = g_tangent; + float3 binormal = g_binormal; + + float3x3 tangentToWorldSpace; + tangentToWorldSpace[0] = mul(tangent, matWorld); + tangentToWorldSpace[1] = mul(binormal, matWorld); + tangentToWorldSpace[2] = mul(normal, matWorld); + + // tangentToWorldSpace es una matriz ortogonal, su inversa = a su transpuesta + // A es OrtoNorm <=> A-1 == At + float3x3 worldToTangentSpace = transpose(tangentToWorldSpace); // proyecto - oPos = mul(Pos, matWorldViewProj); + oPos = mul(Pos, matWorldViewProj); //Propago la textura - Tex = Texcoord*fTexScale; - - tsView = mul(wsView, worldToTangentSpace); // Vector View en TangentSpace - tsLight = mul(g_LightDir, worldToTangentSpace); // Vector Light en TangentSpace + Tex = Texcoord * fTexScale; - // propago el vector normal en Worldspace - wsNormal = normal; - // tambien devuelve el vector view en worldspace wsView + tsView = mul(wsView, worldToTangentSpace); // Vector View en TangentSpace + tsLight = mul(g_LightDir, worldToTangentSpace); // Vector Light en TangentSpace + + // propago el vector normal en Worldspace + wsNormal = normal; + } + // ws = worldspace ts = tangentspace -float4 PSParallaxOcclusion(float2 Texcoord: TEXCOORD0, - float3 Pos : POSITION, - float3 tsView : TEXCOORD1, - float3 wsNormal : TEXCOORD2, - float3 tsLight : TEXCOORD3, - float3 wsView : TEXCOORD4 -) : COLOR0 +float4 PSParallaxOcclusion(float2 Texcoord : TEXCOORD0, + float3 Pos : POSITION, + float3 tsView : TEXCOORD1, + float3 wsNormal : TEXCOORD2, + float3 tsLight : TEXCOORD3, + float3 wsView : TEXCOORD4 + ) : COLOR0 { + + //return float4(wsNormal.xyz,1); + // normalizo todo lo que interpola el PS - wsView = normalize(wsView); - tsView = normalize(tsView); - tsLight = normalize(tsLight); - wsNormal = normalize(wsNormal); + wsView = normalize(wsView); + tsView = normalize(tsView); + tsLight = normalize(tsLight); + wsNormal = normalize(wsNormal); // POM Algoritmo Standard - float fParallaxLimit = length(tsView.xy) / tsView.z; - fParallaxLimit *= fHeightMapScale; - float2 vOffset = normalize(-tsView.xy); - vOffset = vOffset * fParallaxLimit; + float fParallaxLimit = length(tsView.xy) / tsView.z; + fParallaxLimit *= fHeightMapScale; + float2 vOffset = normalize(-tsView.xy); + vOffset = vOffset * fParallaxLimit; // interpola entre un min y un max, proporcionalmente al angulo de vision - int nNumSamples = (int)lerp(min_cant_samples ,max_cant_samples, - abs(dot(wsView,wsNormal))); - float fStepSize = 1.0 / (float)nNumSamples; + int nNumSamples = (int) lerp(min_cant_samples, max_cant_samples, + abs(dot(wsView, wsNormal))); + float fStepSize = 1.0 / (float) nNumSamples; - float2 dx, dy; - dx = ddx(Texcoord); - dy = ddy(Texcoord); + float2 dx, dy; + dx = ddx(Texcoord); + dy = ddy(Texcoord); // Ray casting: - float2 vOffsetStep = fStepSize * vOffset; - float2 vCurrOffset = float2(0, 0); - float2 vLastOffset = float2(0, 0); - - float fCurrH = 0; - float fLastH = 0; - - float stepHeight = 1.0; - int nCurrSample = 0; - float4 vCurrSample; - float4 vLastSample; - - while (nCurrSample < nNumSamples) - { - vCurrSample = tex2Dgrad(heightMap, Texcoord + vCurrOffset, dx, dy); - fCurrH = vCurrSample.a; - if (fCurrH > stepHeight) - { - float Ua = 0; - float X = (fStepSize + (fCurrH - fLastH)); - if (X != 0.0f) - Ua = ((stepHeight + fStepSize) - fLastH) / X; - vCurrOffset = vLastOffset + Ua* vOffsetStep; - nCurrSample = nNumSamples + 1; - } - else - { - nCurrSample++; - stepHeight -= fStepSize; - vLastOffset = vCurrOffset; - vCurrOffset += vOffsetStep; - vLastSample = vCurrSample; - fLastH = fCurrH; - } - } - - return Phong(Texcoord + vCurrOffset, tsLight, -tsView,dx,dy); + float2 vOffsetStep = fStepSize * vOffset; + float2 vCurrOffset = float2(0, 0); + float2 vLastOffset = float2(0, 0); + + float fCurrH = 0; + float fLastH = 0; + + float stepHeight = 1.0; + int nCurrSample = 0; + float4 vCurrSample; + float4 vLastSample; + + while (nCurrSample < nNumSamples) + { + vCurrSample = tex2Dgrad(heightMap, Texcoord + vCurrOffset, dx, dy); + fCurrH = vCurrSample.a; + if (fCurrH > stepHeight) + { + float Ua = 0; + float X = (fStepSize + (fCurrH - fLastH)); + if (X != 0.0f) + Ua = ((stepHeight + fStepSize) - fLastH) / X; + vCurrOffset = vLastOffset + Ua * vOffsetStep; + nCurrSample = nNumSamples + 1; + } + else + { + nCurrSample++; + stepHeight -= fStepSize; + vLastOffset = vCurrOffset; + vCurrOffset += vOffsetStep; + vLastSample = vCurrSample; + fLastH = fCurrH; + } + } + + return Phong(Texcoord + vCurrOffset, tsLight, -tsView, dx, dy); } // Parallax oclussion technique ParallaxOcclusion { - pass p0 - { - VertexShader = compile vs_3_0 RenderSceneVS(); - PixelShader = compile ps_3_0 PSParallaxOcclusion(); - } + pass p0 + { + VertexShader = compile vs_3_0 RenderSceneVS(); + PixelShader = compile ps_3_0 PSParallaxOcclusion(); + } } -float4 PSBumpMap(float2 Texcoord: TEXCOORD0, - float3 Pos : POSITION, - float3 tsView : TEXCOORD1, - float3 wsNormal : TEXCOORD2, - float3 tsLight : TEXCOORD3 -) : COLOR0 +technique ParallaxOcclusion2 { - return Phong(Texcoord, tsLight, -tsView,ddx(Texcoord),ddy(Texcoord)); + pass p0 + { + VertexShader = compile vs_3_0 RenderSceneVS2(); + PixelShader = compile ps_3_0 PSParallaxOcclusion(); + } } +technique ParallaxOcclusionPiso +{ + pass p0 + { + VertexShader = compile vs_3_0 RenderSceneVSNormalFija(); + PixelShader = compile ps_3_0 PSParallaxOcclusion(); + } +} + +float4 PSBumpMap(float2 Texcoord : TEXCOORD0, + float3 Pos : POSITION, + float3 tsView : TEXCOORD1, + float3 wsNormal : TEXCOORD2, + float3 tsLight : TEXCOORD3 + ) : COLOR0 +{ + return Phong(Texcoord, tsLight, -tsView, ddx(Texcoord), ddy(Texcoord)); +} + + technique BumpMap { - pass p0 - { - VertexShader = compile vs_3_0 RenderSceneVS(); - PixelShader = compile ps_3_0 PSBumpMap(); - } -} \ No newline at end of file + pass p0 + { + VertexShader = compile vs_3_0 RenderSceneVS(); + PixelShader = compile ps_3_0 PSBumpMap(); + } +} + + +technique BumpMap2 +{ + pass p0 + { + VertexShader = compile vs_3_0 RenderSceneVS2(); + PixelShader = compile ps_3_0 PSBumpMap(); + } +} + + +float4 PSDraft(float2 Texcoord : TEXCOORD0) : COLOR0 +{ + return float4(tex2D(diffuseMap, Texcoord * 0.0001).rgb, k_alpha); +} + + +technique Draft +{ + pass p0 + { + VertexShader = compile vs_3_0 RenderSceneVS(); + PixelShader = compile ps_3_0 PSDraft(); + } +} + + +//Vertex Shader +//Input del Vertex Shader +struct VS_INPUT +{ + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; +}; +//Output del Vertex Shader +struct VS_OUTPUT +{ + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float3 Pos : TEXCOORD2; // Posicion real 3d +}; + +VS_OUTPUT vs_main(VS_INPUT Input) +{ + VS_OUTPUT Output; + + //Proyectar posicion + Output.Position = mul(Input.Position, matWorldViewProj); + + //Las Texcoord quedan igual + Output.Texcoord = Input.Texcoord; + + // Calculo la posicion real + float4 pos_real = mul(Input.Position, matWorld); + Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); + + // Transformo la normal y la normalizo + //Output.Norm = normalize(mul(Input.Normal,matInverseTransposeWorld)); + Output.Norm = normalize(mul(Input.Normal, matWorld)); + return (Output); + +} + +//Pixel Shader +float4 ps_main(float3 Texcoord : TEXCOORD0, float3 N : TEXCOORD1, float3 Pos : TEXCOORD2) : COLOR0 +{ + //Obtener el texel de textura + float4 fvBaseColor = tex2D(diffuseMap, Texcoord); + return fvBaseColor; +} + +technique DefaultTechnique +{ + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_main(); + } +} + diff --git a/TGC.Examples/Shaders/WorkshopShaders/PhongShading.fx b/TGC.Examples/Shaders/WorkshopShaders/PhongShading.fx index 635aada0..d16c1b26 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/PhongShading.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/PhongShading.fx @@ -16,20 +16,20 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; float3 fvLightPosition = float3(-100.00, 100.00, -100.00); float3 fvEyePosition = float3(0.00, 0.00, -100.00); -float k_la = 0.3; // luz ambiente global -float k_ld = 0.9; // luz difusa -float k_ls = 0.4; // luz specular -float fSpecularPower = 16.84; // exponente de la luz specular +float k_la = 0.3; // luz ambiente global +float k_ld = 0.9; // luz difusa +float k_ls = 0.4; // luz specular +float fSpecularPower = 16.84; // exponente de la luz specular /**************************************************************************************/ /* DefaultTechnique */ @@ -38,43 +38,45 @@ float fSpecularPower = 16.84; // exponente de la luz specular //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 Norm : TEXCOORD1; // Normales - float3 Pos : TEXCOORD2; // Posicion real 3d + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float3 Pos : TEXCOORD2; // Posicion real 3d }; //Vertex Shader VS_OUTPUT vs_main(VS_INPUT Input) { - VS_OUTPUT Output; - - //Proyectar posicion - Output.Position = mul(Input.Position, matWorldViewProj); - - //Propagamos las coordenadas de textura - Output.Texcoord = Input.Texcoord; - - // Calculo la posicion real (en world space) - float4 pos_real = mul(Input.Position, matWorld); - // Y la propago usando las coordenadas de texturas 2 (*) - Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); - - // Transformo la normal y la normalizo (si la escala no es uniforme usar la inversa Traspta) - //Output.Norm = normalize(mul(Input.Normal,matInverseTransposeWorld)); - Output.Norm = normalize(mul(Input.Normal, matWorld)); - return(Output); + VS_OUTPUT Output; + + //Proyectar posicion + Output.Position = mul(Input.Position, matWorldViewProj); + + //Propagamos las coordenadas de textura + Output.Texcoord = Input.Texcoord; + + // Calculo la posicion real (en world space) + float4 pos_real = mul(Input.Position, matWorld); + // Y la propago usando las coordenadas de texturas 2 (*) + Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); + + // Transformo la normal y la normalizo (si la escala no es uniforme usar la inversa Traspta) + //Output.Norm = normalize(mul(Input.Normal,matInverseTransposeWorld)); + Output.Norm = normalize(mul(Input.Normal, matWorld)); + return (Output); + } + // (*) Usar las coordenadas de texturas 2, 3 y demas es un "hack" habitual, // que permite pasarle al pixel shader distintas variables que se calculan por vertice // El rasterizer se ocupa de que al PS le lleguen los valores interpolados. @@ -83,13 +85,13 @@ VS_OUTPUT vs_main(VS_INPUT Input) // //Pixel Shader -float4 ps_main(float3 Texcoord: TEXCOORD0, float3 N : TEXCOORD1, +float4 ps_main(float3 Texcoord : TEXCOORD0, float3 N : TEXCOORD1, float3 Pos : TEXCOORD2) : COLOR0 { - float ld = 0; // luz difusa - float le = 0; // luz specular + float ld = 0; // luz difusa + float le = 0; // luz specular - N = normalize(N); + N = normalize(N); // si hubiera varias luces, se podria iterar por c/u. // Pero hay que tener en cuenta que este algoritmo es bastante pesado @@ -99,22 +101,22 @@ float4 ps_main(float3 Texcoord: TEXCOORD0, float3 N : TEXCOORD1, // el resto se aproxima con luz ambiente. // for(int =0;i; - MinFilter = Point; - MagFilter = Point; - MipFilter = Point; - AddressU = Clamp; - AddressV = Clamp; + Texture = ; + MinFilter = Point; + MagFilter = Point; + MipFilter = Point; + AddressU = Clamp; + AddressV = Clamp; }; //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 Norm : TEXCOORD1; // Normales - float3 Pos : TEXCOORD2; // Posicion real 3d + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float3 Pos : TEXCOORD2; // Posicion real 3d }; //----------------------------------------------------------------------------- @@ -64,11 +64,11 @@ void VertShadow(float4 Pos : POSITION, out float2 Depth : TEXCOORD0) { // transformacion estandard - oPos = mul(Pos, matWorld); // uso el del mesh - oPos = mul(oPos, g_mViewLightProj); // pero visto desde la pos. de la luz + oPos = mul(Pos, matWorld); // uso el del mesh + oPos = mul(oPos, g_mViewLightProj); // pero visto desde la pos. de la luz // devuelvo: profundidad = z/w - Depth.xy = oPos.zw; + Depth.xy = oPos.zw; } //----------------------------------------------------------------------------- @@ -79,16 +79,16 @@ void PixShadow(float2 Depth : TEXCOORD0, out float4 Color : COLOR) // parche para ver el shadow map //float k = Depth.x/Depth.y; //Color = (1-k); - Color = Depth.x / Depth.y; + Color = Depth.x / Depth.y; } technique RenderShadow { - pass p0 - { - VertexShader = compile vs_3_0 VertShadow(); - PixelShader = compile ps_3_0 PixShadow(); - } + pass p0 + { + VertexShader = compile vs_3_0 VertShadow(); + PixelShader = compile ps_3_0 PixShadow(); + } } //----------------------------------------------------------------------------- @@ -105,18 +105,18 @@ void VertScene(float4 iPos : POSITION, ) { // transformo al screen space - oPos = mul(iPos, matWorldViewProj); + oPos = mul(iPos, matWorldViewProj); // propago coordenadas de textura - Tex = iTex; + Tex = iTex; // propago la normal - vNormal = mul(iNormal, (float3x3)matWorldView); + vNormal = mul(iNormal, (float3x3) matWorldView); // propago la posicion del vertice en World space - vPos = mul(iPos, matWorld); + vPos = mul(iPos, matWorld); // propago la posicion del vertice en el espacio de proyeccion de la luz - vPosLight = mul(vPos, g_mViewLightProj); + vPosLight = mul(vPos, g_mViewLightProj); } //----------------------------------------------------------------------------- @@ -126,19 +126,19 @@ float4 PixScene(float2 Tex : TEXCOORD0, float4 vPos : TEXCOORD1, float3 vNormal : TEXCOORD2, float4 vPosLight : TEXCOORD3 -) :COLOR +) : COLOR { - float3 vLight = normalize(float3(vPos - g_vLightPos)); - float cono = dot(vLight, g_vLightDir); - float4 K = 0.0; - if (cono > 0.7) - { + float3 vLight = normalize(float3(vPos - g_vLightPos)); + float cono = dot(vLight, g_vLightDir); + float4 K = 0.0; + if (cono > 0.7) + { // coordenada de textura CT - float2 CT = 0.5 * vPosLight.xy / vPosLight.w + float2(0.5, 0.5); - CT.y = 1.0f - CT.y; + float2 CT = 0.5 * vPosLight.xy / vPosLight.w + float2(0.5, 0.5); + CT.y = 1.0f - CT.y; // sin ningun aa. conviene con smap size >= 512 - float I = (tex2D(g_samShadow, CT) + EPSILON < vPosLight.z / vPosLight.w) ? 0.0f : 1.0f; + float I = (tex2D(g_samShadow, CT) + EPSILON < vPosLight.z / vPosLight.w) ? 0.0f : 1.0f; // interpolacion standard bi-lineal del shadow map // CT va de 0 a 1, lo multiplico x el tamaño de la textura @@ -167,22 +167,22 @@ float4 PixScene(float2 Tex : TEXCOORD0, I /= (2*r+1)*(2*r+1); */ - if (cono < 0.8) - I *= 1 - (0.8 - cono) * 10; + if (cono < 0.8) + I *= 1 - (0.8 - cono) * 10; - K = I; - } + K = I; + } - float4 color_base = tex2D(diffuseMap, Tex); - color_base.rgb *= 0.5 + 0.5*K; - return color_base; + float4 color_base = tex2D(diffuseMap, Tex); + color_base.rgb *= 0.5 + 0.5 * K; + return color_base; } technique RenderScene { - pass p0 - { - VertexShader = compile vs_3_0 VertScene(); - PixelShader = compile ps_3_0 PixScene(); - } + pass p0 + { + VertexShader = compile vs_3_0 VertScene(); + PixelShader = compile ps_3_0 PixScene(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/WorkshopShaders/ToonShading.fx b/TGC.Examples/Shaders/WorkshopShaders/ToonShading.fx index 8465fd8a..8ca2cef1 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/ToonShading.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/ToonShading.fx @@ -16,52 +16,52 @@ float4x4 matInverseTransposeWorld; //Matriz Transpose(Invert(World)) texture texDiffuseMap; sampler2D diffuseMap = sampler_state { - Texture = (texDiffuseMap); - ADDRESSU = WRAP; - ADDRESSV = WRAP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (texDiffuseMap); + ADDRESSU = WRAP; + ADDRESSV = WRAP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; float3 fvLightPosition = float3(-100.00, 100.00, -100.00); float3 fvEyePosition = float3(0.00, 0.00, -100.00); -float k_la = 0.3; // luz ambiente global -float k_ld = 0.9; // luz difusa -float k_ls = 0.4; // luz specular +float k_la = 0.3; // luz ambiente global +float k_ld = 0.9; // luz difusa +float k_ls = 0.4; // luz specular float fSpecularPower = 16.84; -float screen_dx; // tamaño de la pantalla en pixels +float screen_dx; // tamaño de la pantalla en pixels float screen_dy; //Input del Vertex Shader struct VS_INPUT { - float4 Position : POSITION0; - float3 Normal : NORMAL0; - float4 Color : COLOR; - float2 Texcoord : TEXCOORD0; + float4 Position : POSITION0; + float3 Normal : NORMAL0; + float4 Color : COLOR; + float2 Texcoord : TEXCOORD0; }; texture g_RenderTarget; sampler RenderTarget = sampler_state { - Texture = ; - MipFilter = NONE; - MinFilter = NONE; - MagFilter = NONE; + Texture = ; + MipFilter = NONE; + MinFilter = NONE; + MagFilter = NONE; }; // mapa de normales -texture g_Normals; // mapa de normales +texture g_Normals; // mapa de normales sampler Normales = sampler_state { - Texture = ; - MipFilter = NONE; - MinFilter = NONE; - MagFilter = NONE; + Texture = ; + MipFilter = NONE; + MinFilter = NONE; + MagFilter = NONE; }; /**************************************************************************************/ @@ -71,71 +71,71 @@ sampler_state //Output del Vertex Shader struct VS_OUTPUT { - float4 Position : POSITION0; - float2 Texcoord : TEXCOORD0; - float3 Norm : TEXCOORD1; // Normales - float3 Pos : TEXCOORD2; // Posicion real 3d + float4 Position : POSITION0; + float2 Texcoord : TEXCOORD0; + float3 Norm : TEXCOORD1; // Normales + float3 Pos : TEXCOORD2; // Posicion real 3d }; //Vertex Shader VS_OUTPUT vs_main(VS_INPUT Input) { - VS_OUTPUT Output; + VS_OUTPUT Output; //Proyectar posicion - Output.Position = mul(Input.Position, matWorldViewProj); + Output.Position = mul(Input.Position, matWorldViewProj); //Las Texcoord quedan igual - Output.Texcoord = Input.Texcoord; + Output.Texcoord = Input.Texcoord; // Calculo la posicion real - float4 pos_real = mul(Input.Position, matWorld); - Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); + float4 pos_real = mul(Input.Position, matWorld); + Output.Pos = float3(pos_real.x, pos_real.y, pos_real.z); // Transformo la normal y la normalizo //Output.Norm = normalize(mul(Input.Normal,matInverseTransposeWorld)); - Output.Norm = normalize(mul(Input.Normal, matWorld)); - return(Output); + Output.Norm = normalize(mul(Input.Normal, matWorld)); + return (Output); } //Pixel Shader -float4 ps_main(float3 Texcoord: TEXCOORD0, float3 N : TEXCOORD1, +float4 ps_main(float3 Texcoord : TEXCOORD0, float3 N : TEXCOORD1, float3 Pos : TEXCOORD2) : COLOR0 { - float ld = 0; // luz difusa - float le = 0; // luz specular + float ld = 0; // luz difusa + float le = 0; // luz specular // normalizo la normal - N = normalize(N); + N = normalize(N); // 1- calculo la luz diffusa - float3 LD = normalize(fvLightPosition - float3(Pos.x,Pos.y,Pos.z)); - ld += saturate(dot(N, LD))*k_ld; + float3 LD = normalize(fvLightPosition - float3(Pos.x, Pos.y, Pos.z)); + ld += saturate(dot(N, LD)) * k_ld; // 2- calcula la reflexion specular - float3 D = normalize(float3(Pos.x,Pos.y,Pos.z) - fvEyePosition); - float ks = saturate(dot(reflect(LD,N), D)); - ks = pow(ks,fSpecularPower); - le += ks*k_ls; + float3 D = normalize(float3(Pos.x, Pos.y, Pos.z) - fvEyePosition); + float ks = saturate(dot(reflect(LD, N), D)); + ks = pow(ks, fSpecularPower); + le += ks * k_ls; //Obtener el texel de textura //float4 fvBaseColor = tex2D( diffuseMap, Texcoord ); //voy a usar un color listo: - float4 fvBaseColor = float4(1,0.5,0.5,1); + float4 fvBaseColor = float4(1, 0.5, 0.5, 1); // suma luz diffusa, ambiente y especular - float4 RGBColor = 0; - RGBColor.rgb = saturate(fvBaseColor*(saturate(k_la + ld)) + le); - return RGBColor; + float4 RGBColor = 0; + RGBColor.rgb = saturate(fvBaseColor * (saturate(k_la + ld)) + le); + return RGBColor; } technique DefaultTechnique { - pass Pass_0 - { - VertexShader = compile vs_2_0 vs_main(); - PixelShader = compile ps_2_0 ps_main(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 ps_main(); + } } /**************************************************************************************/ @@ -147,35 +147,35 @@ void VSCopy(float4 vPos : POSITION, out float4 oPos : POSITION, out float2 oScreenPos : TEXCOORD0) { - oPos = vPos; - oScreenPos = vTex; - oPos.w = 1; + oPos = vPos; + oScreenPos = vTex; + oPos.w = 1; } // pixel copy -void PSCopy(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) +void PSCopy(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) { - float4 c0 = tex2D(RenderTarget, screen_pos); - float4 c1 = tex2D(RenderTarget, screen_pos + float2(0, 15 / screen_dy)); - float4 c2 = tex2D(RenderTarget, screen_pos + float2(15 / screen_dx, 0)); - float4 c3 = tex2D(RenderTarget, screen_pos + float2(15 / screen_dx, 15 / screen_dy)); - - float4 c4 = tex2D(RenderTarget, screen_pos); - float4 c5 = tex2D(RenderTarget, screen_pos + float2(0, 35 / screen_dy)); - float4 c6 = tex2D(RenderTarget, screen_pos + float2(35 / screen_dx, 0)); - float4 c7 = tex2D(RenderTarget, screen_pos + float2(35 / screen_dx, 35 / screen_dy)); - - Color = (c0 + c1 + c2 + c3 + c4 + c5 + c6 + c7) / 8; - Color.a = 1; + float4 c0 = tex2D(RenderTarget, screen_pos); + float4 c1 = tex2D(RenderTarget, screen_pos + float2(0, 15 / screen_dy)); + float4 c2 = tex2D(RenderTarget, screen_pos + float2(15 / screen_dx, 0)); + float4 c3 = tex2D(RenderTarget, screen_pos + float2(15 / screen_dx, 15 / screen_dy)); + + float4 c4 = tex2D(RenderTarget, screen_pos); + float4 c5 = tex2D(RenderTarget, screen_pos + float2(0, 35 / screen_dy)); + float4 c6 = tex2D(RenderTarget, screen_pos + float2(35 / screen_dx, 0)); + float4 c7 = tex2D(RenderTarget, screen_pos + float2(35 / screen_dx, 35 / screen_dy)); + + Color = (c0 + c1 + c2 + c3 + c4 + c5 + c6 + c7) / 8; + Color.a = 1; } technique CopyScreen { - pass Pass_0 - { - VertexShader = compile vs_3_0 VSCopy(); - PixelShader = compile ps_3_0 PSCopy(); - } + pass Pass_0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSCopy(); + } } /**************************************************************************************/ @@ -183,65 +183,63 @@ technique CopyScreen /**************************************************************************************/ // Pixel shader que genera el mapa de Normales -void NormalMapPS(float3 Norm : TEXCOORD1, out float4 Color : COLOR) +void NormalMapPS(float3 Norm : TEXCOORD1, out float4 Color : COLOR) { - Color.a = 1; - Color.r = Norm.x; - Color.g = Norm.y; - Color.b = Norm.z; + Color.a = 1; + Color.r = Norm.x; + Color.g = Norm.y; + Color.b = Norm.z; } // edge detect -void PSEdge(float2 screen_pos : TEXCOORD0, +void PSEdge(float2 screen_pos : TEXCOORD0, out float4 Color : COLOR) { - float4 pixel = tex2D(RenderTarget, screen_pos); - - float ep = 0.5; - float4 c0 = tex2D(Normales, screen_pos); - float4 c1 = tex2D(Normales, screen_pos + float2(0, 1 / screen_dy)); - int flag = 0; - Color.a = 1; - Color.rgb = 0; - if (distance(c0, c1) > ep) - flag = 1; - else - { - c1 = tex2D(Normales, screen_pos + float2(1 / screen_dy, 0)); - if (distance(c0, c1) > ep) - flag = 1; - else - { - c1 = tex2D(Normales, screen_pos + float2(2 / screen_dy, 0)); - if (distance(c0, c1) > ep) - flag = 2; - else - { - c1 = tex2D(Normales, screen_pos + float2(0, 2 / screen_dy)); - if (distance(c0, c1) > ep) - flag = 2; - } - } - } - - if (flag == 0) - Color.rgb = round(pixel.rgb * 3) / 3; - else - if (flag == 1) - Color.rgb = 1; - else - if (flag == 2) - Color.r = 1; + float4 pixel = tex2D(RenderTarget, screen_pos); + + float ep = 0.5; + float4 c0 = tex2D(Normales, screen_pos); + float4 c1 = tex2D(Normales, screen_pos + float2(0, 1 / screen_dy)); + int flag = 0; + Color.a = 1; + Color.rgb = 0; + if (distance(c0, c1) > ep) + flag = 1; + else + { + c1 = tex2D(Normales, screen_pos + float2(1 / screen_dy, 0)); + if (distance(c0, c1) > ep) + flag = 1; + else + { + c1 = tex2D(Normales, screen_pos + float2(2 / screen_dy, 0)); + if (distance(c0, c1) > ep) + flag = 2; + else + { + c1 = tex2D(Normales, screen_pos + float2(0, 2 / screen_dy)); + if (distance(c0, c1) > ep) + flag = 2; + } + } + } + + if (flag == 0) + Color.rgb = round(pixel.rgb * 3) / 3; + else if (flag == 1) + Color.rgb = 1; + else if (flag == 2) + Color.r = 1; } // Genera el mapa de normales technique NormalMap { - pass P0 - { - VertexShader = compile vs_3_0 vs_main(); - PixelShader = compile ps_3_0 NormalMapPS(); - } + pass P0 + { + VertexShader = compile vs_3_0 vs_main(); + PixelShader = compile ps_3_0 NormalMapPS(); + } } /**************************************************************************************/ @@ -250,9 +248,9 @@ technique NormalMap technique EdgeDetect { - pass P0 - { - VertexShader = compile vs_3_0 VSCopy(); - PixelShader = compile ps_3_0 PSEdge(); - } + pass P0 + { + VertexShader = compile vs_3_0 VSCopy(); + PixelShader = compile ps_3_0 PSEdge(); + } } \ No newline at end of file diff --git a/TGC.Examples/Shaders/WorkshopShaders/VolRender.fx b/TGC.Examples/Shaders/WorkshopShaders/VolRender.fx index e387dea5..6999def2 100644 --- a/TGC.Examples/Shaders/WorkshopShaders/VolRender.fx +++ b/TGC.Examples/Shaders/WorkshopShaders/VolRender.fx @@ -1,4 +1,4 @@ -float screen_dx; // tamaño de la pantalla en pixels +float screen_dx; // tamaño de la pantalla en pixels float screen_dy; //Textura utilizada por el Pixel Shader @@ -6,31 +6,31 @@ texture tex_buffer; sampler2D buffer = sampler_state { - Texture = (tex_buffer); - ADDRESSU = CLAMP; - ADDRESSV = CLAMP; - MINFILTER = LINEAR; - MAGFILTER = LINEAR; - MIPFILTER = LINEAR; + Texture = (tex_buffer); + ADDRESSU = CLAMP; + ADDRESSV = CLAMP; + MINFILTER = LINEAR; + MAGFILTER = LINEAR; + MIPFILTER = LINEAR; }; void vs_copy(float4 vPos : POSITION, float2 vTex : TEXCOORD0, out float4 oPos : POSITION, out float2 oScreenPos : TEXCOORD0) { - oPos = vPos; - oScreenPos = vTex; - oPos.w = 1; + oPos = vPos; + oScreenPos = vTex; + oPos.w = 1; } float4 ps_raytracing(float2 vPos : VPOS, float2 texcoords : TEXCOORD0) : COLOR0 { - return tex2D(buffer,texcoords); + return tex2D(buffer, texcoords); } technique volRender { - pass p0 - { - VertexShader = compile vs_3_0 vs_copy(); - PixelShader = compile ps_3_0 ps_raytracing(); - } + pass p0 + { + VertexShader = compile vs_3_0 vs_copy(); + PixelShader = compile ps_3_0 ps_raytracing(); + } } \ No newline at end of file diff --git a/TGC.Examples/ShadersExamples/BasicShader.cs b/TGC.Examples/ShadersExamples/BasicShader.cs index 60b8a9fe..69f5efb8 100644 --- a/TGC.Examples/ShadersExamples/BasicShader.cs +++ b/TGC.Examples/ShadersExamples/BasicShader.cs @@ -54,7 +54,7 @@ public override void Init() // indico que tecnica voy a usar // Hay effectos que estan organizados con mas de una tecnica. - mesh.Technique = "RenderScene"; + mesh.Technique = "RenderScene2"; //Centrar camara rotacional respecto a este mesh diff --git a/TGC.Examples/ShadersExamples/DemoShaders.cs b/TGC.Examples/ShadersExamples/DemoShaders.cs index 89a7bb50..1e35f8f1 100644 --- a/TGC.Examples/ShadersExamples/DemoShaders.cs +++ b/TGC.Examples/ShadersExamples/DemoShaders.cs @@ -130,7 +130,7 @@ public override void Init() mesh.Scale = new TGCVector3(0.5f, 0.5f, 0.5f); mesh.Position = new TGCVector3(0f, 0f, 0f); - mesh.AutoTransformEnable = false; + mesh.AutoTransform = false; var size = mesh.BoundingBox.calculateSize(); largo_tanque = Math.Abs(size.Z); alto_tanque = Math.Abs(size.Y) * mesh.Scale.Y; @@ -138,7 +138,7 @@ public override void Init() an_tanque = 0; canoa.Scale = new TGCVector3(1f, 1f, 1f); canoa.Position = new TGCVector3(3000f, 550f, 0f); - canoa.AutoTransformEnable = false; + canoa.AutoTransform = false; dir_canoa = new TGCVector3(0, 0, 1); nivel_mar = 135f; piso.Scale = new TGCVector3(25f, 1f, 25f); diff --git a/TGC.Examples/ShadersExamples/EnviromentMap.cs b/TGC.Examples/ShadersExamples/EnviromentMap.cs index c957313f..30e06476 100644 --- a/TGC.Examples/ShadersExamples/EnviromentMap.cs +++ b/TGC.Examples/ShadersExamples/EnviromentMap.cs @@ -109,12 +109,12 @@ public override void Init() sceneX = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Sphere\\Sphere-TgcScene.xml"); meshX = sceneX.Meshes[0]; - meshX.AutoTransformEnable = true; + meshX.AutoTransform = true; scene2 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera\\Palmera-TgcScene.xml"); palmera = scene2.Meshes[0]; - palmera.AutoTransformEnable = true; + palmera.AutoTransform = true; scene3 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\AvionCaza\\AvionCaza-TgcScene.xml"); @@ -137,7 +137,7 @@ public override void Init() for (var j = 0; j < 15; j++) { var instance = palmera.createMeshInstance(palmera.Name + i); - instance.AutoTransformEnable = true; + instance.AutoTransform = true; 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)); diff --git a/TGC.Examples/ShadersExamples/NightVision.cs b/TGC.Examples/ShadersExamples/NightVision.cs index 7e13ee88..83fb4046 100644 --- a/TGC.Examples/ShadersExamples/NightVision.cs +++ b/TGC.Examples/ShadersExamples/NightVision.cs @@ -59,16 +59,16 @@ public override void Init() var scene2 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Pasto\\Pasto-TgcScene.xml"); pasto = scene2.Meshes[0]; - pasto.AutoTransformEnable = true; + pasto.AutoTransform = true; var scene3 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\ArbolSelvatico\\ArbolSelvatico-TgcScene.xml"); arbol = scene3.Meshes[0]; - arbol.AutoTransformEnable = true; + arbol.AutoTransform = true; var scene4 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Arbusto2\\Arbusto2-TgcScene.xml"); arbusto = scene4.Meshes[0]; - arbusto.AutoTransformEnable = true; + arbusto.AutoTransform = true; //Cargar personaje con animaciones var skeletalLoader = new TgcSkeletalLoader(); diff --git a/TGC.Examples/ShadersExamples/OutRun.cs b/TGC.Examples/ShadersExamples/OutRun.cs index a2481ed2..668e2cfc 100644 --- a/TGC.Examples/ShadersExamples/OutRun.cs +++ b/TGC.Examples/ShadersExamples/OutRun.cs @@ -82,7 +82,7 @@ public override void Init() var loader = new TgcSceneLoader(); var scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\Auto\\Auto-TgcScene.xml"); car = scene.Meshes[0]; - car.AutoTransformEnable = false; + car.AutoTransform = false; //Cargar Shader personalizado string compilationErrors; diff --git a/TGC.Examples/ShadersExamples/PhongShading.cs b/TGC.Examples/ShadersExamples/PhongShading.cs index bdfc4bd6..fc129d29 100644 --- a/TGC.Examples/ShadersExamples/PhongShading.cs +++ b/TGC.Examples/ShadersExamples/PhongShading.cs @@ -75,7 +75,7 @@ public override void Init() //Crear caja para indicar ubicacion de la luz lightBox = TGCBox.fromSize(new TGCVector3(5, 5, 5), Color.Yellow); - lightBox.AutoTransformEnable = true; + lightBox.AutoTransform = true; // Creo 3 viewport, para mostrar una comparativa entre los metodos de iluminacion diff --git a/TGC.Examples/ShadersExamples/ShadowMap.cs b/TGC.Examples/ShadersExamples/ShadowMap.cs index 1bd90da5..cf1402ce 100644 --- a/TGC.Examples/ShadersExamples/ShadowMap.cs +++ b/TGC.Examples/ShadersExamples/ShadowMap.cs @@ -73,7 +73,7 @@ public override void Init() avion.Scale = new TGCVector3(0.1f, 0.1f, 0.1f); avion.Position = new TGCVector3(100f, 100f, 0f); - avion.AutoTransformEnable = false; + avion.AutoTransform = false; dir_avion = new TGCVector3(0, 0, 1); //Cargar Shader personalizado diff --git a/TGC.Examples/Sound/PlaySound3D.cs b/TGC.Examples/Sound/PlaySound3D.cs index 75e66ab3..6f69b242 100644 --- a/TGC.Examples/Sound/PlaySound3D.cs +++ b/TGC.Examples/Sound/PlaySound3D.cs @@ -53,7 +53,7 @@ public override void Init() //Crear piso var pisoTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\tierra.jpg"); piso = TGCBox.fromSize(new TGCVector3(5000, 5, 5000), pisoTexture); - piso.AutoTransformEnable = true; + piso.AutoTransform = true; piso.Position = new TGCVector3(0, -60, 0); //Cargar obstaculos y posicionarlos. Los obstaculos se crean con TgcBox en lugar de cargar un modelo. @@ -65,7 +65,7 @@ public override void Init() //Obstaculo 1 obstaculo = TGCBox.fromSize(new TGCVector3(80, 150, 80), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\Quake\\TexturePack3\\goo2.jpg")); - obstaculo.AutoTransformEnable = true; + obstaculo.AutoTransform = true; obstaculo.Position = new TGCVector3(-250, 0, 0); obstaculos.Add(obstaculo); @@ -81,7 +81,7 @@ public override void Init() obstaculo = TGCBox.fromSize(new TGCVector3(80, 300, 80), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\Quake\\TexturePack3\\lun_dirt.jpg")); - obstaculo.AutoTransformEnable = true; + obstaculo.AutoTransform = true; obstaculo.Position = new TGCVector3(250, 0, 800); obstaculos.Add(obstaculo); @@ -94,7 +94,7 @@ public override void Init() obstaculo = TGCBox.fromSize(new TGCVector3(80, 100, 150), TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\Quake\\TexturePack3\\Metal2_1.jpg")); - obstaculo.AutoTransformEnable = true; + obstaculo.AutoTransform = true; obstaculo.Position = new TGCVector3(500, 0, -400); obstaculos.Add(obstaculo); @@ -108,7 +108,7 @@ public override void Init() var scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\Hummer\\Hummer-TgcScene.xml"); personaje = scene.Meshes[0]; - personaje.AutoTransformEnable = true; + personaje.AutoTransform = true; personaje.Position = new TGCVector3(0, -50, 0); //Hacer que el Listener del sonido 3D siga al personaje diff --git a/TGC.Examples/TGC.Examples.csproj b/TGC.Examples/TGC.Examples.csproj index 84ac543a..72479ec4 100644 --- a/TGC.Examples/TGC.Examples.csproj +++ b/TGC.Examples/TGC.Examples.csproj @@ -109,6 +109,10 @@ + + + + @@ -223,6 +227,10 @@ + + + + diff --git a/TGC.Examples/Transformations/EjemploQuaternions.cs b/TGC.Examples/Transformations/EjemploQuaternions.cs index fa2bd5f0..7f69abce 100644 --- a/TGC.Examples/Transformations/EjemploQuaternions.cs +++ b/TGC.Examples/Transformations/EjemploQuaternions.cs @@ -33,7 +33,7 @@ public override void Init() var textureQuat = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\paredMuyRugosa.jpg"); boxTGCQuaternion = TGCBox.fromSize(new TGCVector3(50, 0, 0), new TGCVector3(50, 50, 50), textureQuat); - boxTGCQuaternion.AutoTransformEnable = false; + boxTGCQuaternion.AutoTransform = false; Modifiers.addVertex3f("Rotacion", TGCVector3.Empty, new TGCVector3(360, 360, 360), TGCVector3.Empty); diff --git a/TGC.Examples/Transformations/SistemaSolar/SistemaSolar.cs b/TGC.Examples/Transformations/SistemaSolar/SistemaSolar.cs index c6723d00..97eac310 100644 --- a/TGC.Examples/Transformations/SistemaSolar/SistemaSolar.cs +++ b/TGC.Examples/Transformations/SistemaSolar/SistemaSolar.cs @@ -78,9 +78,9 @@ public override void Init() }); //Deshabilitamos el manejo automatico de Transformaciones de TgcMesh, para poder manipularlas en forma personalizada - sun.AutoTransformEnable = false; - earth.AutoTransformEnable = false; - moon.AutoTransformEnable = false; + sun.AutoTransform = false; + earth.AutoTransform = false; + moon.AutoTransform = false; //Camara en primera persona Camara = new TgcRotationalCamera(new TGCVector3(0f, 200f, 1000f), 500f, Input); @@ -93,8 +93,9 @@ public override void Update() public override void Render() { + //BackgroundColor D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); - D3DDevice.Instance.Device.BeginScene(); + BeginScene(); ClearTextures(); //Actualizar transformacion y renderizar el sol diff --git a/TGC.Examples/Tutorial/Tutorial1.cs b/TGC.Examples/Tutorial/Tutorial1.cs index efb27113..4597943c 100644 --- a/TGC.Examples/Tutorial/Tutorial1.cs +++ b/TGC.Examples/Tutorial/Tutorial1.cs @@ -79,7 +79,7 @@ public override void Init() center = new TGCVector3(-15, 0, 0); texture = TgcTexture.createTexture(MediaDir + "MeshCreator\\Textures\\Metal\\cajaMetal.jpg"); box3 = TGCBox.fromSize(center, size, texture); - box3.AutoTransformEnable = true; + 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 diff --git a/TGC.Examples/Tutorial/Tutorial2.cs b/TGC.Examples/Tutorial/Tutorial2.cs index 039c41be..dd2d2722 100644 --- a/TGC.Examples/Tutorial/Tutorial2.cs +++ b/TGC.Examples/Tutorial/Tutorial2.cs @@ -45,7 +45,7 @@ public override void Init() //De toda la escena solo nos interesa guardarnos el primer modelo (el único que hay en este caso). mesh = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\Hummer\\Hummer-TgcScene.xml").Meshes[0]; - mesh.AutoTransformEnable = true; + mesh.AutoTransform = true; mesh.RotateY(FastMath.QUARTER_PI); mesh.Move(new TGCVector3(100, 40, -200)); //mesh.Transform = TGCMatrix.RotationY(FastMath.QUARTER_PI) * TGCMatrix.Translation(100,40,-200); diff --git a/TGC.Examples/Tutorial/Tutorial3.cs b/TGC.Examples/Tutorial/Tutorial3.cs index 2cb5e015..7c065595 100644 --- a/TGC.Examples/Tutorial/Tutorial3.cs +++ b/TGC.Examples/Tutorial/Tutorial3.cs @@ -44,7 +44,7 @@ public override void Init() //Solo nos interesa el primer modelo de esta escena (tiene solo uno) mainMesh = scene2.Meshes[0]; - mainMesh.AutoTransformEnable = true; + mainMesh.AutoTransform = true; //Movemos el mesh un poco para arriba. Porque sino choca con el piso todo el tiempo y no se puede mover. mainMesh.Move(0, 5, 0); diff --git a/TGC.Examples/WorkshopShaders/BasicShader.cs b/TGC.Examples/WorkshopShaders/BasicShader.cs new file mode 100644 index 00000000..e4e1bbc9 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/BasicShader.cs @@ -0,0 +1,97 @@ +using Microsoft.DirectX.Direct3D; +using System.Drawing; +using TGC.Core.Direct3D; +using TGC.Core.Mathematica; +using TGC.Core.SceneLoader; +using TGC.Core.Shaders; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Camara; +using TGC.Examples.Example; + +namespace Examples.WorkshopShaders +{ + /// + /// Ejemplo EnvMap: + /// Unidades Involucradas: + /// # Unidad 8 - Adaptadores de Video - Shaders + /// + /// Es el hola mundo de los shaders + /// + /// Autor: Mariano Banquiero + /// + /// + public class BasicShader : TGCExampleViewer + { + private Effect effect; + private TgcScene scene; + private TgcMesh mesh; + private float time; + + public BasicShader(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-BasicShader"; + Description = "Ejemplo de Shader Basico"; + } + + public override void Init() + { + //Crear loader + TgcSceneLoader loader = new TgcSceneLoader(); + + //Cargar los mesh: + scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\TanqueFuturistaRuedas\\TanqueFuturistaRuedas-TgcScene.xml"); + mesh = scene.Meshes[0]; + mesh.Scale = new TGCVector3(5, 5, 5); + mesh.Position = new TGCVector3(0f, 0f, 0f); + + //Cargar Shader personalizado + effect = TgcShaders.loadEffect(ShadersDir + "WorkshopShaders\\BasicShader.fx"); + + // le asigno el efecto a la malla + mesh.Effect = effect; + + // indico que tecnica voy a usar + // Hay effectos que estan organizados con mas de una tecnica. + mesh.Technique = "RenderScene"; + + //Centrar camara rotacional respecto a este mesh + Camara = new TgcRotationalCamera(mesh.BoundingBox.calculateBoxCenter(), mesh.BoundingBox.calculateBoxRadius() * 5, Input); + + time = 0; + } + + public override void Update() + { + PreUpdate(); + } + + public override void Render() + { + ClearTextures(); + D3DDevice.Instance.Device.BeginScene(); + + time += ElapsedTime; + + D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + + // Cargar variables de shader, por ejemplo el tiempo transcurrido. + effect.SetValue("time", time); + + // dibujo la malla pp dicha + mesh.Render(); + + RenderAxis(); + RenderFPS(); + D3DDevice.Instance.Device.EndScene(); + D3DDevice.Instance.Device.Present(); + } + + public override void Dispose() + { + effect.Dispose(); + scene.disposeAll(); + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/ComboRata.cs b/TGC.Examples/WorkshopShaders/ComboRata.cs new file mode 100644 index 00000000..0dfd5b07 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/ComboRata.cs @@ -0,0 +1,444 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using TGC.Core.Collision; +using TGC.Core.Mathematica; +using TGC.Core.SceneLoader; +using TGC.Core.SkeletalAnimation; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Core.Utils; +using TGC.Examples.Example; +using TgcViewer.Utils.Gui; + +namespace Examples.WorkshopShaders +{ + public class ComboRata : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + private TgcScene scene; + private Effect effect; + private Texture g_pBaseTexture; + private Texture g_pHeightmap; + private Texture g_pBaseTexture2; + private Texture g_pHeightmap2; + private Texture g_pBaseTexture3; + private Texture g_pHeightmap3; + private Texture g_pBaseTexture4; + private Texture g_pHeightmap4; + private float time; + private List rooms = new List(); + + private List enemigos = new List(); + private float[] enemigo_an = new float[50]; + private int cant_enemigos = 0; + + // gui + private DXGui gui = new DXGui(); + + public ComboRata(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-ComboRata"; + Description = "ComboRata"; + } + + public override void Init() + { + time = 0f; + Device d3dDevice = GuiController.Instance.D3dDevice; + GuiController.Instance.CustomRenderEnabled = true; + MyMediaDir = MediaDir + "WorkshopShaders\\"; + MyShaderDir = ShadersDir + "WorkshopShaders\\"; + + //Crear loader + TgcSceneLoader loader = new TgcSceneLoader(); + scene = loader.loadSceneFromFile(MyMediaDir + "Piso\\comborata-TgcScene.xml"); + + g_pBaseTexture = TextureLoader.FromFile(d3dDevice, MyMediaDir + "Piso\\Textures\\rocks.jpg"); + g_pHeightmap = TextureLoader.FromFile(d3dDevice, MyMediaDir + "Piso\\Textures\\rocks_NM_height.tga"); + + g_pBaseTexture2 = TextureLoader.FromFile(d3dDevice, MyMediaDir + "Piso\\Textures\\stones.bmp"); + g_pHeightmap2 = TextureLoader.FromFile(d3dDevice, MyMediaDir + "Piso\\Textures\\stones_NM_height.tga"); + + g_pBaseTexture3 = TextureLoader.FromFile(d3dDevice, MyMediaDir + "Piso\\Textures\\granito.jpg"); + g_pHeightmap3 = TextureLoader.FromFile(d3dDevice, MyMediaDir + "Piso\\Textures\\saint_NM_height.tga"); + + g_pBaseTexture4 = TextureLoader.FromFile(d3dDevice, MyMediaDir + "Piso\\Textures\\granito.jpg"); + g_pHeightmap4 = TextureLoader.FromFile(d3dDevice, MyMediaDir + "Piso\\Textures\\four_NM_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); + } + + Modifiers.addVertex3f("LightDir", new TGCVector3(-1, -1, -1), new TGCVector3(1, 1, 1), new TGCVector3(0, -1, 0)); + Modifiers.addFloat("minSample", 1f, 10f, 10f); + Modifiers.addFloat("maxSample", 11f, 50f, 50f); + Modifiers.addFloat("HeightMapScale", 0.001f, 0.5f, 0.1f); + + GuiController.Instance.FpsCamera.Enable = true; + GuiController.Instance.FpsCamera.setCamera(new TGCVector3(147.2558f, 8.0536f, 262.2509f), new TGCVector3(148.0797f, 7.7869f, 262.7511f)); + + //Cargar personaje con animaciones + TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader(); + Random rnd = new Random(); + + // meto un enemigo por cada cuarto + cant_enemigos = 0; + foreach (TgcMesh mesh in scene.Meshes) + { + if (mesh.Name.Contains("Floor")) + { + float kx = rnd.Next(25, 75) / 100.0f; + float kz = rnd.Next(25, 75) / 100.0f; + float pos_x = mesh.BoundingBox.PMin.X * kx + mesh.BoundingBox.PMax.X * (1 - kx); + float pos_z = mesh.BoundingBox.PMin.Z * kz + mesh.BoundingBox.PMax.Z * (1 - kz); + + enemigos.Add(skeletalLoader.loadMeshAndAnimationsFromFile(MediaDir + "SkeletalAnimations\\BasicHuman\\" + "CombineSoldier-TgcSkeletalMesh.xml", MediaDir + "SkeletalAnimations\\BasicHuman\\", new string[] { MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Walk-TgcSkeletalAnim.xml", })); + + //Configurar animacion inicial + enemigos[cant_enemigos].playAnimation("Walk", true); + enemigos[cant_enemigos].Position = new TGCVector3(pos_x, 1f, pos_z); + enemigos[cant_enemigos].Scale = new TGCVector3(0.3f, 0.3f, 0.3f); + enemigo_an[cant_enemigos] = 0; + cant_enemigos++; + } + } + + // levanto el GUI + float W = GuiController.Instance.Panel3d.Width; + float H = GuiController.Instance.Panel3d.Height; + gui.Create(); + 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); + } + + public override void Update() + { + PreUpdate(); + + 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].move(vel * speed); + enemigos[t].Rotation = new TGCVector3(0, (float)Math.PI + an, 0); // +(float)Math.PI/2 + + //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] += (float)rnd.Next(0, 100) / 100.0f; + } + + enemigos[t].updateAnimation(); + } + } + + public override void Render() + { + Device device = GuiController.Instance.D3dDevice; + Control panel3d = GuiController.Instance.Panel3d; + float aspectRatio = (float)panel3d.Width / (float)panel3d.Height; + time += ElapsedTime; + + TGCVector3 lightDir = (TGCVector3)Modifiers["LightDir"]; + effect.SetValue("g_LightDir", TgcParserUtils.vector3ToFloat3Array(lightDir)); + effect.SetValue("min_cant_samples", (float)Modifiers["minSample"]); + effect.SetValue("max_cant_samples", (float)Modifiers["maxSample"]); + effect.SetValue("fHeightMapScale", (float)Modifiers["HeightMapScale"]); + effect.SetValue("fvEyePosition", TgcParserUtils.vector3ToFloat3Array(GuiController.Instance.FpsCamera.getPosition())); + + effect.SetValue("time", time); + effect.SetValue("aux_Tex", g_pBaseTexture); + effect.SetValue("height_map", g_pHeightmap); + effect.SetValue("phong_lighting", true); + + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + device.BeginScene(); + + foreach (TgcMesh mesh in scene.Meshes) + { + bool va = true; + int nro_textura = 0; + mesh.Effect = effect; + if (mesh.Name.Contains("Floor")) + { + effect.SetValue("g_normal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, -1, 0))); + effect.SetValue("g_tangent", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(1, 0, 0))); + effect.SetValue("g_binormal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 0, 1))); + nro_textura = 0; + } + else + if (mesh.Name.Contains("Roof")) + { + effect.SetValue("g_normal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 1, 0))); + effect.SetValue("g_tangent", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(1, 0, 0))); + effect.SetValue("g_binormal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 0, 1))); + nro_textura = 0; + + va = false; + } + else + if (mesh.Name.Contains("East")) + { + effect.SetValue("g_normal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(1, 0, 0))); + effect.SetValue("g_tangent", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 0, 1))); + effect.SetValue("g_binormal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 1, 0))); + nro_textura = 1; + } + else + if (mesh.Name.Contains("West")) + { + effect.SetValue("g_normal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(-1, 0, 0))); + effect.SetValue("g_tangent", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 0, 1))); + effect.SetValue("g_binormal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 1, 0))); + nro_textura = 1; + } + else + if (mesh.Name.Contains("North")) + { + effect.SetValue("g_normal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 0, -1))); + effect.SetValue("g_tangent", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(1, 0, 0))); + effect.SetValue("g_binormal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 1, 0))); + nro_textura = 1; + } + else + if (mesh.Name.Contains("South")) + { + effect.SetValue("g_normal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 0, 1))); + effect.SetValue("g_tangent", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(1, 0, 0))); + effect.SetValue("g_binormal", TgcParserUtils.vector3ToFloat3Array(new TGCVector3(0, 1, 0))); + nro_textura = 1; + } + + switch (nro_textura) + { + case 0: + default: + effect.SetValue("aux_Tex", g_pBaseTexture); + effect.SetValue("height_map", g_pHeightmap); + break; + + case 1: + effect.SetValue("aux_Tex", g_pBaseTexture2); + effect.SetValue("height_map", g_pHeightmap2); + break; + + case 2: + effect.SetValue("aux_Tex", g_pBaseTexture3); + effect.SetValue("height_map", g_pHeightmap3); + break; + + case 3: + effect.SetValue("aux_Tex", g_pBaseTexture4); + effect.SetValue("height_map", g_pHeightmap4); + break; + } + + if (va) + { + mesh.Technique = "ParallaxOcclusion2"; + mesh.Render(); + } + } + + //Render personames enemigos + foreach (TgcSkeletalMesh m in enemigos) + m.Render(); + + // Render hud + renderHUD(); + + gui.trapezoidal_style = false; + //radar de proximidad + float max_dist = 80; + foreach (TgcSkeletalMesh m in enemigos) + { + TGCVector3 pos_personaje = GuiController.Instance.FpsCamera.getPosition(); + TGCVector3 pos_enemigo = m.Position * 1; + float dist = (pos_personaje - pos_enemigo).Length(); + + if (dist < max_dist) + { + pos_enemigo.Y = m.BoundingBox.PMax.Y * 0.75f + m.BoundingBox.PMin.Y * 0.25f; + pos_enemigo.Project(device.Viewport, device.Transform.Projection, device.Transform.View, device.Transform.World); + if (pos_enemigo.Z > 0 && pos_enemigo.Z < 1) + { + float an = (max_dist - dist) / max_dist * 3.1415f * 2.0f; + int d = (int)dist; + gui.DrawArc(new TGCVector2(pos_enemigo.X + 20, pos_enemigo.Y), 40, 0, an, 10, dist < 30 ? Color.Tomato : Color.WhiteSmoke); + gui.DrawLine(pos_enemigo.X, pos_enemigo.Y, pos_enemigo.X + 20, pos_enemigo.Y, 3, Color.PowderBlue); + gui.DrawLine(pos_enemigo.X + 20, pos_enemigo.Y, pos_enemigo.X + 40, pos_enemigo.Y - 20, 3, Color.PowderBlue); + gui.TextOut((int)pos_enemigo.X + 50, (int)pos_enemigo.Y - 20, "Proximidad " + d, Color.PowderBlue); + } + } + } + gui.trapezoidal_style = true; + + device.EndScene(); + } + + public void renderHUD() + { + Device device = GuiController.Instance.D3dDevice; + device.RenderState.ZBufferEnable = false; + int W = GuiController.Instance.Panel3d.Width; + int H = GuiController.Instance.Panel3d.Height; + + // Elapsed time + int an = (int)(time * 10) % 360; + float hasta = an / 180.0f * (float)Math.PI; + gui.DrawArc(new TGCVector2(40, H - 100), 25, 0, hasta, 8, Color.Yellow); + gui.TextOut(20, H - 140, "Elapsed Time:" + Math.Round(time), Color.LightSteelBlue); + + // dibujo los enemigos + TGCVector3 pos_personaje = GuiController.Instance.FpsCamera.getPosition(); + TGCVector3 dir_view = GuiController.Instance.FpsCamera.getLookAt() - pos_personaje; + TGCVector2 dir_v = new TGCVector2(dir_view.X, dir_view.Z); + dir_v.Normalize(); + TGCVector2 dir_w = new TGCVector2(dir_v.Y, -dir_v.X); + + int dx = 1000; + int dy = 1000; + int dW = 200; + int dH = 200; + float ex = (float)dW / (float)dx; + float ey = (float)dH / (float)dy; + int ox = 10 + dW / 2; + int oy = 10 + dH / 2; + + for (int t = 0; t < cant_enemigos; ++t) + { + TGCVector3 pos = enemigos[t].Position - pos_personaje; + TGCVector2 p = new TGCVector2(pos.X, pos.Z); + float x = TGCVector2.Dot(dir_w, p); + float y = TGCVector2.Dot(dir_v, p); + int xm = (int)(ox + x * ex); + int ym = (int)(oy + y * ey); + + if (Math.Abs(xm - ox) < dW / 2 - 10 && Math.Abs(ym - oy) < dH / 2 - 10) + gui.DrawRect(xm - 2, ym - 2, xm + 2, ym + 2, 1, Color.WhiteSmoke); + } + + TGCVector2[] P = new TGCVector2[20]; + P[0] = new TGCVector2(ox - 5, oy + 5); + P[1] = new TGCVector2(ox + 5, oy + 5); + P[2] = new TGCVector2(ox, oy - 10); + P[3] = P[0]; + gui.DrawSolidPoly(P, 4, Color.Tomato, false); + gui.DrawCircle(new TGCVector2(ox, oy), 14, 3, Color.Yellow); + + foreach (TgcBoundingBox room in rooms) + { + TGCVector2[] Q = new TGCVector2[4]; + TGCVector2[] Qp = new TGCVector2[5]; + + float xm = 0; + float ym = 0; + Q[0] = new TGCVector2(room.PMin.X - pos_personaje.X, room.PMin.Z - pos_personaje.Z); + Q[1] = new TGCVector2(room.PMin.X - pos_personaje.X, room.PMax.Z - pos_personaje.Z); + Q[2] = new TGCVector2(room.PMax.X - pos_personaje.X, room.PMax.Z - pos_personaje.Z); + Q[3] = new TGCVector2(room.PMax.X - pos_personaje.X, room.PMin.Z - pos_personaje.Z); + for (int t = 0; t < 4; ++t) + { + float x = TGCVector2.Dot(dir_w, Q[t]); + float y = TGCVector2.Dot(dir_v, Q[t]); + Qp[t] = new TGCVector2(ox + x * ex, oy + y * ey); + xm += x * ex; + ym += y * ey; + } + Qp[4] = Qp[0]; + xm /= 4; + ym /= 4; + + if (Math.Abs(xm) < dW / 2 - 10 && Math.Abs(ym) < dH / 2 - 10) + gui.DrawPoly(Qp, 5, 1, Color.Tomato); + } + + // posicion X,Z + float kx = pos_personaje.X * ex; + P[0] = new TGCVector2(10, H - 10); + P[1] = new TGCVector2(15, H - 30); + P[2] = new TGCVector2(5 + kx, H - 30); + P[3] = new TGCVector2(25 + kx, H - 10); + P[4] = P[0]; + gui.DrawSolidPoly(P, 5, Color.Tomato); + gui.DrawPoly(P, 5, 2, Color.HotPink); + + float kz = pos_personaje.Z * ey; + P[0] = new TGCVector2(10, H - 40); + P[1] = new TGCVector2(15, H - 60); + P[2] = new TGCVector2(5 + kz, H - 60); + P[3] = new TGCVector2(25 + kz, H - 40); + P[4] = P[0]; + gui.DrawSolidPoly(P, 5, Color.Green); + gui.DrawPoly(P, 5, 2, Color.YellowGreen); + + device.RenderState.ZBufferEnable = true; + gui.Render(); + } + + public override void Dispose() + { + scene.disposeAll(); + effect.Dispose(); + g_pBaseTexture.Dispose(); + g_pHeightmap.Dispose(); + g_pBaseTexture2.Dispose(); + g_pHeightmap2.Dispose(); + g_pBaseTexture3.Dispose(); + g_pHeightmap3.Dispose(); + g_pBaseTexture4.Dispose(); + g_pHeightmap4.Dispose(); + gui.Dispose(); + foreach (TgcSkeletalMesh m in enemigos) + { + m.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/DepthOfField.cs b/TGC.Examples/WorkshopShaders/DepthOfField.cs new file mode 100644 index 00000000..b0458fa7 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/DepthOfField.cs @@ -0,0 +1,184 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Drawing; +using System.Windows.Forms; +using TGC.Core; +using TGC.Core.Direct3D; +using TGC.Core.Mathematica; +using TGC.Core.SceneLoader; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Camara; +using TGC.Examples.Example; + +namespace Examples.WorkshopShaders +{ + public class DepthOfField : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + private TgcMesh mesh; + private Effect effect; + private Surface g_pDepthStencil; // Depth-stencil buffer + private Texture g_pRenderTarget, g_pBlurFactor; + private VertexBuffer g_pVBV3D; + + public DepthOfField(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-DepthOfField"; + Description = "Depth of Field Sample"; + } + + public override void Init() + { + Device d3dDevice = D3DDevice.Instance.Device; + MyMediaDir = MediaDir + "WorkshopShaders\\"; + MyShaderDir = ShadersDir + "WorkshopShaders\\"; + + //Cargamos un escenario + + TgcSceneLoader loader = new TgcSceneLoader(); + TgcScene scene = loader.loadSceneFromFile(MediaDir + "\\MeshCreator\\Meshes\\Esqueletos\\EsqueletoHumano3\\Esqueleto3-TgcScene.xml"); + mesh = scene.Meshes[0]; + + //Cargar Shader personalizado + string compilationErrors; + effect = Effect.FromFile(d3dDevice, ShadersDir + "WorkshopShaders\\GaussianBlur.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors); + if (effect == null) + { + throw new Exception("Error al cargar shader. Errores: " + compilationErrors); + } + //Configurar Technique dentro del shader + effect.Technique = "DefaultTechnique"; + + //Camara en primera persona + Camara = new TgcFpsCamera(Input); + Camara.SetCamera(new TGCVector3(50, 30, 50), new TGCVector3(0,10, -50)); + + g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true); + + // inicializo el render target + g_pRenderTarget = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); + effect.SetValue("g_RenderTarget", g_pRenderTarget); + + // Blur Factor + g_pBlurFactor = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); + effect.SetValue("g_BlurFactor", g_pBlurFactor); + + // Resolucion de pantalla + effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth); + effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight); + + CustomVertex.PositionTextured[] vertices = new CustomVertex.PositionTextured[] + { + new CustomVertex.PositionTextured( -1, 1, 1, 0,0), + new CustomVertex.PositionTextured(1, 1, 1, 1,0), + new CustomVertex.PositionTextured(-1, -1, 1, 0,1), + new CustomVertex.PositionTextured(1,-1, 1, 1,1) + }; + //vertex buffer de los triangulos + g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); + g_pVBV3D.SetData(vertices, 0, LockFlags.None); + + Modifiers.addBoolean("activar_efecto", "Activar efecto", true); + Modifiers.addFloat("focus_plane", 1, 300, 10); + Modifiers.addFloat("blur_factor", 0.1f, 5f, 0.5f); + } + + public override void Update() + { + PreUpdate(); + } + + public override void Render() + { + var d3dDevice = D3DDevice.Instance.Device; + + bool activar_efecto = (bool)Modifiers["activar_efecto"]; + effect.SetValue("zfoco", (float)Modifiers["focus_plane"]); + effect.SetValue("blur_k", (float)Modifiers["blur_factor"]); + + // dibujo la escena una textura + // guardo el Render target anterior y seteo la textura como render target + Surface pOldRT = d3dDevice.GetRenderTarget(0); + Surface pSurf = g_pRenderTarget.GetSurfaceLevel(0); + if (activar_efecto) + d3dDevice.SetRenderTarget(0, pSurf); + // hago lo mismo con el depthbuffer, necesito el que no tiene multisampling + Surface pOldDS = d3dDevice.DepthStencilSurface; + // Probar de comentar esta linea, para ver como se produce el fallo en el ztest + // por no soportar usualmente el multisampling en el render to texture. + if (activar_efecto) + d3dDevice.DepthStencilSurface = g_pDepthStencil; + + d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + d3dDevice.BeginScene(); + renderScene("DefaultTechnique"); + d3dDevice.EndScene(); + pSurf.Dispose(); + + if (activar_efecto) + { + // Genero el depth map + Surface pSurf2 = g_pBlurFactor.GetSurfaceLevel(0); + d3dDevice.SetRenderTarget(0, pSurf2); + d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + d3dDevice.BeginScene(); + renderScene("RenderBlurFactor"); + d3dDevice.EndScene(); + pSurf2.Dispose(); + + // restuaro el render target y el stencil + d3dDevice.DepthStencilSurface = pOldDS; + d3dDevice.SetRenderTarget(0, pOldRT); + + // dibujo el quad pp dicho : + d3dDevice.BeginScene(); + effect.Technique = "DepthOfField"; + d3dDevice.VertexFormat = CustomVertex.PositionTextured.Format; + d3dDevice.SetStreamSource(0, g_pVBV3D, 0); + effect.SetValue("g_RenderTarget", g_pRenderTarget); + effect.SetValue("g_BlurFactor", g_pBlurFactor); + + d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + effect.Begin(FX.None); + effect.BeginPass(0); + d3dDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + d3dDevice.EndScene(); + } + + RenderAxis(); + RenderFPS(); + D3DDevice.Instance.Device.Present(); + } + + public void renderScene(string technique) + { + // seteo la tecnica en el efecto + effect.Technique = technique; + mesh.Effect = effect; + mesh.Technique = technique; + for (int j = 0; j < 5; ++j) + { + for (int i = 0; i < 15; ++i) + { + mesh.Position = new TGCVector3(j * 20, 0, i * 50); + mesh.Render(); + } + } + } + + public override void Dispose() + { + mesh.Dispose(); + effect.Dispose(); + g_pRenderTarget.Dispose(); + g_pBlurFactor.Dispose(); + g_pVBV3D.Dispose(); + g_pDepthStencil.Dispose(); + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/Distorsiones.cs b/TGC.Examples/WorkshopShaders/Distorsiones.cs new file mode 100644 index 00000000..f1cf7426 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/Distorsiones.cs @@ -0,0 +1,197 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Collections.Generic; +using System.Drawing; +using TGC.Core.Direct3D; +using TGC.Core.Mathematica; +using TGC.Core.SceneLoader; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Camara; +using TGC.Examples.Example; + +namespace Examples.WorkshopShaders +{ + public class Distorsiones : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + private List meshes; + private Effect effect; + private Surface g_pDepthStencil; // Depth-stencil buffer + private Texture g_pRenderTarget; + private VertexBuffer g_pVBV3D; + public float time; + + public enum Distorciones : int + { + Nada = 0, + FishEye = 1, + Pincushion = 2, + Barrel = 3, + OculusRift = 4, + } + + public Distorsiones(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-Distorsionador"; + Description = "Distorsionadores"; + } + + public override void Init() + { + time = 0; + + Device d3dDevice = D3DDevice.Instance.Device; + MyMediaDir = MediaDir + "WorkshopShaders\\"; + MyShaderDir = ShadersDir + "WorkshopShaders\\"; + + //Cargamos un escenario + TgcSceneLoader loader = new TgcSceneLoader(); + TgcScene scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Scenes\\Deposito\\Deposito-TgcScene.xml"); + meshes = scene.Meshes; + + //Cargar Shader personalizado + string compilationErrors; + effect = Effect.FromFile(d3dDevice, ShadersDir + "WorkshopShaders\\FullQuad.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors); + if (effect == null) + { + throw new Exception("Error al cargar shader. Errores: " + compilationErrors); + } + //Configurar Technique dentro del shader + effect.Technique = "DefaultTechnique"; + + //Camara en primera personas + Camara = new TgcFpsCamera(Input); + Camara.SetCamera(new TGCVector3(-182.3816f, 82.3252f, -811.9061f), new TGCVector3(-182.0957f, 82.3147f, -810.9479f)); + + g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true); + + // inicializo el render target + g_pRenderTarget = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); + + effect.SetValue("g_RenderTarget", g_pRenderTarget); + + // Resolucion de pantalla + effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth); + effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight); + + CustomVertex.PositionTextured[] vertices = new CustomVertex.PositionTextured[] + { + new CustomVertex.PositionTextured( -1, 1, 1, 0,0), + new CustomVertex.PositionTextured(1, 1, 1, 1,0), + new CustomVertex.PositionTextured(-1, -1, 1, 0,1), + new CustomVertex.PositionTextured(1,-1, 1, 1,1) + }; + //vertex buffer de los triangulos + g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); + g_pVBV3D.SetData(vertices, 0, LockFlags.None); + + Modifiers.addEnum("distorcionador", typeof(Distorciones), Distorciones.Pincushion); + Modifiers.addBoolean("grid", "mostrar grilla", false); + Modifiers.addFloat("Ku", 0, 1, 0.1f); + Modifiers.addFloat("Kv", 0, 1, 0.1f); + + Modifiers.addFloat("oc_scale_in", 0.1f, 4, 2.5f); + Modifiers.addFloat("oc_scale", 0.01f, 1f, 0.35f); + } + + public override void Update() + { + PreUpdate(); + } + + public override void Render() + { + Device d3dDevice = D3DDevice.Instance.Device; + + time += ElapsedTime; + //Cargar variables de shader + + // dibujo la escena una textura + effect.Technique = "DefaultTechnique"; + // guardo el Render target anterior y seteo la textura como render target + Surface pOldRT = d3dDevice.GetRenderTarget(0); + Surface pSurf = g_pRenderTarget.GetSurfaceLevel(0); + d3dDevice.SetRenderTarget(0, pSurf); + // hago lo mismo con el depthbuffer, necesito el que no tiene multisampling + Surface pOldDS = d3dDevice.DepthStencilSurface; + // Probar de comentar esta linea, para ver como se produce el fallo en el ztest + // por no soportar usualmente el multisampling en el render to texture. + d3dDevice.DepthStencilSurface = g_pDepthStencil; + d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + d3dDevice.BeginScene(); + + //Dibujamos todos los meshes del escenario + foreach (TgcMesh m in meshes) + { + m.Render(); + } + d3dDevice.EndScene(); + pSurf.Dispose(); + + int distorcionador = (int)Modifiers["distorcionador"]; + // restuaro el render target y el stencil + d3dDevice.DepthStencilSurface = pOldDS; + d3dDevice.SetRenderTarget(0, pOldRT); + + // dibujo el quad pp dicho : + d3dDevice.BeginScene(); + + switch (distorcionador) + { + case 1: + effect.Technique = "OjoPez"; + break; + + case 2: + effect.Technique = "Pincusion"; + break; + + case 3: + effect.Technique = "Barrel"; + break; + + case 4: + effect.Technique = "OculusRift"; + break; + + default: + effect.Technique = "ScreenCopy"; + break; + } + effect.SetValue("time", time); + effect.SetValue("fish_kU", (float)Modifiers["Ku"]); + effect.SetValue("fish_kV", (float)Modifiers["Kv"]); + effect.SetValue("grid", (bool)Modifiers["grid"]); + effect.SetValue("ScaleIn", (float)Modifiers["oc_scale_in"]); + effect.SetValue("Scale", (float)Modifiers["oc_scale"]); + + d3dDevice.VertexFormat = CustomVertex.PositionTextured.Format; + d3dDevice.SetStreamSource(0, g_pVBV3D, 0); + effect.SetValue("g_RenderTarget", g_pRenderTarget); + + d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + effect.Begin(FX.None); + effect.BeginPass(0); + d3dDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + + PostRender(); + } + + public override void Dispose() + { + foreach (TgcMesh m in meshes) + { + m.Dispose(); + } + effect.Dispose(); + g_pRenderTarget.Dispose(); + g_pVBV3D.Dispose(); + g_pDepthStencil.Dispose(); + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/GPUAttack.cs b/TGC.Examples/WorkshopShaders/GPUAttack.cs new file mode 100644 index 00000000..3e1d2303 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/GPUAttack.cs @@ -0,0 +1,306 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Drawing; +using System.Windows.Forms; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Example; + +namespace Examples.Shaders +{ + public class EjemploGPUAttack : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + private Effect effect; + private Texture g_pRenderTarget, g_pTempData; + private Surface g_pDepthStencil; // Depth-stencil buffer + private VertexBuffer g_pVB; + private static int MAX_DS = 512; + public int a = 33; + public int c = 213; + public int m = 251; + public int[] hash = new int[4]; + public bool found = false; + + public EjemploGPUAttack(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) + : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-GPUAttack"; + Description = "GPUAttack"; + } + + public unsafe override void Init() + { + Device d3dDevice = GuiController.Instance.D3dDevice; + GuiController.Instance.CustomRenderEnabled = true; + + MyMediaDir = MediaDir + "\\WorkshopShaders\\"; + MyShaderDir = ShadersDir + "\\WorkshopShaders\\"; + + //Cargar Shader + string compilationErrors; + effect = Effect.FromFile(d3dDevice, MyShaderDir + "GPUAttack.fx", null, null, ShaderFlags.None, null, out compilationErrors); + if (effect == null) + { + throw new Exception("Error al cargar shader. Errores: " + compilationErrors); + } + + // inicializo el render target + g_pRenderTarget = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default); + effect.SetValue("g_RenderTarget", g_pRenderTarget); + // temporaria para recuperar los valores + g_pTempData = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, 0, Format.A8R8G8B8, Pool.SystemMemory); + // stencil + g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(MAX_DS, MAX_DS, DepthFormat.D24S8, MultiSampleType.None, 0, true); + + //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[] + { + 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_pVB = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); + g_pVB.SetData(vertices, 0, LockFlags.None); + + string input = InputBox("Ingrese la Clave de 4 letras (A..Z)", "Clave", "CASA"); + + int[] clave = new int[4]; + for (int i = 0; i < 4; ++i) + clave[i] = input[i]; + Hash(clave, hash); + effect.SetValue("hash_buscado", hash); + + char[] buffer = new char[5]; + buffer[0] = (char)hash[0]; + buffer[1] = (char)hash[1]; + buffer[2] = (char)hash[2]; + buffer[3] = (char)hash[3]; + buffer[4] = (char)0; + string msg = new string(buffer); + msg = "El hash es " + msg + "\n"; + MessageBox.Show(msg); + } + + public override void Update() + { + PreUpdate(); + } + + public unsafe override void Render() + { + if (found) + return; + + Device device = GuiController.Instance.D3dDevice; + + Surface pOldRT = device.GetRenderTarget(0); + Surface pSurf = g_pRenderTarget.GetSurfaceLevel(0); + device.SetRenderTarget(0, pSurf); + Surface pOldDS = device.DepthStencilSurface; + device.DepthStencilSurface = g_pDepthStencil; + + device.RenderState.ZBufferEnable = false; + device.Clear(ClearFlags.Target, Color.Black, 1.0f, 0); + device.BeginScene(); + effect.Technique = "ComputeHash"; + device.VertexFormat = CustomVertex.PositionTextured.Format; + device.SetStreamSource(0, g_pVB, 0); + effect.Begin(FX.None); + effect.BeginPass(0); + device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + device.EndScene(); + device.Present(); + device.SetRenderTarget(0, pOldRT); + device.DepthStencilSurface = pOldDS; + + // leo los datos de la textura + // ---------------------------------------------------------------------- + Surface pDestSurf = g_pTempData.GetSurfaceLevel(0); + device.GetRenderTargetData(pSurf, pDestSurf); + Byte* pData = (Byte*)pDestSurf.LockRectangle(LockFlags.None).InternalData.ToPointer(); + + string msg = ""; + + for (int i = 0; i < MAX_DS; i++) + { + for (int j = 0; j < MAX_DS; j++) + { + Byte A = *pData++; + Byte R = *pData++; + Byte G = *pData++; + Byte B = *pData++; + + if (R == 255 && G == 255 && B == 255) + { + int group_x = j / 32; + int x = j % 32; + int group_y = i / 32; + int y = i % 32; + + int[] clave = new int[4]; + clave[0] = 'A' + group_x; + clave[1] = 'A' + group_y; + clave[2] = 'A' + x; + clave[3] = 'A' + y; + Hash(clave, hash); + char[] buffer = new char[5]; + buffer[0] = (char)clave[0]; + buffer[1] = (char)clave[1]; + buffer[2] = (char)clave[2]; + buffer[3] = (char)clave[3]; + buffer[4] = (char)0; + msg = new string(buffer); + msg = "La clave que elegiste es " + msg + "\n"; + found = true; + } + + /* + int group_x = j / 32; + int x = j % 32; + int group_y = i/ 32; + int y = i % 32; + + int[] clave = new int[4]; + clave[0] = 'A' + group_x; + clave[1] = 'A' + group_y; + clave[2] = 'A' + x; + clave[3] = 'A' + y; + + Hash(clave, hash); + + if (hash[0] != G || hash[1] != R || hash[2] != A || hash[3] != B) + { + int a = 0; + } + */ + } + } + pDestSurf.UnlockRectangle(); + pSurf.Dispose(); + + if (found) + MessageBox.Show(msg); + } + + public void Hash(int[] clave, int[] buffer) + { + // for(int i=0;i<4;++i) + // buffer[i] = (a * clave[i] + c) % m; + + int k = (clave[0] + clave[1] + clave[2] + clave[3]) % 256; + for (int i = 0; i < 4; ++i) + { + k = (a * k + c) % m; + buffer[i] = k; + k += clave[i]; + } + } + + public override void Dispose() + { + effect.Dispose(); + g_pRenderTarget.Dispose(); + g_pDepthStencil.Dispose(); + g_pVB.Dispose(); + g_pTempData.Dispose(); + } + + public static String InputBox(String caption, String prompt, String defaultText) + { + String localInputText = defaultText; + if (InputQuery(caption, prompt, ref localInputText)) + { + return localInputText; + } + else + { + return ""; + } + } + + public static int MulDiv(int a, float b, int c) + { + return (int)((float)a * b / (float)c); + } + + public static Boolean InputQuery(String caption, String prompt, ref String value) + { + Form form; + form = new Form(); + form.AutoScaleMode = AutoScaleMode.Font; + form.Font = SystemFonts.IconTitleFont; + + SizeF dialogUnits; + dialogUnits = form.AutoScaleDimensions; + + form.FormBorderStyle = FormBorderStyle.FixedDialog; + form.MinimizeBox = false; + form.MaximizeBox = false; + form.Text = caption; + + form.ClientSize = new Size( + MulDiv(180, dialogUnits.Width, 4), + MulDiv(63, dialogUnits.Height, 8)); + + form.StartPosition = FormStartPosition.CenterScreen; + + System.Windows.Forms.Label lblPrompt; + lblPrompt = new System.Windows.Forms.Label(); + lblPrompt.Parent = form; + lblPrompt.AutoSize = true; + lblPrompt.Left = MulDiv(8, dialogUnits.Width, 4); + lblPrompt.Top = MulDiv(8, dialogUnits.Height, 8); + lblPrompt.Text = prompt; + + System.Windows.Forms.TextBox edInput; + edInput = new System.Windows.Forms.TextBox(); + edInput.Parent = form; + edInput.Left = lblPrompt.Left; + edInput.Top = MulDiv(19, dialogUnits.Height, 8); + edInput.Width = MulDiv(164, dialogUnits.Width, 4); + edInput.Text = value; + edInput.SelectAll(); + + int buttonTop = MulDiv(41, dialogUnits.Height, 8); + //Command buttons should be 50x14 dlus + //Size buttonSize = ScaleSize(new Size(50, 14), dialogUnits.Width / 4, dialogUnits.Height / 8); + Size buttonSize = new Size(MulDiv(50, dialogUnits.Width, 4), + MulDiv(14, dialogUnits.Height, 8)); + System.Windows.Forms.Button bbOk = new System.Windows.Forms.Button(); + bbOk.Parent = form; + bbOk.Text = "OK"; + bbOk.DialogResult = DialogResult.OK; + form.AcceptButton = bbOk; + bbOk.Location = new Point(MulDiv(38, dialogUnits.Width, 4), buttonTop); + bbOk.Size = buttonSize; + + System.Windows.Forms.Button bbCancel = new System.Windows.Forms.Button(); + bbCancel.Parent = form; + bbCancel.Text = "Cancel"; + bbCancel.DialogResult = DialogResult.Cancel; + form.CancelButton = bbCancel; + bbCancel.Location = new Point(MulDiv(92, dialogUnits.Width, 4), buttonTop); + bbCancel.Size = buttonSize; + + if (form.ShowDialog() == DialogResult.OK) + { + value = edInput.Text; + return true; + } + else + { + return false; + } + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/GPUAttack6.cs b/TGC.Examples/WorkshopShaders/GPUAttack6.cs new file mode 100644 index 00000000..4e43edb1 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/GPUAttack6.cs @@ -0,0 +1,327 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Drawing; +using System.Windows.Forms; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Example; + +namespace Examples.Shaders +{ + public class EjemploGPUAttack6 : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + private Effect effect; + private Texture g_pRenderTarget, g_pTempData; + private Surface g_pDepthStencil; // Depth-stencil buffer + private VertexBuffer g_pVB; + private static int MAX_DS = 1024; + public int a = 33; + public int c = 213; + public int m = 251; + public int[] hash = new int[6]; + public bool found = false; + public int prefix_x = 0; + public int prefix_y = 0; + + public EjemploGPUAttack6(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) + : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-GPUAttack6"; + Description = "GPUAttack6"; + } + + public unsafe override void Init() + { + Device d3dDevice = GuiController.Instance.D3dDevice; + GuiController.Instance.CustomRenderEnabled = true; + + MyMediaDir = MediaDir + "\\WorkshopShaders\\"; + MyShaderDir = ShadersDir + "\\WorkshopShaders\\"; + + //Cargar Shader + string compilationErrors; + effect = Effect.FromFile(d3dDevice, MyShaderDir + "GPUAttack.fx", null, null, ShaderFlags.None, null, out compilationErrors); + if (effect == null) + { + throw new Exception("Error al cargar shader. Errores: " + compilationErrors); + } + + // inicializo el render target + g_pRenderTarget = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default); + effect.SetValue("g_RenderTarget", g_pRenderTarget); + // temporaria para recuperar los valores + g_pTempData = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, 0, Format.A8R8G8B8, Pool.SystemMemory); + // stencil + g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(MAX_DS, MAX_DS, DepthFormat.D24S8, MultiSampleType.None, 0, true); + + //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[] + { + 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_pVB = new VertexBuffer(typeof(CustomVertex.PositionTextured), + 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, + CustomVertex.PositionTextured.Format, Pool.Default); + g_pVB.SetData(vertices, 0, LockFlags.None); + + string input = InputBox("Ingrese la Clave de 6 letras (A..Z)", "Clave", "CHARLY"); + + int[] clave = new int[6]; + for (int i = 0; i < 6; ++i) + clave[i] = input[i]; + Hash(clave, hash); + effect.SetValue("hash_buscado6", hash); + + char[] buffer = new char[7]; + for (int i = 0; i < 6; ++i) + buffer[i] = (char)hash[i]; + buffer[6] = (char)0; + string msg = new string(buffer); + msg = "El hash es " + msg + "\n"; + MessageBox.Show(msg); + } + + public override void Update() + { + PreUpdate(); + } + + public unsafe override void Render() + { + if (found) + return; + + Device device = GuiController.Instance.D3dDevice; + Control panel3d = GuiController.Instance.Panel3d; + + Surface pOldRT = device.GetRenderTarget(0); + Surface pSurf = g_pRenderTarget.GetSurfaceLevel(0); + device.SetRenderTarget(0, pSurf); + Surface pOldDS = device.DepthStencilSurface; + device.DepthStencilSurface = g_pDepthStencil; + + effect.SetValue("prefix_x", prefix_x); + effect.SetValue("prefix_y", prefix_y); + + device.RenderState.ZBufferEnable = false; + device.Clear(ClearFlags.Target, Color.Black, 1.0f, 0); + device.BeginScene(); + effect.Technique = "ComputeHash6"; + device.VertexFormat = CustomVertex.PositionTextured.Format; + device.SetStreamSource(0, g_pVB, 0); + effect.Begin(FX.None); + effect.BeginPass(0); + device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + device.EndScene(); + + device.SetRenderTarget(0, pOldRT); + device.DepthStencilSurface = pOldDS; + + // leo los datos de la textura + // ---------------------------------------------------------------------- + Surface pDestSurf = g_pTempData.GetSurfaceLevel(0); + device.GetRenderTargetData(pSurf, pDestSurf); + Byte* pData = (Byte*)pDestSurf.LockRectangle(LockFlags.None).InternalData.ToPointer(); + + string msg = ""; + + for (int i = 0; i < MAX_DS; i++) + { + for (int j = 0; j < MAX_DS; j++) + { + Byte A = *pData++; + Byte R = *pData++; + Byte G = *pData++; + Byte B = *pData++; + + if (R == 255 && G == 255 && B == 255) + { + int group_x = j / 32; + int x = j % 32; + int group_y = i / 32; + int y = i % 32; + + int[] clave = new int[6]; + clave[0] = 'A' + prefix_x; + clave[1] = 'A' + prefix_y; + clave[2] = 'A' + group_x; + clave[3] = 'A' + group_y; + clave[4] = 'A' + x; + clave[5] = 'A' + y; + Hash(clave, hash); + char[] buffer = new char[7]; + for (int t = 0; t < 6; ++t) + buffer[t] = (char)clave[t]; + buffer[6] = (char)0; + msg = new string(buffer); + msg = "La clave que elegiste es " + msg; + found = true; + i = j = MAX_DS; + } + + /* + + int group_x = j / 32; + int x = j % 32; + int group_y = i/ 32; + int y = i % 32; + + int[] clave = new int[6]; + clave[0] = 'A' + prefix_x; + clave[1] = 'A' + prefix_y; + clave[2] = 'A' + group_x; + clave[3] = 'A' + group_y; + clave[4] = 'A' + x; + clave[5] = 'A' + y; + Hash(clave, hash); + + if (hash[0] != G || hash[1] != R || hash[2] != A || hash[3] != B) + { + int a = 0; + } + */ + } + } + pDestSurf.UnlockRectangle(); + pSurf.Dispose(); + + if (found) + MessageBox.Show(msg); + + char[] saux = new char[3]; + saux[0] = (char)('A' + prefix_x); + saux[1] = (char)('A' + prefix_y); + saux[2] = (char)0; + string s = new string(saux); + s = "Hacking " + s + "AAAA - " + s + "ZZZZ"; + + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + device.BeginScene(); + GuiController.Instance.Text3d.drawText(s, 100, 300, Color.Yellow); + device.EndScene(); + + if (++prefix_x == 32) + { + prefix_x = 0; + ++prefix_y; + } + } + + public void Hash(int[] clave, int[] buffer) + { + int k = (clave[0] + clave[1] + clave[2] + clave[3] + clave[4] + clave[5]) % 256; + for (int i = 0; i < 6; ++i) + { + k = (a * k + c) % m; + buffer[i] = k; + k += clave[i]; + } + } + + public override void Dispose() + { + effect.Dispose(); + g_pRenderTarget.Dispose(); + g_pDepthStencil.Dispose(); + g_pVB.Dispose(); + g_pTempData.Dispose(); + } + + public static String InputBox(String caption, String prompt, String defaultText) + { + String localInputText = defaultText; + if (InputQuery(caption, prompt, ref localInputText)) + { + return localInputText; + } + else + { + return ""; + } + } + + public static int MulDiv(int a, float b, int c) + { + return (int)((float)a * b / (float)c); + } + + public static Boolean InputQuery(String caption, String prompt, ref String value) + { + Form form; + form = new Form(); + form.AutoScaleMode = AutoScaleMode.Font; + form.Font = SystemFonts.IconTitleFont; + + SizeF dialogUnits; + dialogUnits = form.AutoScaleDimensions; + + form.FormBorderStyle = FormBorderStyle.FixedDialog; + form.MinimizeBox = false; + form.MaximizeBox = false; + form.Text = caption; + + form.ClientSize = new Size( + MulDiv(180, dialogUnits.Width, 4), + MulDiv(63, dialogUnits.Height, 8)); + + form.StartPosition = FormStartPosition.CenterScreen; + + System.Windows.Forms.Label lblPrompt; + lblPrompt = new System.Windows.Forms.Label(); + lblPrompt.Parent = form; + lblPrompt.AutoSize = true; + lblPrompt.Left = MulDiv(8, dialogUnits.Width, 4); + lblPrompt.Top = MulDiv(8, dialogUnits.Height, 8); + lblPrompt.Text = prompt; + + System.Windows.Forms.TextBox edInput; + edInput = new System.Windows.Forms.TextBox(); + edInput.Parent = form; + edInput.Left = lblPrompt.Left; + edInput.Top = MulDiv(19, dialogUnits.Height, 8); + edInput.Width = MulDiv(164, dialogUnits.Width, 4); + edInput.Text = value; + edInput.SelectAll(); + + int buttonTop = MulDiv(41, dialogUnits.Height, 8); + Size buttonSize = new Size(MulDiv(50, dialogUnits.Width, 4), MulDiv(14, dialogUnits.Height, 8)); + System.Windows.Forms.Button bbOk = new System.Windows.Forms.Button(); + bbOk.Parent = form; + bbOk.Text = "OK"; + bbOk.DialogResult = DialogResult.OK; + form.AcceptButton = bbOk; + bbOk.Location = new Point(MulDiv(38, dialogUnits.Width, 4), buttonTop); + bbOk.Size = buttonSize; + + System.Windows.Forms.Button bbCancel = new System.Windows.Forms.Button(); + bbCancel.Parent = form; + bbCancel.Text = "Cancel"; + bbCancel.DialogResult = DialogResult.Cancel; + form.CancelButton = bbCancel; + bbCancel.Location = new Point(MulDiv(92, dialogUnits.Width, 4), buttonTop); + bbCancel.Size = buttonSize; + + if (form.ShowDialog() == DialogResult.OK) + { + value = edInput.Text; + return true; + } + else + { + return false; + } + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/GPUCompute.cs b/TGC.Examples/WorkshopShaders/GPUCompute.cs new file mode 100644 index 00000000..0ce3a533 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/GPUCompute.cs @@ -0,0 +1,402 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Drawing; +using TGC.Core.Geometry; +using TGC.Core.Input; +using TGC.Core.Mathematica; +using TGC.Core.SceneLoader; +using TGC.Core.Terrain; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Example; + +namespace Examples.Shaders +{ + public class EjemploGPUCompute : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + private TgcScene scene; + private TgcMesh mesh; + private TgcArrow arrow, arrowN, arrowT; + private Effect effect; + + private Surface g_pDepthStencil; // Depth-stencil buffer + private Texture g_pBaseTexture; + private Texture g_pHeightmap; + private Texture g_pVelocidad; + private Texture g_pVelocidadOut; + private Texture g_pPos; + private Texture g_pPosOut; + + private Texture g_pTempVel, g_pTempPos; + private VertexBuffer g_pVBV3D, g_pVB; + private Surface pSurf; + + private TGCVector3 LookAt, LookFrom; + + // enviroment map + private TgcSimpleTerrain terrain; + + private string currentHeightmap; + private string currentTexture; + private float currentScaleXZ; + private float currentScaleY; + + private float time; + + private float esfera_radio; + private static int MAX_DS = 512; + private float[,] vel_x; + private float[,] vel_z; + private float[,] pos_x; + private float[,] pos_z; + private float[,] pos_y; + + public EjemploGPUCompute(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) + : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-GPUCompute"; + Description = "GPUCompute"; + } + + public unsafe override void Init() + { + Device d3dDevice = GuiController.Instance.D3dDevice; + GuiController.Instance.CustomRenderEnabled = true; + + MyMediaDir = MediaDir + "WorkshopShaders\\"; + MyShaderDir = ShadersDir + "WorkshopShaders\\"; + + time = 0f; + vel_x = new float[MAX_DS, MAX_DS]; + vel_z = new float[MAX_DS, MAX_DS]; + pos_x = new float[MAX_DS, MAX_DS]; + pos_y = new float[MAX_DS, MAX_DS]; + pos_z = new float[MAX_DS, MAX_DS]; + + //Crear loader + TgcSceneLoader loader = new TgcSceneLoader(); + + // ------------------------------------------------------------ + //Path de Heightmap default del terreno y Path de Textura default del terreno + TGCVector3 PosTerrain = new TGCVector3(0, 0, 0); + currentHeightmap = MyMediaDir + "Heighmaps\\" + "Heightmap2.jpg"; + currentScaleXZ = 100f; + currentScaleY = 6f; + currentTexture = MyMediaDir + "Heighmaps\\" + "Heightmap2.JPG"; //+ "grid.JPG"; + terrain = new TgcSimpleTerrain(); + terrain.loadHeightmap(currentHeightmap, currentScaleXZ, currentScaleY, PosTerrain); + terrain.loadTexture(currentTexture); + // tomo el ancho de la textura, ojo tiene que ser cuadrada + float terrain_width = (float)terrain.HeightmapData.GetLength(0); + + // mesh principal + scene = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Sphere\\Sphere-TgcScene.xml"); + Bitmap b = (Bitmap)Bitmap.FromFile(MyMediaDir + "Heighmaps\\grid.jpg"); + g_pBaseTexture = Texture.FromBitmap(d3dDevice, b, Usage.None, Pool.Managed); + b.Dispose(); + mesh = scene.Meshes[0]; + mesh.Scale = new TGCVector3(0.5f, 0.5f, 0.5f); + mesh.Position = new TGCVector3(0f, 0f, 0f); + mesh.AutoTransformEnable = false; + TGCVector3 size = mesh.BoundingBox.calculateSize(); + esfera_radio = Math.Abs(size.Y) / 2; + + //Cargar Shader + string compilationErrors; + effect = Effect.FromFile(d3dDevice, MyShaderDir + "GPUCompute.fx", null, null, ShaderFlags.None, null, out compilationErrors); + if (effect == null) + { + throw new Exception("Error al cargar shader. Errores: " + compilationErrors); + } + //Configurar Technique + effect.Technique = "DefaultTechnique"; + effect.SetValue("map_size", terrain_width); + effect.SetValue("map_desf", 0.5f / terrain_width); + + arrow = new TgcArrow(); + arrow.Thickness = 1f; + arrow.HeadSize = new TGCVector2(2f, 2f); + arrow.BodyColor = Color.Blue; + arrowN = new TgcArrow(); + arrowN.Thickness = 1f; + arrowN.HeadSize = new TGCVector2(2f, 2f); + arrowN.BodyColor = Color.Red; + arrowT = new TgcArrow(); + arrowT.Thickness = 1f; + arrowT.HeadSize = new TGCVector2(2f, 2f); + arrowT.BodyColor = Color.Green; + + GuiController.Instance.RotCamera.CameraCenter = new TGCVector3(0, 0, 0); + GuiController.Instance.RotCamera.CameraDistance = 3200; + GuiController.Instance.RotCamera.RotationSpeed = 2f; + + LookAt = new TGCVector3(0, 0, 0); + LookFrom = new TGCVector3(3200, 3000, 3200); + + float aspectRatio = (float)GuiController.Instance.Panel3d.Width / GuiController.Instance.Panel3d.Height; + GuiController.Instance.CurrentCamera.updateCamera(); + d3dDevice.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, 5f, 40000f); + + // Creo el mapa de velocidad + g_pVelocidad = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default); + g_pVelocidadOut = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default); + // Mapa de Posicion + g_pPos = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default); + g_pPosOut = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default); + + // stencil compatible sin multisampling + g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(MAX_DS, MAX_DS, DepthFormat.D24S8, MultiSampleType.None, 0, true); + + // temporaria para recuperar los valores + g_pTempVel = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, 0, Format.A32B32G32R32F, Pool.SystemMemory); + g_pTempPos = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, 0, Format.A32B32G32R32F, Pool.SystemMemory); + + effect.SetValue("g_pVelocidad", g_pVelocidad); + effect.SetValue("g_pPos", g_pPos); + // Textura del heigmap + g_pHeightmap = TextureLoader.FromFile(d3dDevice, currentHeightmap); + effect.SetValue("height_map", g_pHeightmap); + + // Resolucion de pantalla + effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth); + effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight); + effect.SetValue("currentScaleXZ", currentScaleXZ); + effect.SetValue("currentScaleY", currentScaleY); + + //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[] + { + new CustomVertex.PositionTextured( -1, 1, 1, 0,0), + new CustomVertex.PositionTextured(1, 1, 1, 1,0), + new CustomVertex.PositionTextured(-1, -1, 1, 0,1), + new CustomVertex.PositionTextured(1,-1, 1, 1,1) + }; + //vertex buffer de los triangulos + g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); + g_pVBV3D.SetData(vertices, 0, LockFlags.None); + + g_pVB = new VertexBuffer(typeof(CustomVertex.PositionColored), MAX_DS * MAX_DS, d3dDevice, Usage.Dynamic | Usage.None, CustomVertex.PositionColored.Format, Pool.Default); + + // inicializo el mapa de velocidades + Device device = GuiController.Instance.D3dDevice; + TGCMatrix ant_Proj = device.Transform.Projection; + TGCMatrix ant_World = device.Transform.World; + TGCMatrix ant_View = device.Transform.View; + device.Transform.Projection = TGCMatrix.Identity; + device.Transform.World = TGCMatrix.Identity; + device.Transform.View = TGCMatrix.Identity; + + // rt1 = velocidad + Surface pOldRT = device.GetRenderTarget(0); + Surface pSurf = g_pVelocidad.GetSurfaceLevel(0); + device.SetRenderTarget(0, pSurf); + Surface pOldDS = device.DepthStencilSurface; + device.DepthStencilSurface = g_pDepthStencil; + + // rt2 = posicion + Surface pSurf2 = g_pPos.GetSurfaceLevel(0); + device.SetRenderTarget(1, pSurf2); + + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + device.BeginScene(); + effect.Technique = "ComputeVel"; + device.VertexFormat = CustomVertex.PositionTextured.Format; + device.SetStreamSource(0, g_pVBV3D, 0); + effect.Begin(FX.None); + effect.BeginPass(0); + device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + device.EndScene(); + + effect.SetValue("Kp", esfera_radio * (float)Math.PI / 2); + + // restauro los RT + device.SetRenderTarget(0, pOldRT); + device.SetRenderTarget(1, null); + device.DepthStencilSurface = pOldDS; + // restauro las Transf. + device.Transform.Projection = ant_Proj; + device.Transform.World = ant_World; + device.Transform.View = ant_View; + + Modifiers.addBoolean("dibujar_terreno", "Dibujar Terreno", true); + } + + public override void Update() + { + PreUpdate(); + } + + public unsafe override void Render() + { + Device device = GuiController.Instance.D3dDevice; + + time += ElapsedTime; + TgcD3dInput d3dInput = GuiController.Instance.D3dInput; + //Obtener variacion XY del mouse + if (d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT)) + { + float mouseX = d3dInput.XposRelative; + float mouseY = d3dInput.YposRelative; + float an = mouseX * 0.1f; + + float x = (float)(LookFrom.X * Math.Cos(an) + LookFrom.Z * Math.Sin(an)); + float z = (float)(LookFrom.Z * Math.Cos(an) - LookFrom.X * Math.Sin(an)); + LookFrom.X = x; + LookFrom.Z = z; + LookFrom.Y += mouseY * 150f; + } + + //Determinar distancia de la camara o zoom segun el Mouse Wheel + if (d3dInput.WheelPos != 0) + { + TGCVector3 vdir = LookFrom - LookAt; + vdir.Normalize(); + LookFrom = LookFrom - vdir * (d3dInput.WheelPos * 500); + } + + device.Transform.View = TGCMatrix.LookAtLH(LookFrom, LookAt, new TGCVector3(0, 1, 0)); + + TGCMatrix ant_Proj = device.Transform.Projection; + TGCMatrix ant_World = device.Transform.World; + TGCMatrix ant_View = device.Transform.View; + device.Transform.Projection = TGCMatrix.Identity; + device.Transform.World = TGCMatrix.Identity; + device.Transform.View = TGCMatrix.Identity; + device.SetRenderState(RenderStates.AlphaBlendEnable, false); + + // rt1= velocidad + Surface pOldRT = device.GetRenderTarget(0); + Surface pSurf = g_pVelocidadOut.GetSurfaceLevel(0); + device.SetRenderTarget(0, pSurf); + Surface pOldDS = device.DepthStencilSurface; + device.DepthStencilSurface = g_pDepthStencil; + // rt2 = posicion + Surface pSurf2 = g_pPosOut.GetSurfaceLevel(0); + device.SetRenderTarget(1, pSurf2); + + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + device.BeginScene(); + + effect.SetValue("elapsedTime", ElapsedTime); + effect.Technique = "ComputeVel"; + effect.SetValue("g_pVelocidad", g_pVelocidad); + effect.SetValue("g_pPos", g_pPos); + device.VertexFormat = CustomVertex.PositionTextured.Format; + device.SetStreamSource(0, g_pVBV3D, 0); + effect.Begin(FX.None); + effect.BeginPass(1); + device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + device.EndScene(); + + // leo los datos de la textura de velocidades + // ---------------------------------------------------------------------- + Surface pDestSurf = g_pTempVel.GetSurfaceLevel(0); + device.GetRenderTargetData(pSurf, pDestSurf); + Surface pDestSurf2 = g_pTempPos.GetSurfaceLevel(0); + device.GetRenderTargetData(pSurf2, pDestSurf2); + + float* pDataVel = (float*)pDestSurf.LockRectangle(LockFlags.None).InternalData.ToPointer(); + float* pDataPos = (float*)pDestSurf2.LockRectangle(LockFlags.None).InternalData.ToPointer(); + for (int i = 0; i < MAX_DS; i++) + { + for (int j = 0; j < MAX_DS; j++) + { + vel_x[i, j] = *pDataVel++; + vel_z[i, j] = *pDataVel++; + pDataVel++; // no usado + pDataVel++; // no usado + + pos_x[i, j] = *pDataPos++; + pos_z[i, j] = *pDataPos++; + pos_y[i, j] = *pDataPos++; + pDataPos++; // no usado + } + } + pDestSurf.UnlockRectangle(); + pDestSurf2.UnlockRectangle(); + + pSurf.Dispose(); + pSurf2.Dispose(); + + device.SetRenderTarget(0, pOldRT); + device.SetRenderTarget(1, null); + device.DepthStencilSurface = pOldDS; + + // swap de texturas + Texture aux = g_pVelocidad; + g_pVelocidad = g_pVelocidadOut; + g_pVelocidadOut = aux; + aux = g_pPos; + g_pPos = g_pPosOut; + g_pPosOut = aux; + + // dibujo pp dicho ---------------------------------------------- + device.Transform.Projection = ant_Proj; + device.Transform.World = ant_World; + device.Transform.View = ant_View; + + device.BeginScene(); + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + + //Renderizar terreno + if ((bool)Modifiers["dibujar_terreno"]) + terrain.Render(); + + // dibujo las particulas como point sprites + mesh.Effect = effect; + mesh.Technique = "DefaultTechnique"; + effect.SetValue("texDiffuseMap", g_pBaseTexture); + + CustomVertex.PositionColored[,] vertices = new CustomVertex.PositionColored[MAX_DS, MAX_DS]; + for (int i = 0; i < MAX_DS; i++) + { + for (int j = 0; j < MAX_DS; j++) + { + float x0 = pos_x[i, j]; + float z0 = pos_z[i, j]; + float H = pos_y[i, j]; + vertices[i, j] = new CustomVertex.PositionColored(x0, H + esfera_radio, z0, Color.Blue.ToArgb()); + } + } + g_pVB.SetData(vertices, 0, LockFlags.None); + + device.VertexFormat = CustomVertex.PositionColored.Format; + device.SetStreamSource(0, g_pVB, 0); + device.SetTexture(0, null); + device.SetRenderState(RenderStates.PointSize, 32); + device.SetRenderState(RenderStates.PointScaleEnable, true); + device.SetRenderState(RenderStates.PointSpriteEnable, true); + device.DrawPrimitives(PrimitiveType.PointList, 0, MAX_DS * MAX_DS); + device.EndScene(); + } + + public override void Dispose() + { + mesh.Dispose(); + effect.Dispose(); + terrain.Dispose(); + g_pDepthStencil.Dispose(); + g_pBaseTexture.Dispose(); + g_pVelocidad.Dispose(); + g_pVelocidadOut.Dispose(); + g_pPos.Dispose(); + g_pPosOut.Dispose(); + g_pTempPos.Dispose(); + g_pTempVel.Dispose(); + g_pHeightmap.Dispose(); + scene.disposeAll(); + g_pVB.Dispose(); + g_pVBV3D.Dispose(); + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/GUI.cs b/TGC.Examples/WorkshopShaders/GUI.cs new file mode 100644 index 00000000..ad450546 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/GUI.cs @@ -0,0 +1,1581 @@ +using Microsoft.DirectX; +using Microsoft.DirectX.Direct3D; +using System; +using System.Drawing; +using System.IO; +using TGC.Core.Input; +using TGC.Examples.Camara; + +namespace TgcViewer.Utils.Gui +{ + public enum tipoCursor + { + sin_cursor, + targeting, + over, + progress, + pressed, + gripped + } + + public enum itemState + { + normal, + hover, + pressed, + disabled + } + + public enum MessageType + { + WM_NOTHING, + WM_PRESSING, + WM_COMMAND, + WM_CLOSE, + } + + public enum frameBorder + { + rectangular, + sin_borde, + redondeado, + solapa, + } + + public struct GuiMessage + { + public MessageType message; + public int id; + } + + // Vertex format para dibujar en 2d + public struct VERTEX2D + { + public float x, y, z, rhw; // Posicion + public int color; // Color + }; + + public struct st_dialog + { + public int item_0; + public bool trapezoidal_style; + public bool autohide; + public bool hoover_enabled; + }; + + public struct st_bitmap + { + public Texture texture; + public string fname; + public int Width; + public int Height; + } + + public class DXGui + { + // Defines + public const int MAX_GUI_ITEMS = 100; + + public const int MAX_BITMAPS = 10; + public const int MAX_CURSOR = 10; + public const int MAX_DIALOG = 20; + + // Eventos + public const int EVENT_FIRST_SCROLL = 60000; + + public const int EVENT_SCROLL_LEFT = 60000; + public const int EVENT_SCROLL_RIGHT = 60001; + + // Otras + public float M_PI = (float)Math.PI; + + public float M_PI_2 = (float)Math.PI * 0.5f; + + // Pila de items seleccionados + public const int MAX_ITEMS_SEL = 300; + + public const float MENU_OFFSET = 400; + public const float MENU_OFFSET_SALIDA = 800; + + public GUIItem[] items = new GUIItem[MAX_GUI_ITEMS]; + public int cant_items; + public int item_0; + public int sel; // item seleccionado + public int item_pressed; // item prsionado + + public int foco; // item con foco + public float delay_sel; + public float delay_sel0; + public float delay_press; + public float delay_press0; + public float time; + public float delay_show; + public bool hidden; + public Matrix RTQ; // Matriz de cambio de Rectangle to Quad (Trapezoidal quad) + public float timer_sel; + + // Estilos del dialogo actual + public bool trapezoidal_style; + + public bool autohide; + + // Colores x defecto + public static Color c_fondo = Color.FromArgb(80, 30, 155, 110); // Color de fondo + + public static Color c_font = Color.FromArgb(255, 255, 255); // Color de font item normal + public static Color c_selected = Color.FromArgb(255, 128, 128); // Color de font item seleccionado + public static Color c_selected_frame = Color.FromArgb(128, 192, 255); // Color de borde selected rect + public static Color c_grad_inf_0 = Color.FromArgb(255, 254, 237); // Color gradiente inferior menu item valor hasta + public static Color c_grad_inf_1 = Color.FromArgb(255, 235, 182); // Color gradiente inferior menu item valor desde + public static Color c_grad_sup_0 = Color.FromArgb(255, 231, 162); // Color gradiente superior menu item valor hasta + public static Color c_grad_sup_1 = Color.FromArgb(255, 217, 120); // Color gradiente superior menu item valor desde + public static Color c_buttom_frame = Color.FromArgb(80, 220, 20); // Color recuadro del boton + public static Color c_buttom_selected = Color.FromArgb(184, 224, 248); // Color interior del boton seleccionado + public static Color c_buttom_text = Color.FromArgb(130, 255, 130); // Color texto del boton + public static Color c_buttom_sel_text = Color.FromArgb(255, 220, 220); // Color texto del boton seleccionado + public static Color c_frame_border = Color.FromArgb(130, 255, 130); // Color borde los frames + public static Color c_item_disabled = Color.FromArgb(128, 128, 128); // color texto item deshabilitado + + // Cableados + public int rbt; // radio button transfer + + public Color sel_color; // color seleccionado + + // Escala y origen global de todo el dialogo + public float ex, ey, ox, oy; + + // origen de los items scrolleables + public float sox, soy; + + // pila para dialogos + public st_dialog[] dialog = new st_dialog[MAX_DIALOG]; // pila para guardar el primer item + + public int cant_dialog; + + public Sprite sprite; + public Line line; + public Microsoft.DirectX.Direct3D.Font font; + public Microsoft.DirectX.Direct3D.Font font_small; + public Microsoft.DirectX.Direct3D.Font font_medium; + + // Cursores + public Texture[] cursores = new Texture[MAX_CURSOR]; + + public tipoCursor cursor_der, cursor_izq; + + // Pool de texturas para DrawImage + public st_bitmap[] bitmaps = new st_bitmap[MAX_BITMAPS]; + + public int cant_bitmaps; + + // Transicion entre dialogos + public float delay_initDialog; + + public byte alpha; + + // Posicion del mouse + public float mouse_x; + + public float mouse_y; + + // Posicion anterior + public float mouse_x_ant; + + public float mouse_y_ant; + public float delay_move; + public float delay_move0 = 0.5f; + + // Camara TGC + public TgcFpsCamera camera; + + // Parametros srcoll automatico + public float vel_scroll = 500; // pixeles por segundo + + public float min_sox = -3000; + public float max_sox = 3000; + + public bool hoover_enabled; // indica si esta habilitado que si se queda parado en un lugar sintetize un press + public bool closing; // indica que el dialogo se esta cerrado. + public bool blocked; + + public DXGui() + { + cant_items = 0; + cant_dialog = 0; + trapezoidal_style = true; + autohide = false; + hoover_enabled = true; + alpha = 255; + + // Computo la matrix de cambio rect to quad + float W = GuiController.Instance.Panel3d.Width; + float H = GuiController.Instance.Panel3d.Height; + RTQ = rectToQuad(0, 0, W, H, 0, 0, W - 50, 60, W - 100, H - 50, 0, H); + closing = false; + } + + public void Reset() + { + cant_items = 0; + item_pressed = sel = -1; + time = 0; + item_0 = 0; + ey = ex = 1; + ox = oy = 0; + sox = soy = 0; + mouse_x = mouse_y = -1; + mouse_x_ant = mouse_y_ant = -1; + delay_move = 0; + for (int i = 0; i < MAX_CURSOR; ++i) + cursores[i] = null; + cant_bitmaps = 0; + cursor_izq = tipoCursor.targeting; + cursor_der = tipoCursor.targeting; + alpha = 1; + timer_sel = 0; + closing = false; + } + + public void Dispose() + { + font.Dispose(); + font_small.Dispose(); + font_medium.Dispose(); + sprite.Dispose(); + line.Dispose(); + for (int i = 0; i < MAX_CURSOR; ++i) + if (cursores[i] != null) + cursores[i].Dispose(); + + for (int i = 0; i < cant_bitmaps; ++i) + bitmaps[i].texture.Dispose(); + } + + // interface + public void Create() + { + Reset(); + // Creo el sprite + Device d3dDevice = GuiController.Instance.D3dDevice; + sprite = new Sprite(d3dDevice); + // lines varios + line = new Line(d3dDevice); + // Fonts + font = new Microsoft.DirectX.Direct3D.Font(d3dDevice, 22, 0, FontWeight.Light, 0, false, CharacterSet.Default, + Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "Lucida Console"); + font.PreloadGlyphs('0', '9'); + font.PreloadGlyphs('a', 'z'); + font.PreloadGlyphs('A', 'Z'); + + font_small = new Microsoft.DirectX.Direct3D.Font(d3dDevice, 10, 0, FontWeight.Light, 0, false, CharacterSet.Default, + Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "Lucida Console"); + font_small.PreloadGlyphs('0', '9'); + font_small.PreloadGlyphs('a', 'z'); + font_small.PreloadGlyphs('A', 'Z'); + + font_medium = new Microsoft.DirectX.Direct3D.Font(d3dDevice, 16, 0, FontWeight.Bold, 0, false, CharacterSet.Default, + Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "Lucida Console"); + font_medium.PreloadGlyphs('0', '9'); + font_medium.PreloadGlyphs('a', 'z'); + font_medium.PreloadGlyphs('A', 'Z'); + + // Cargo las textura del cursor + cursores[(int)tipoCursor.targeting] = cargar_textura("cursor_default.png", true); + cursores[(int)tipoCursor.over] = cargar_textura("cursor_over.png", true); + cursores[(int)tipoCursor.gripped] = cargar_textura("cursor_gripper.png", true); + } + + // dialog support + public void InitDialog(bool pautohide = false, bool trapezoidal = true, bool delay = false) + { + // guardo el valor de item_0 en la pila + dialog[cant_dialog].item_0 = item_0; + // y el valor del estilo del dialogo actual + dialog[cant_dialog].trapezoidal_style = trapezoidal_style; + dialog[cant_dialog].autohide = autohide; + dialog[cant_dialog].hoover_enabled = hoover_enabled; + + ++cant_dialog; + // y el primer item del nuevo dialog es cant items + item_0 = cant_items; + // y seteo el nuevo estilo de dialogo + trapezoidal_style = trapezoidal; + autohide = pautohide; + hoover_enabled = true; // X defecto tiene el hoover enabled + foco = -1; + rbt = -1; + sel = -1; + timer_sel = 0; + ox = oy = 0; + Show(); + delay_initDialog = delay ? 1.0f : 0; + closing = false; + } + + public void EndDialog() + { + // actualizo la cantidad de items + cant_items = item_0; + // recupero el valor de item_0 y del estilo del dialogo + --cant_dialog; + item_0 = dialog[cant_dialog].item_0; + trapezoidal_style = dialog[cant_dialog].trapezoidal_style; + autohide = dialog[cant_dialog].autohide; + hoover_enabled = dialog[cant_dialog].hoover_enabled; + // Saco el foco + foco = -1; + // valores x defecto del scroll + ox = oy = 0; + sox = soy = 0; + // Resteo cualquier item seleccionado anterior y timer de seleccion + sel = -1; + timer_sel = 0; + + // el closing puede tardar un huevo, porque usualmente despues de hacer el endialog, se ejecuta + // el comando que se selecciono, y si esa opcion tarda mucho, cuando se repinta el dialogo anterior + // todo el tiempo en iddle que esta almacenado en el elapsedtime, se asimila a la posicion del mouse + // y se puede dar el caso que se presione (hoover) un boton no deseado + // entonces, al cerrar ponemos este flag en true hasta el siguiente frame donde el sistema retome el control + closing = true; + } + + public void Show(bool show = true) + { + hidden = !show; + delay_show = autohide ? 0.5f : 0f; + } + + // Alerts + public void MessageBox(string msg, string titulo = "") + { + InitDialog(false, false); + float W = GuiController.Instance.Panel3d.Width / ex; + float H = GuiController.Instance.Panel3d.Height / ey; + + int dx = (int)(700.0f / ex); + int dy = (int)(450.0f / ey); + int x0 = (int)((W - dx) / 2); + int y0 = (int)((H - dy) / 2); + int r = 170; + + InsertFrame(titulo, x0, y0, dx, dy, Color.FromArgb(64, 32, 64)); + InsertItem(msg, x0 + 50, y0 + 80); + InsertCircleButton(0, "OK", "ok.png", x0 + 70, y0 + dy - r - 90, r); + InsertCircleButton(1, "CANCEL", "cancel.png", x0 + dx - r - 70, y0 + dy - r - 90, r); + } + + // input + public GuiMessage ProcessInput(float elapsed_time) + { + GuiMessage msg = new GuiMessage(); + msg.message = MessageType.WM_NOTHING; + msg.id = -1; + int ant_sel = sel; + + // Hardcodeado escala dinamica + + if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.F2)) + { + ex /= 1.1f; + ey = ex; + } + else + if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.F3)) + { + ex *= 1.1f; + ey = ex; + } + + // tomo la posicion del mouse + float sx = GuiController.Instance.D3dInput.Xpos; + float sy = GuiController.Instance.D3dInput.Ypos; + + // Autohide dialog + if (autohide) + { + if (mouse_x < MENU_OFFSET && hidden) + // El dialogo esta oculto y se mueve con el mouse a posicion izquierda + Show(); + else + if (mouse_x > MENU_OFFSET_SALIDA && !hidden) + // El dialogo esta visible y se mueve con el mouse a posicion derecha + Show(false); + } + + // verifico si el cusor pasa por arriba de un item, si es seleccionable, lo muestro + sel = -1; + int t = item_0; + while (t < cant_items && sel == -1) + { + if (!items[t].disabled && (items[t].seleccionable || items[t].auto_seleccionable)) + { + Point pt = new Point(0, 0); + if (items[t].scrolleable) + { + pt.X = (int)(sx - sox * ex); + pt.Y = (int)(sy - soy * ey); + } + else + { + pt.X = (int)sx; + pt.Y = (int)sy; + } + if (items[t].pt_inside(this, pt)) + sel = t; + } + ++t; + } + + if (ant_sel != sel) + { + // cambio de seleccion + if (ant_sel != -1) + items[ant_sel].state = itemState.normal; + if (sel != -1) + items[sel].state = itemState.hover; + + // inicio el timer de seleccion + delay_sel0 = delay_sel = 0.5f; + + // inicio el timer de quieto + timer_sel = 0; + } + + if (GuiController.Instance.D3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT)) + { + // Presiona el item actual + if (sel != -1) + { + items[sel].state = itemState.pressed; + // y cambio el estado de checked del item + // primero limpio todo porque solo puede haber un item marcado en todo el dialogo + for (int j = item_0; j < cant_items; ++j) + items[j].marcado = false; + // Y ahora marco el item donde hice click + items[sel].marcado = true; + // Esta version no soporta varios Grupos de checkbox (como el group y el tabstop de windows RC) + + // inicio el timer de press + delay_press0 = delay_press = 0.1f; + // Reseteo el timer sel + timer_sel = 0; + // genero el mensaje + msg.message = MessageType.WM_PRESSING; + msg.id = items[sel].item_id; + // guardo el item presionado, por si se mueve del mismo antes que se genere el evento wm_command + item_pressed = sel; + } + } + + // mouse move ? + if (Math.Abs(mouse_x - sx) > 0.5f || Math.Abs(mouse_y - sy) > 0.5f) + { + // Guardo la pos. anterior del mouse + mouse_x_ant = mouse_x; + mouse_y_ant = mouse_y; + // Inicializo el timer de mov. suave del mouse + delay_move = delay_move0; + } + // Actualizo la pos actual + mouse_x = sx; + mouse_y = sy; + return msg; + } + + public GuiMessage Update(float elapsed_time) + { + if (closing) + { + // el dialogo se estaba cerrando, + closing = false; + GuiMessage msg = new GuiMessage(); + msg.message = MessageType.WM_CLOSE; + msg.id = -1; + item_pressed = -1; + return msg; // y termino de procesar por este frame + } + + // Actualizo los timers + time += elapsed_time; + + if (delay_initDialog > 0) + { + delay_initDialog -= elapsed_time; + if (delay_initDialog < 0) + delay_initDialog = 0; + } + + // Si hay un item seleccionado inicio el timer para el press (hoover model) + // Salvo que sea un autoselccionable, en ese caso no hay timer, ya que se presiona constantemente + if (sel != -1 && !items[sel].auto_seleccionable) + timer_sel += elapsed_time; + else + timer_sel = 0; + + if (delay_show > 0) + { + delay_show -= elapsed_time; + if (delay_show < 0) + delay_show = 0; + + if (hidden) + ox = -MENU_OFFSET * (1 - delay_show); + else + ox = -MENU_OFFSET * delay_show; + } + + if (delay_sel > 0) + { + delay_sel -= elapsed_time; + if (delay_sel < 0) + delay_sel = 0; + } + + if (delay_move > 0) + { + delay_move -= elapsed_time; + if (delay_move < 0) + delay_move = 0; + } + + // computo la matriz de transformacion final RTQ + if (trapezoidal_style) + { + float W = GuiController.Instance.Panel3d.Width; + float H = GuiController.Instance.Panel3d.Height; + RTQ = rectToQuad(0, 0, W, H, + 0, 0, W - 50, 60, W - 100, H - 50, 0, H); + } + else + RTQ = Matrix.Identity; + + if (delay_press > 0) + { + delay_press -= elapsed_time; + if (delay_press < 0) + { + // Termino el delay de press + delay_press = 0; + // Si habia algun item presionado, lo libero + if (sel != -1 && items[sel].state == itemState.pressed) + items[sel].state = itemState.normal; + + // Aca es el mejor momento para generar el msg, asi el usuario tiene tiempo de ver la animacion + // de que el boton se esta presionando, antes que se triggere el comando + // genero el mensaje, ojo, uso item_pressed, porque por ahi se movio desde el momento que se genero + // el primer evento de pressing y en ese caso sel!=item_pressed + if (item_pressed != -1) + { + GuiMessage msg = new GuiMessage(); + msg.message = MessageType.WM_COMMAND; + msg.id = items[item_pressed].item_id; + // Y limpio el item pressed, evitando cualquier posibilidad de generar 2 veces el mismo msg + item_pressed = -1; + return msg; // y termino de procesar por este frame + } + } + } + + // Actualizo el timer de los items actuales + for (int i = item_0; i < cant_items; ++i) + items[i].ftime += elapsed_time; + + // Proceso el input y devuelve el resultado + return ProcessInput(elapsed_time); + } + + public void Render() + { + Device d3dDevice = GuiController.Instance.D3dDevice; + if (sprite.Disposed) + return; + + // elimino cualquier textura que me cague el modulate del vertex color + d3dDevice.SetTexture(0, null); + // Desactivo el zbuffer + bool ant_zenable = d3dDevice.RenderState.ZBufferEnable; + d3dDevice.RenderState.ZBufferEnable = false; + + // 1- dibujo los items 2d con una interface de sprites + sprite.Begin(SpriteFlags.AlphaBlend); + Matrix matAnt = sprite.Transform * Matrix.Identity; + Vector2 scale = new Vector2(ex, ey); + Vector2 offset = new Vector2(ox, oy); + sprite.Transform = Matrix.Transformation2D(new Vector2(0, 0), 0, scale, new Vector2(0, 0), 0, offset) * RTQ; + + int item_desde = item_0; + // Transicion entre dialogos + bool hay_tr = false; + if (delay_initDialog > 0 && cant_dialog > 0) + { + // Dibujo los items del dialogo anterior + item_desde = dialog[cant_dialog - 1].item_0; + hay_tr = true; + alpha = (byte)(255 * delay_initDialog); + } + else + alpha = 255; // No hay transicion + + // si hay un item en modo hover postergo su renderizado para lo ultimo de todo + // Esto es porque tiene que verse arriba de los demas items y no hay info de Z + // de momento solo soporta un solo item en modo hover al mismo tiempo + int item_sel = -1; + for (int i = item_desde; i < cant_items; ++i) + { + if (hay_tr && i == item_0) + // Llegue al dialogo actual, actualizo el alpha blend + alpha = (byte)(255 - alpha); + + if (!items[i].item3d) + { + if (items[i].state != itemState.hover || item_sel != -1) + items[i].Render(this); + else + item_sel = i; // Este item lo dibujo al final de todo + } + } + + // Item seleccionado + if (item_sel != -1) + { + sprite.End(); // Termino el anterior + sprite.Begin(SpriteFlags.AlphaBlend); + items[item_sel].Render(this); + } + sprite.End(); + + // 3- dibujo los items 3d a travez de la interface usual del TGC (usando la camara y un viewport) + item_sel = -1; + d3dDevice.RenderState.ZBufferEnable = true; + for (int i = item_0; i < cant_items; ++i) + if (items[i].item3d) + { + if (items[i].state != itemState.hover || item_sel != -1) + items[i].Render(this); + else + item_sel = i; // Este item lo dibujo al final de todo + } + + // Item seleccionado + if (item_sel != -1) + items[item_sel].Render(this); + + // Desactivo el z buffer para los sprites + d3dDevice.RenderState.ZBufferEnable = false; + + // Items con el flag siempre visible (que no pertenecen a este dialogo) + for (int i = 0; i < item_desde; ++i) + if (items[i].siempre_visible) + items[i].Render(this); + + // 4 - dibujo el cusor con la misma interface de prites + sprite.Begin(SpriteFlags.AlphaBlend); + sprite.Transform = Matrix.Transformation2D(new Vector2(0, 0), 0, new Vector2(1, 1), new Vector2(0, 0), 0, new Vector2(0, 0)); + + // mano derecha + float t = delay_move / delay_move0; + Vector3 hand_pos = new Vector3(mouse_x, mouse_y, 0) * (1 - t) + new Vector3(mouse_x_ant, mouse_y_ant, 0) * t; + if (cursores[(int)cursor_der] != null) + { + sprite.Transform = Matrix.Transformation2D(new Vector2(0, 0), 0, new Vector2(1, 1), Vector2.Empty, 0, new Vector2(0, 0)); + sprite.Draw(cursores[(int)cursor_der], Rectangle.Empty, new Vector3(32, 32, 0), hand_pos, Color.FromArgb(255, 255, 255, 255)); + } + sprite.End(); + + // Restauro el zbuffer + d3dDevice.RenderState.ZBufferEnable = ant_zenable; + // Restauro la transformacion del sprite + sprite.Transform = matAnt; + } + + public void TextOut(int x, int y, string text) + { + TextOut(x, y, text, Color.Black); + } + + public void TextOut(int x, int y, string text, Color clr) + { + Device d3dDevice = GuiController.Instance.D3dDevice; + // elimino cualquier textura que me cague el modulate del vertex color + d3dDevice.SetTexture(0, null); + // Desactivo el zbuffer + bool ant_zenable = d3dDevice.RenderState.ZBufferEnable; + d3dDevice.RenderState.ZBufferEnable = false; + // pongo la matriz identidad + Matrix matAnt = sprite.Transform * Matrix.Identity; + sprite.Transform = trapezoidal_style ? RTQ : Matrix.Identity; + + Rectangle rc = new Rectangle(x, y, x + 600, y + 100); + sprite.Begin(SpriteFlags.AlphaBlend); + font.DrawText(sprite, text, rc, DrawTextFormat.NoClip | DrawTextFormat.Top | DrawTextFormat.Left, clr); + sprite.End(); + + // Restauro el zbuffer + d3dDevice.RenderState.ZBufferEnable = ant_zenable; + // Restauro la transformacion del sprite + sprite.Transform = matAnt; + } + + // Interface para agregar items al UI + public GUIItem InsertItem(GUIItem item) + { + // Inserto el gui item + items[cant_items] = item; + // Devuelvo el item pp dicho agregado a la lista + return items[cant_items++]; + } + + // Inserta un item generico + public GUIItem InsertItem(String s, int x, int y, int dx = 0, int dy = 0) + { + // Static text = item generico + return InsertItem(new GUIItem(this, s, x, y, dx, dy)); + } + + // Inserta un item imagen estatica + public GUIItem InsertImage(String image, int x, int y) + { + // Agrego un item generico + GUIItem item = InsertItem(new GUIItem(this, "", x, y)); + + // Cargo el bitmap + item.cargar_textura(image); + + return item; + } + + // Pop up menu item + public gui_menu_item InsertMenuItem(int id, String s, String imagen, int x, int y, int dx = 0, int dy = 0, bool penabled = true) + { + return (gui_menu_item)InsertItem(new gui_menu_item(this, s, imagen, id, x, y, dx, dy, penabled)); + } + + // Standard push button + public gui_button InsertButton(int id, String s, int x, int y, int dx, int dy) + { + return (gui_button)InsertItem(new gui_button(this, s, id, x, y, dx, dy)); + } + + // button + public gui_circle_button InsertCircleButton(int id, String s, String imagen, int x, int y, int r) + { + return (gui_circle_button)InsertItem(new gui_circle_button(this, s, imagen, id, x, y, r)); + } + + public gui_tile_button InsertTileButton(int id, String s, String imagen, int x, int y, int dx, int dy, bool scrolleable = true) + { + return (gui_tile_button)InsertItem(new gui_tile_button(this, s, imagen, id, x, y, dx, dy, scrolleable)); + } + + // Dialog Frame + public gui_frame InsertFrame(String s, int x, int y, int dx, int dy, Color c_fondo, frameBorder borde = frameBorder.rectangular) + { + return (gui_frame)InsertItem(new gui_frame(this, s, x, y, dx, dy, c_fondo, borde)); + } + + public gui_iframe InsertIFrame(String s, int x, int y, int dx, int dy, Color c_fondo) + { + return (gui_iframe)InsertItem(new gui_iframe(this, s, x, y, dx, dy, c_fondo)); + } + + // Progress bar + public gui_progress_bar InsertProgressBar(int id, int x, int y, int dx, int dy) + { + return (gui_progress_bar)InsertItem(new gui_progress_bar(this, x, y, dx, dy, id)); + } + + // color + public gui_color InsertItemColor(int x, int y, Color color, int id) + { + gui_color pitem = (gui_color)InsertItem(new gui_color(this, "", id, x, y)); + pitem.c_fondo = color; + return pitem; + } + + public int GetDlgItemCtrl(int id) + { + int rta = -1; + int i = item_0; + while (i < cant_items && rta == -1) + if (items[i].item_id == id) + rta = i; + else + ++i; + return rta; + } + + public GUIItem GetDlgItem(int id) + { + int rta = -1; + int i = item_0; + while (i < cant_items && rta == -1) + if (items[i].item_id == id) + rta = i; + else + ++i; + + return rta != -1 ? items[rta] : null; + } + + public void EnableItem(int id, bool enable = true) + { + int nro_item = GetDlgItemCtrl(id); + if (nro_item != -1) + items[nro_item].disabled = !enable; + } + + // line support + public void Transform(VERTEX2D[] pt, int cant_ptos) + { + for (int i = 0; i < cant_ptos; ++i) + { + float x = ox + pt[i].x * ex; + float y = oy + pt[i].y * ey; + + if (trapezoidal_style) + { + pt[i].x = x * RTQ.M11 + y * RTQ.M21 + RTQ.M41; + pt[i].y = x * RTQ.M12 + y * RTQ.M22 + RTQ.M42; + float W = x * RTQ.M14 + y * RTQ.M24 + RTQ.M44; + + pt[i].x /= W; + pt[i].y /= W; + } + else + { + pt[i].x = x; + pt[i].y = y; + } + } + } + + public void Transform(Vector2[] pt, int cant_ptos) + { + for (int i = 0; i < cant_ptos; ++i) + { + float x = ox + pt[i].X * ex; + float y = oy + pt[i].Y * ey; + + if (trapezoidal_style) + { + pt[i].X = x * RTQ.M11 + y * RTQ.M21 + RTQ.M41; + pt[i].Y = x * RTQ.M12 + y * RTQ.M22 + RTQ.M42; + float W = x * RTQ.M14 + y * RTQ.M24 + RTQ.M44; + + pt[i].X /= W; + pt[i].Y /= W; + } + else + { + pt[i].X = x; + pt[i].Y = y; + } + } + } + + public void DrawLine(float x0, float y0, float x1, float y1, int dw, Color color) + { + Vector2[] V = new Vector2[4]; + V[0].X = x0; + V[0].Y = y0; + V[1].X = x1; + V[1].Y = y1; + + if (dw < 1) + dw = 1; + + // direccion normnal + Vector2 v = V[1] - V[0]; + v.Normalize(); + Vector2 n = new Vector2(-v.Y, v.X); + + V[2] = V[1] + n * dw; + V[3] = V[0] + n * dw; + + VERTEX2D[] pt = new VERTEX2D[16]; + // 1er triangulo + pt[0].x = V[0].X; + pt[0].y = V[0].Y; + pt[1].x = V[1].X; + pt[1].y = V[1].Y; + pt[2].x = V[2].X; + pt[2].y = V[2].Y; + + // segundo triangulo + pt[3].x = V[0].X; + pt[3].y = V[0].Y; + pt[4].x = V[2].X; + pt[4].y = V[2].Y; + pt[5].x = V[3].X; + pt[5].y = V[3].Y; + + for (int t = 0; t < 6; ++t) + { + pt[t].z = 0.5f; + pt[t].rhw = 1; + pt[t].color = color.ToArgb(); + ++t; + } + + Transform(pt, 6); + + // dibujo como lista de triangulos + Device d3dDevice = GuiController.Instance.D3dDevice; + d3dDevice.VertexFormat = VertexFormats.Transformed | VertexFormats.Diffuse; + d3dDevice.DrawUserPrimitives(PrimitiveType.TriangleList, 2, pt); + } + + public void DrawPoly(Vector2[] V, int cant_ptos, int dw, Color color) + { + if (dw < 1) + dw = 1; + // Elimino ptos repetidos + Vector2[] P = new Vector2[1000]; + int cant = 1; + P[0] = V[0]; + for (int i = 1; i < cant_ptos; ++i) + if ((V[i] - V[i - 1]).Length() > 0.01) + P[cant++] = V[i]; + + cant_ptos = cant; + bool closed = (P[0] - P[cant_ptos - 1]).Length() < 0.1; + + // calculo el offset + Vector2[] Q = new Vector2[1000]; + Vector2[] N = new Vector2[1000]; + for (int i = 0; i < cant_ptos - 1; ++i) + { + Vector2 p0 = P[i]; + Vector2 p1 = P[i + 1]; + Vector2 v = p1 - p0; + v.Normalize(); + // N = V.normal() + N[i].X = -v.Y; + N[i].Y = v.X; + } + + // ptos intermedios + int i0 = closed ? 0 : 1; + for (int i = i0; i < cant_ptos; ++i) + { + int ia = i != 0 ? i - 1 : cant_ptos - 2; + Vector2 n = N[ia] + N[i]; + n.Normalize(); + float r = Vector2.Dot(N[ia], n); + if (r != 0) + Q[i] = P[i] + n * ((float)dw / r); + else + Q[i] = P[i]; + } + + if (!closed) + { + // poligono abierto: primer y ultimo punto: + Q[0] = P[0] + N[0] * dw; + Q[cant_ptos - 1] = P[cant_ptos - 1] + N[cant_ptos - 2] * dw; + } + else + Q[cant_ptos - 1] = Q[0]; + + VERTEX2D[] pt = new VERTEX2D[4000]; + int t = 0; + for (int i = 0; i < cant_ptos - 1; ++i) + { + // 1er triangulo + pt[t].x = P[i].X; + pt[t].y = P[i].Y; + pt[t + 1].x = Q[i].X; + pt[t + 1].y = Q[i].Y; + pt[t + 2].x = P[i + 1].X; + pt[t + 2].y = P[i + 1].Y; + + // segundo triangulo + pt[t + 3].x = Q[i].X; + pt[t + 3].y = Q[i].Y; + pt[t + 4].x = P[i + 1].X; + pt[t + 4].y = P[i + 1].Y; + pt[t + 5].x = Q[i + 1].X; + pt[t + 5].y = Q[i + 1].Y; + + for (int j = 0; j < 6; ++j) + { + pt[t].z = 0.5f; + pt[t].rhw = 1; + pt[t].color = color.ToArgb(); + ++t; + } + } + + Transform(pt, t); + + // dibujo como lista de triangulos + Device d3dDevice = GuiController.Instance.D3dDevice; + d3dDevice.VertexFormat = VertexFormats.Transformed | VertexFormats.Diffuse; + d3dDevice.DrawUserPrimitives(PrimitiveType.TriangleList, 2 * (cant_ptos - 1), pt); + } + + public void DrawSolidPoly(Vector2[] P, int cant_ptos, Color color, bool gradiente = true) + { + // calculo el centro de gravedad + float xc = 0; + float yc = 0; + float ymin = 100000; + float ymax = -100000; + + for (int i = 0; i < cant_ptos - 1; ++i) + { + xc += P[i].X; + yc += P[i].Y; + + if (P[i].Y > ymax) + ymax = P[i].Y; + if (P[i].Y < ymin) + ymin = P[i].Y; + } + + xc /= (float)(cant_ptos - 1); + yc /= (float)(cant_ptos - 1); + + float dy = Math.Max(1, ymax - ymin); + + byte a = color.A; + byte r = color.R; + byte g = color.G; + byte b = color.B; + + VERTEX2D[] pt = new VERTEX2D[4000]; + pt[0].x = xc; + pt[0].y = yc; + for (int i = 0; i < cant_ptos; ++i) + { + pt[i + 1].x = P[i].X; + pt[i + 1].y = P[i].Y; + } + + for (int i = 0; i < cant_ptos + 1; ++i) + { + pt[i].z = 0.5f; + pt[i].rhw = 1; + if (gradiente) + { + double k = 1 - (pt[i].y - ymin) / dy * 0.5; + pt[i].color = Color.FromArgb(a, (byte)Math.Min(255, r * k), (byte)Math.Min(255, g * k), (byte)Math.Min(255, b * k)).ToArgb(); + } + else + pt[i].color = color.ToArgb(); + } + + Transform(pt, cant_ptos + 1); + + Device d3dDevice = GuiController.Instance.D3dDevice; + d3dDevice.VertexFormat = VertexFormats.Transformed | VertexFormats.Diffuse; + d3dDevice.DrawUserPrimitives(PrimitiveType.TriangleFan, cant_ptos - 1, pt); + } + + public void DrawGradientPoly(Vector2[] P, int cant_ptos, Color color1, Color color2) + { + // calculo el centro de gravedad + float xc = 0; + float yc = 0; + float ymin = 100000; + float ymax = -100000; + float xmin = 100000; + float xmax = -100000; + + for (int i = 0; i < cant_ptos - 1; ++i) + { + xc += P[i].X; + yc += P[i].Y; + + if (P[i].Y > ymax) + ymax = P[i].Y; + if (P[i].Y < ymin) + ymin = P[i].Y; + if (P[i].X > xmax) + xmax = P[i].X; + if (P[i].X < xmin) + xmin = P[i].X; + } + + xc /= (float)(cant_ptos - 1); + yc /= (float)(cant_ptos - 1); + + float dy = Math.Max(1, ymax - ymin); + float dx = Math.Max(1, xmax - xmin); + + byte a = color1.A; + // Color desde + byte r1 = color1.R; + byte g1 = color1.G; + byte b1 = color1.B; + // color hasta + byte r2 = color2.R; + byte g2 = color2.G; + byte b2 = color2.B; + + VERTEX2D[] pt = new VERTEX2D[4000]; + pt[0].x = xc; + pt[0].y = yc; + for (int i = 0; i < cant_ptos; ++i) + { + pt[i + 1].x = P[i].X; + pt[i + 1].y = P[i].Y; + } + + for (int i = 0; i < cant_ptos + 1; ++i) + { + pt[i].z = 0.5f; + pt[i].rhw = 1; + // Gradiente horizontal + float k = (pt[i].x - xmin) / dx; // k = 0..1 + float r = r1 * (1 - k) + r2 * k; + float g = g1 * (1 - k) + g2 * k; + float b = b1 * (1 - k) + b2 * k; + pt[i].color = Color.FromArgb(a, (byte)Math.Min(255, r), + (byte)Math.Min(255, g), + (byte)Math.Min(255, b)).ToArgb(); + } + + Transform(pt, cant_ptos + 1); + + Device d3dDevice = GuiController.Instance.D3dDevice; + d3dDevice.VertexFormat = VertexFormats.Transformed | VertexFormats.Diffuse; + d3dDevice.DrawUserPrimitives(PrimitiveType.TriangleFan, cant_ptos - 1, pt); + } + + public void RoundRect(int x0, int y0, int x1, int y1, int r, int dw, Color color, bool solid = false) + { + if (dw < 1) + dw = 1; + Vector2[] pt = new Vector2[1000]; + + float da = M_PI / 8.0f; + float alfa; + + x0 += r; + y0 += r; + x1 -= r; + y1 -= r; + + int t = 0; + float x = x0; + float y = y0; + for (alfa = 0; alfa < M_PI_2; alfa += da) + { + pt[t].X = x - r * (float)Math.Cos(alfa); + pt[t].Y = y - r * (float)Math.Sin(alfa); + ++t; + } + pt[t].X = x; + pt[t].Y = y - r; + ++t; + + x = x1; + y = y0; + for (alfa = M_PI_2; alfa < M_PI; alfa += da) + { + pt[t].X = x - r * (float)Math.Cos(alfa); + pt[t].Y = y - r * (float)Math.Sin(alfa); + ++t; + } + pt[t].X = x + r; + pt[t].Y = y; + ++t; + + x = x1; + y = y1; + for (alfa = 0; alfa < M_PI_2; alfa += da) + { + pt[t].X = x + r * (float)Math.Cos(alfa); + pt[t].Y = y + r * (float)Math.Sin(alfa); + ++t; + } + pt[t].X = x; + pt[t].Y = y + r; + ++t; + + x = x0; + y = y1; + for (alfa = M_PI_2; alfa < M_PI; alfa += da) + { + pt[t].X = x + r * (float)Math.Cos(alfa); + pt[t].Y = y + r * (float)Math.Sin(alfa); + ++t; + } + pt[t++] = pt[0]; + + if (solid) + DrawSolidPoly(pt, t, color, false); + else + DrawPoly(pt, t, dw, color); + } + + public void DrawRect(int x0, int y0, int x1, int y1, int dw, Color color, bool solid = false) + { + if (dw < 1) + dw = 1; + Vector2[] pt = new Vector2[5]; + + pt[0].X = x0; + pt[0].Y = y0; + pt[1].X = x1; + pt[1].Y = y0; + pt[2].X = x1; + pt[2].Y = y1; + pt[3].X = x0; + pt[3].Y = y1; + pt[4] = pt[0]; + + if (solid) + DrawSolidPoly(pt, 5, color, false); + else + DrawPoly(pt, 5, dw, color); + } + + public void DrawDisc(Vector2 c, int r, Color color) + { + // demasiado pequeño el radio + if (r < 10) + return; + + // quiero que cada linea como maximo tenga 3 pixeles + float da = 3.0f / (float)r; + int cant_ptos = (int)(2 * M_PI / da); + + VERTEX2D[] pt = new VERTEX2D[cant_ptos + 10]; // + 10 x las dudas + + int t = 0; // Cantidad de vertices + // el primer vertice es el centro del circulo + pt[t].x = c.X; + pt[t].y = c.Y; + ++t; + for (int i = 0; i < cant_ptos; ++i) + { + float an = (float)i / (float)cant_ptos * 2 * M_PI; + pt[t].x = c.X + (float)Math.Cos(an) * r; + pt[t].y = c.Y + (float)Math.Sin(an) * r; + ++t; + } + pt[t++] = pt[1]; // Cierro el circulo + + for (int j = 0; j < t; ++j) + { + pt[j].z = 0.5f; + pt[j].rhw = 1; + pt[j].color = color.ToArgb(); + } + + Transform(pt, t); + + Device d3dDevice = GuiController.Instance.D3dDevice; + d3dDevice.VertexFormat = VertexFormats.Transformed | VertexFormats.Diffuse; + d3dDevice.DrawUserPrimitives(PrimitiveType.TriangleFan, t - 2, pt); + } + + public void DrawCircle(Vector2 c, int r, int esp, Color color) + { + // demasiado pequeño el radio + if (r - esp < 10) + return; + + // quiero que cada linea como maximo tenga 5 pixeles + float da = 5.0f / (float)r; + int cant_ptos = (int)(2 * M_PI / da); + + VERTEX2D[] pt = new VERTEX2D[2 * cant_ptos + 10]; // + 10 x las dudas + + int t = 0; // Cantidad de vertices + + for (int i = 0; i < cant_ptos; ++i) + { + float an = (float)i / (float)cant_ptos * 2 * M_PI; + + // alterno los radios interior y exterior entre los pares e impares + + pt[t].x = c.X + (float)Math.Cos(an) * r; + pt[t].y = c.Y + (float)Math.Sin(an) * r; + ++t; + + pt[t].x = c.X + (float)Math.Cos(an) * (r - esp); + pt[t].y = c.Y + (float)Math.Sin(an) * (r - esp); + ++t; + } + + pt[t++] = pt[0]; // Cierro el circulo + pt[t++] = pt[1]; // Cierro el circulo + + for (int j = 0; j < t; ++j) + { + pt[j].z = 0.5f; + pt[j].rhw = 1; + pt[j].color = color.ToArgb(); + } + + Transform(pt, t); + + Device d3dDevice = GuiController.Instance.D3dDevice; + d3dDevice.VertexFormat = VertexFormats.Transformed | VertexFormats.Diffuse; + d3dDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, t - 2, pt); + } + + public void DrawArc(Vector2 c, int r, float desde, float hasta, int esp, Color color) + { + // demasiado pequeño el radio + if (r - esp < 10) + return; + + if (desde > hasta) + { + float aux = desde; + desde = hasta; + hasta = aux; + } + + // quiero que cada linea como maximo tenga 5 pixeles + float da = 5.0f / (float)r; + float arc_len = hasta - desde; + int cant_ptos = (int)(arc_len / da); + + if (cant_ptos <= 0) + return; + + VERTEX2D[] pt = new VERTEX2D[2 * cant_ptos + 10]; // + 10 x las dudas + + int t = 0; // Cantidad de vertices + + for (int i = 0; i < cant_ptos; ++i) + { + float an = desde + (float)i / (float)cant_ptos * arc_len; + + // alterno los radios interior y exterior entre los pares e impares + + pt[t].x = c.X + (float)Math.Cos(an) * r; + pt[t].y = c.Y + (float)Math.Sin(an) * r; + ++t; + + pt[t].x = c.X + (float)Math.Cos(an) * (r - esp); + pt[t].y = c.Y + (float)Math.Sin(an) * (r - esp); + ++t; + } + + for (int j = 0; j < t; ++j) + { + pt[j].z = 0.5f; + pt[j].rhw = 1; + pt[j].color = color.ToArgb(); + } + + Transform(pt, t); + + Device d3dDevice = GuiController.Instance.D3dDevice; + d3dDevice.VertexFormat = VertexFormats.Transformed | VertexFormats.Diffuse; + d3dDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, t - 2, pt); + } + + public void DrawImage(string fname, int x0, int y0, int x1, int y1) + { + if (sprite.Disposed) + return; + + // Verifico si la imagen ya esta cargada + bool flag = false; + int i = 0; + while (i < cant_bitmaps && !flag) + if (fname == bitmaps[i].fname) + flag = true; + else + ++i; + + if (!flag) + { + // No estaba, cargo la textura + i = cant_bitmaps++; + bitmaps[i].texture = cargar_textura(fname); + bitmaps[i].fname = fname; + // Aprovecho para calcular el tamaño de la imagen del boton + SurfaceDescription desc = bitmaps[i].texture.GetLevelDescription(0); + bitmaps[i].Width = desc.Width; + bitmaps[i].Height = desc.Height; + } + + Vector3 pos = new Vector3((x0 + x1) / 2, (y0 + y1) / 2, 0); + Vector3 c0 = new Vector3(bitmaps[i].Width / 2, bitmaps[i].Height / 2, 0); + // Determino la escala para que entre justo + Vector2 scale2 = new Vector2((float)(x1 - x0) / (float)bitmaps[i].Width, (float)(y1 - y0) / (float)bitmaps[i].Height); + sprite.Transform = Matrix.Transformation2D(new Vector2(pos.X, pos.Y), 0, scale2, new Vector2(0, 0), 0, new Vector2(0, 0)); + + Device d3dDevice = GuiController.Instance.D3dDevice; + d3dDevice.SetTexture(0, null); + bool ant_zenable = d3dDevice.RenderState.ZBufferEnable; + d3dDevice.RenderState.ZBufferEnable = false; + sprite.Begin(SpriteFlags.AlphaBlend); + sprite.Draw(bitmaps[i].texture, c0, pos, Color.FromArgb(255, 255, 255, 255).ToArgb()); + sprite.End(); + d3dDevice.RenderState.ZBufferEnable = ant_zenable; + } + + // Helper para cargar una textura + public static Texture cargar_textura(String filename, bool alpha_channel = false) + { + Texture textura = null; + filename.TrimEnd(); + // cargo la textura + Device d3dDevice = GuiController.Instance.D3dDevice; + String fname_aux = GuiController.Instance.ExamplesDir + "Shaders\\WorkshopShaders\\Media\\gui\\" + filename; + if (!File.Exists(fname_aux)) + // Pruebo con el nombre directo + fname_aux = filename; + if (!File.Exists(fname_aux)) + return null; // File doesnt exist + try + { + if (alpha_channel) + { + textura = TextureLoader.FromFile(d3dDevice, fname_aux, -2, -2, 1, Usage.None, + Format.A8B8G8R8, Pool.Managed, Filter.None, Filter.None, 0); + // Mask transparente + //SetAlphaChannel(textura, 255, 0, 255); + } + else + textura = TextureLoader.FromFile(d3dDevice, fname_aux, -2, -2, 1, Usage.None, + Format.A8B8G8R8, Pool.Managed, Filter.None, Filter.None, 0); + //textura = TextureLoader.FromFile(d3dDevice, fname_aux); + } + catch (Exception error) + { + } + return textura; + } + + public static int SetAlphaChannel(Texture g_pTexture, byte r0, byte g0, byte b0) + { + // Initialize the alpha channel + // tengo que hacer el reemplazo en TODOS los mipmaps generados para esta textura + int cant_mipmaps = g_pTexture.LevelCount; + for (int i = 0; i < cant_mipmaps; ++i) + { + SurfaceDescription desc = g_pTexture.GetLevelDescription(i); + int m_dwWidth = desc.Width; + int m_dwHeight = desc.Height; + Surface surf = g_pTexture.GetSurfaceLevel(i); + int pitch; + GraphicsStream gs = surf.LockRectangle(LockFlags.Discard, out pitch); + int size = m_dwHeight * pitch; + byte[] buffer = new byte[size]; + gs.Read(buffer, 0, size); + surf.UnlockRectangle(); + + for (int y = 0; y < m_dwHeight; y++) + { + for (int x = 0; x < m_dwWidth; x++) + { + int dwOffset = y * pitch + x * 4; + byte b = buffer[dwOffset]; + byte g = buffer[dwOffset + 1]; + byte r = buffer[dwOffset + 2]; + byte a; + if (Math.Abs(b - b0) < 15 && Math.Abs(g - g0) < 15 && Math.Abs(r - r0) < 15) // es el mask transparente + a = 0; + else + a = 255; + buffer[dwOffset + 3] = a; + } + } + + gs = surf.LockRectangle(LockFlags.Discard); + gs.Write(buffer, 0, size); + surf.UnlockRectangle(); + } + + return 1; + } + + public Matrix rectToQuad(float X, float Y, float W, float H, + float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) + { + float y21 = y2 - y1; + float y32 = y4 - y2; + float y43 = y3 - y4; + float y14 = y1 - y3; + float y31 = y4 - y1; + float y42 = y3 - y2; + + float a = -H * (x2 * x4 * y14 + x2 * x3 * y31 - x1 * x3 * y32 + x1 * x4 * y42); + float b = W * (x2 * x4 * y14 + x4 * x3 * y21 + x1 * x3 * y32 + x1 * x2 * y43); + float c = H * X * (x2 * x4 * y14 + x2 * x3 * y31 - x1 * x3 * y32 + x1 * x4 * y42) - H * W * x1 * (x3 * y32 - x4 * y42 + x2 * y43) - W * Y * (x2 * x4 * y14 + x4 * x3 * y21 + x1 * x3 * y32 + x1 * x2 * y43); + + float d = H * (-x3 * y21 * y4 + x2 * y1 * y43 - x1 * y2 * y43 - x4 * y1 * y3 + x4 * y2 * y3); + float e = W * (x3 * y2 * y31 - x4 * y1 * y42 - x2 * y31 * y3 + x1 * y4 * y42); + float f = -(W * (x3 * (Y * y2 * y31 + H * y1 * y32) - x4 * (H + Y) * y1 * y42 + H * x2 * y1 * y43 + x2 * Y * (y1 - y4) * y3 + x1 * Y * y4 * (-y2 + y3)) - H * X * (x3 * y21 * y4 - x2 * y1 * y43 + x4 * (y1 - y2) * y3 + x1 * y2 * (-y4 + y3))); + + float g = H * (x4 * y21 - x3 * y21 + (-x1 + x2) * y43); + float h = W * (-x2 * y31 + x3 * y31 + (x1 - x4) * y42); + float i = W * Y * (x2 * y31 - x3 * y31 - x1 * y42 + x4 * y42) + H * (X * (-(x4 * y21) + x3 * y21 + x1 * y43 - x2 * y43) + W * (-(x4 * y2) + x3 * y2 + x2 * y4 - x3 * y4 - x2 * y3 + x4 * y3)); + + const double ep = 0.0001; + + if (Math.Abs(i) < ep) + { + i = (float)(ep * (i > 0 ? 1.0f : -1.0f)); + } + + Matrix transform = new Matrix(); + + // X + transform.M11 = a / i; + transform.M21 = b / i; + transform.M31 = 0; + transform.M41 = c / i; + // Y + transform.M12 = d / i; + transform.M22 = e / i; + transform.M32 = 0; + transform.M42 = f / i; + + // Z + transform.M13 = 0; + transform.M23 = 0; + transform.M33 = 1; + transform.M43 = 0; + + // W + transform.M14 = g / i; + transform.M24 = h / i; + transform.M34 = 0; + transform.M44 = 1.0f; + + return transform; + } + + // Devuelve true si el punto x,y esta sobre una region "hot", es decir que + // corresponde a un item seleccionable. + // se usa para determinar si aplicar o no snap al movimiento de la mano + // No interesa que boton es, solo si esta o no en su region + public bool IsHotRegion(int x, int y) + { + bool rta = false; + int t = item_0; + while (t < cant_items && !rta) + { + if (!items[t].disabled && (items[t].seleccionable || items[t].auto_seleccionable)) + { + Point pt = new Point(0, 0); + if (items[t].scrolleable) + { + pt.X = (int)(x - sox * ex); + pt.Y = (int)(y - soy * ey); + } + else + { + pt.X = (int)x; + pt.Y = (int)y; + } + if (items[t].pt_inside(this, pt)) + rta = true; + } + ++t; + } + return rta; + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/GUIItem.cs b/TGC.Examples/WorkshopShaders/GUIItem.cs new file mode 100644 index 00000000..294e2596 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/GUIItem.cs @@ -0,0 +1,746 @@ +using Microsoft.DirectX; +using Microsoft.DirectX.Direct3D; +using System; +using System.Drawing; +using TGC.Core.SceneLoader; + +namespace TgcViewer.Utils.Gui +{ + // item generico, con soporte de texto, bitmap, etc + public class GUIItem + { + public int item_id; + public int nro_item; + public int flags; + public Rectangle rc; + public String text; + public Texture textura; + public int image_width; + public int image_height; + public Texture textura_sel; + public TgcMesh mesh; + public float ftime; + public Color c_fondo; // color del fondo + public Color c_font; // color de los textos + public Color c_selected; // color seleccionado + public bool seleccionable; // indica que el item es seleccionable + public bool auto_seleccionable; // no hace falta presionarlo para que genere eventos + public bool scrolleable; // indica que el item escrollea junto con el gui + public bool item3d; + public bool disabled; + public itemState state; + public Microsoft.DirectX.Direct3D.Font font; + public bool siempre_visible; + public bool marcado; // indica que el item esta "chequeado" + public bool image_centrada; // indica que la imagen se dibuja centrada + + // auxiliares + public Point center; + + public int len; + + public GUIItem() + { + Clean(); + } + + public void Clean() + { + item_id = -1; + ftime = 0; + state = itemState.normal; + seleccionable = false; + auto_seleccionable = false; + scrolleable = true; + text = ""; + rc = Rectangle.Empty; + textura_sel = textura = null; + len = 0; + c_fondo = DXGui.c_fondo; + c_font = DXGui.c_font; + c_selected = DXGui.c_selected; + center = Point.Empty; + item3d = false; + disabled = false; + image_width = image_height = 0; + siempre_visible = false; + marcado = false; + image_centrada = true; + } + + public GUIItem(DXGui gui, String s, int x, int y, int dx = 0, int dy = 0, int id = -1) + { + Clean(); + item_id = id; + nro_item = gui.cant_items; + font = gui.font; + text = s; + rc = new Rectangle(x, y, dx, dy); + center = new Point(x + dx / 2, y + dy / 2); + len = s.Length; + } + + public void cargar_textura(String imagen) + { + // Cargo la imagen en el gui + if ((textura = DXGui.cargar_textura(imagen, true)) != null) + { + // Aprovecho para calcular el tamaño de la imagen del boton + SurfaceDescription desc = textura.GetLevelDescription(0); + image_width = desc.Width; + image_height = desc.Height; + } + + // x defecto la imagen seleccionada tiene el mismo nombre con el S_ al principio + textura_sel = DXGui.cargar_textura("S_" + imagen, true); + } + + public void Dispose() + { + if (textura != null) + textura.Dispose(); + + if (textura_sel != null) + textura_sel.Dispose(); + } + + // interface: + public bool pt_inside(DXGui gui, Point p) + { + Vector2[] Q = new Vector2[2]; + Q[0] = new Vector2(rc.X, rc.Y); + Q[1] = new Vector2(rc.X + rc.Width, rc.Y + rc.Height); + gui.Transform(Q, 2); + Rectangle r = new Rectangle((int)Q[0].X, (int)Q[0].Y, (int)(Q[1].X - Q[0].X), (int)(Q[1].Y - Q[0].Y)); + return r.Contains(p); + } + + public virtual bool ProcessMsg() + { + return false; + } + + public virtual void Render(DXGui gui) + { + bool sel = gui.sel == nro_item && !disabled ? true : false; + Color color = sel ? c_selected : c_font; + if (rc.Width == 0 || rc.Height == 0) + { + // Ajusta el rectangulo para que adapte al texto a dibujar + Rectangle tw = gui.font.MeasureString(gui.sprite, text, DrawTextFormat.NoClip | DrawTextFormat.Top, color); + rc.Width = tw.Width + 20; + rc.Height = tw.Height + 10; + rc.X -= 10; + rc.Y -= 5; + + // Recalcula el centro + center = new Point(rc.X + rc.Width / 2, rc.Y + rc.Height / 2); + } + + Texture tx = sel && textura_sel != null ? textura_sel : textura; + if (tx != null) + { + Vector3 pos = image_centrada ? + new Vector3(rc.X - image_width, rc.Y + (rc.Height - image_height) / 2, 0) : + new Vector3(rc.X, rc.Y, 0); + gui.sprite.Draw(tx, Rectangle.Empty, Vector3.Empty, pos, Color.FromArgb(gui.alpha, 255, 255, 255)); + } + + if (sel) + { + gui.RoundRect(rc.Left - 8, rc.Top - 6, rc.Right + 8, rc.Bottom + 6, 6, 3, + Color.FromArgb(gui.alpha, DXGui.c_selected_frame), false); + int dy = rc.Height / 2; + + gui.line.Width = 2f; + gui.line.Begin(); + + byte r0 = DXGui.c_grad_inf_0.R; + byte g0 = DXGui.c_grad_inf_0.G; + byte b0 = DXGui.c_grad_inf_0.B; + byte r1 = DXGui.c_grad_inf_1.R; + byte g1 = DXGui.c_grad_inf_1.G; + byte b1 = DXGui.c_grad_inf_1.B; + + // Gradiente de abajo + for (int i = 0; i < dy; ++i) + { + Vector2[] pt = new Vector2[2]; + pt[0].X = rc.X - 3; + pt[1].X = rc.X + rc.Width + 3; + pt[1].Y = pt[0].Y = rc.Y + rc.Height / 2 - i; + gui.Transform(pt, 2); + float t = (float)i / (float)dy; + byte r = (byte)(r0 * t + r1 * (1 - t)); + byte g = (byte)(g0 * t + g1 * (1 - t)); + byte b = (byte)(b0 * t + b1 * (1 - t)); + gui.line.Draw(pt, Color.FromArgb(gui.alpha, r, g, b)); + } + + // Gradiente de arriba + r0 = DXGui.c_grad_sup_0.R; + g0 = DXGui.c_grad_sup_0.G; + b0 = DXGui.c_grad_sup_0.B; + r1 = DXGui.c_grad_sup_1.R; + g1 = DXGui.c_grad_sup_1.G; + b1 = DXGui.c_grad_sup_1.B; + + for (int i = 0; i < dy; ++i) + { + Vector2[] pt = new Vector2[2]; + pt[0].X = rc.X - 3; + pt[1].X = rc.X + rc.Width + 3; + pt[1].Y = pt[0].Y = rc.Y + rc.Height / 2 + i; + gui.Transform(pt, 2); + float t = (float)i / (float)dy; + byte r = (byte)(r0 * t + r1 * (1 - t)); + byte g = (byte)(g0 * t + g1 * (1 - t)); + byte b = (byte)(b0 * t + b1 * (1 - t)); + gui.line.Draw(pt, Color.FromArgb(gui.alpha, r, g, b)); + } + gui.line.End(); + } + + // dibujo el texto pp dicho + gui.font.DrawText(gui.sprite, text, rc, DrawTextFormat.NoClip | DrawTextFormat.VerticalCenter, + disabled ? Color.FromArgb(gui.alpha, DXGui.c_item_disabled) : sel ? Color.FromArgb(gui.alpha, 0, 32, 128) : c_font); + } + } + + // menu item + public class gui_menu_item : GUIItem + { + public gui_menu_item(DXGui gui, String s, String imagen, int id, int x, int y, int dx = 0, int dy = 0, bool penabled = true) : + base(gui, s, x, y, dx, dy, id) + { + disabled = !penabled; + seleccionable = true; + cargar_textura(imagen); + } + } + + // standard button + public class gui_button : GUIItem + { + public gui_button(DXGui gui, String s, int id, int x, int y, int dx = 0, int dy = 0) : + base(gui, s, x, y, dx, dy, id) + { + seleccionable = true; + } + + public override void Render(DXGui gui) + { + bool sel = gui.sel == nro_item ? true : false; + if (textura != null) + { + Vector3 pos = new Vector3(rc.Left - 64, rc.Top - 8, 0); + gui.sprite.Draw(textura, Rectangle.Empty, Vector3.Empty, pos, Color.FromArgb(gui.alpha, 255, 255, 255)); + } + + // recuadro del boton + gui.RoundRect(rc.Left, rc.Top, rc.Right, rc.Bottom, 15, 3, DXGui.c_buttom_frame); + + if (sel) + // boton seleccionado: lleno el interior + gui.RoundRect(rc.Left, rc.Top, rc.Right, rc.Bottom, 10, 1, DXGui.c_buttom_selected, true); + + // Texto del boton + Rectangle rc2 = new Rectangle(rc.Left, rc.Top + 10, rc.Width, rc.Height - 20); + Color color = sel ? DXGui.c_buttom_sel_text : DXGui.c_buttom_text; + gui.font.DrawText(gui.sprite, text, rc, DrawTextFormat.VerticalCenter | DrawTextFormat.Center, color); + } + } + + public class gui_color : GUIItem + { + public gui_color(DXGui gui, String s, int id, int x, int y) : base(gui, s, x, y, 50, 50, id) + { + seleccionable = true; + } + + public override void Render(DXGui gui) + { + bool sel = gui.sel == nro_item ? true : false; + + float rx = rc.Width / 2; + float ry = rc.Height / 2; + float x0 = rc.Left + rx; + float y0 = rc.Top + ry; + + if (sel || marcado) + { + rx += 12; + ry += 12; + x0 -= 6; + y0 -= 6; + } + + Vector2[] Q = new Vector2[7]; + for (int i = 0; i < 6; ++i) + { + Q[i].X = (float)(x0 + rx * Math.Cos(2 * Math.PI / 6 * i)); + Q[i].Y = (float)(y0 + ry * Math.Sin(2 * Math.PI / 6 * i)); + } + Q[6] = Q[0]; + + gui.DrawSolidPoly(Q, 7, c_fondo, false); + + if (sel) + // boton seleccionado: lleno el interior + gui.DrawPoly(Q, 7, 4, DXGui.c_buttom_selected); + else + if (marcado) + gui.DrawPoly(Q, 7, 3, Color.FromArgb(240, 245, 245)); + else + gui.DrawPoly(Q, 7, 1, Color.FromArgb(120, 120, 64)); + } + } + + public class gui_edit : GUIItem + { + public override void Render(DXGui gui) + { + bool sel = gui.sel == nro_item ? true : false; + bool foco = gui.foco == nro_item ? true : false; + + // recuadro del edit + gui.RoundRect(rc.Left, rc.Top, rc.Right, rc.Bottom, 11, 2, Color.FromArgb(80, 220, 20)); + + if (foco) + // tiene foco + gui.RoundRect(rc.Left, rc.Top, rc.Right, rc.Bottom, 8, 1, Color.FromArgb(255, 255, 255, 255), true); + + // Texto del edit + Color color = foco ? Color.FromArgb(0, 0, 0) : Color.FromArgb(130, 255, 130); + gui.font.DrawText(gui.sprite, text, rc, DrawTextFormat.Top | DrawTextFormat.Left, color); + + if (foco) + { + // si esta vacio, le agrego una I para que cuente bien el alto del caracter + String p = text; + if (p.Length == 0) + p += "I"; + Rectangle tw = gui.font.MeasureString(gui.sprite, p, DrawTextFormat.Top | DrawTextFormat.NoClip, color); + Rectangle rc2 = new Rectangle(rc.Right + tw.Width, rc.Top, 12, rc.Height); + // dibujo el cursor titilando + int cursor = (int)(gui.time * 5); + if (cursor % 2 != 0) + { + gui.line.Width = 8; + Vector2[] pt = new Vector2[2]; + pt[0].X = rc2.Left; + pt[1].X = rc2.Right; + pt[1].Y = pt[0].Y = rc2.Bottom; + + gui.Transform(pt, 2); + gui.line.Begin(); + gui.line.Draw(pt, Color.FromArgb(0, 64, 0)); + gui.line.End(); + } + } + } + } + + // Rectangular frame + public class gui_frame : GUIItem + { + public frameBorder borde; + + public gui_frame(DXGui gui, String s, int x, int y, int dx, int dy, Color color, + frameBorder tipo_borde = frameBorder.rectangular) : + base(gui, s, x, y, dx, dy) + { + c_fondo = color; + borde = tipo_borde; + } + + public override void Render(DXGui gui) + { + bool sel = gui.sel == nro_item ? true : false; + Color clr = Color.FromArgb(Math.Min(gui.alpha, c_fondo.A), c_fondo); + switch (borde) + { + case frameBorder.sin_borde: + // dibujo solo interior + gui.DrawRect(rc.X, rc.Y, rc.X + rc.Width, rc.Y + rc.Height, 1, clr, true); + break; + + case frameBorder.redondeado: + // Interior + gui.RoundRect(rc.X, rc.Y, rc.X + rc.Width, rc.Y + rc.Height, 30, 6, clr, true); + // Contorno + gui.RoundRect(rc.X, rc.Y, rc.X + rc.Width, rc.Y + rc.Height, 30, 6, Color.FromArgb(gui.alpha, DXGui.c_frame_border)); + break; + + case frameBorder.solapa: + { + float r = 40; + Vector2[] pt = new Vector2[10]; + pt[0].X = rc.X; + pt[0].Y = rc.Y + rc.Height; + pt[1].X = rc.X; + pt[1].Y = rc.Y; + pt[2].X = rc.X + rc.Width - r; + pt[2].Y = rc.Y; + pt[3].X = rc.X + rc.Width; + pt[3].Y = rc.Y + r; + pt[4].X = rc.X + rc.Width; + pt[4].Y = rc.Y + rc.Height; + pt[5].X = rc.X; + pt[5].Y = rc.Y + rc.Height; + pt[6] = pt[0]; + + gui.DrawSolidPoly(pt, 7, clr, false); + gui.DrawPoly(pt, 5, 6, DXGui.c_frame_border); + } + + break; + + case frameBorder.rectangular: + default: + + // interior + gui.DrawRect(rc.X, rc.Y, rc.X + rc.Width, rc.Y + rc.Height, 1, Color.FromArgb(gui.alpha, c_fondo), true); + // contorno + gui.DrawRect(rc.X, rc.Y, rc.X + rc.Width, rc.Y + rc.Height, 6, Color.FromArgb(gui.alpha, DXGui.c_frame_border)); + break; + } + + // Texto del frame + Rectangle rc2 = new Rectangle(rc.X, rc.Y, rc.X + rc.Width, rc.Y + rc.Height); + rc2.Y += 30; + rc2.X += 30; + Color color = sel ? c_selected : c_font; + gui.font.DrawText(gui.sprite, text, rc2, DrawTextFormat.NoClip | DrawTextFormat.Top, Color.FromArgb(gui.alpha, color)); + } + } + + // Irregular frame + public class gui_iframe : GUIItem + { + public gui_iframe(DXGui gui, String s, int x, int y, int dx, int dy, Color color) : + base(gui, s, x, y, dx, dy) + { + c_fondo = color; + } + + public override void Render(DXGui gui) + { + bool sel = gui.sel == nro_item ? true : false; + + float M_PI = (float)Math.PI; + Vector2[] pt = new Vector2[255]; + float da = M_PI / 8; + float alfa; + + float x0 = rc.Left; + float x1 = rc.Right; + float y0 = rc.Top; + float y1 = rc.Bottom; + float r = 10; + int t = 0; + float x = x0; + float y = y0; + for (alfa = 0; alfa < M_PI / 2; alfa += da) + { + pt[t].X = (float)(x - r * Math.Cos(alfa)); + pt[t].Y = (float)(y - r * Math.Sin(alfa)); + ++t; + } + pt[t].X = x; + pt[t].Y = y - r; + ++t; + + pt[t].X = (x1 + x0) / 2; + pt[t].Y = y - r; + ++t; + pt[t].X = (x1 + x0) / 2 + 50; + pt[t].Y = y + 20 - r; + ++t; + + x = x1; + y = y0 + 20; + for (alfa = M_PI / 2; alfa < M_PI; alfa += da) + { + pt[t].X = (float)(x - r * Math.Cos(alfa)); + pt[t].Y = (float)(y - r * Math.Sin(alfa)); + ++t; + } + pt[t].X = x + r; + pt[t].Y = y; + ++t; + + x = x1; + y = y1; + for (alfa = 0; alfa < M_PI / 2; alfa += da) + { + pt[t].X = (float)(x + r * Math.Cos(alfa)); + pt[t].Y = (float)(y + r * Math.Sin(alfa)); + ++t; + } + pt[t].X = x; + pt[t].Y = y + r; + ++t; + + pt[t].X = x0 + 150; + pt[t].Y = y + r; + + ++t; + pt[t].X = x0 + 100; + pt[t].Y = y - 20 + r; + ++t; + + x = x0; + y = y - 20; + for (alfa = M_PI / 2; alfa < M_PI; alfa += da) + { + pt[t].X = (float)(x + r * Math.Cos(alfa)); + pt[t].Y = (float)(y + r * Math.Sin(alfa)); + ++t; + } + pt[t++] = pt[0]; + + // interior + gui.DrawSolidPoly(pt, t, c_fondo); + + // contorno + gui.DrawPoly(pt, t, 6, DXGui.c_frame_border); + + // Texto del frame + Rectangle rc2 = new Rectangle(rc.Top, rc.Left, rc.Width, rc.Height); + rc2.Y += 25; + rc2.X += 30; + Color color = sel ? c_selected : c_font; + gui.font.DrawText(gui.sprite, text, rc2, DrawTextFormat.NoClip | DrawTextFormat.Top, color); + } + } + + public class gui_rect : GUIItem + { + public int radio; + + public override void Render(DXGui gui) + { + bool sel = gui.sel == nro_item ? true : false; + Color color = sel ? Color.FromArgb(gui.alpha, 255, 220, 220) : Color.FromArgb(gui.alpha, 130, 255, 130); + gui.RoundRect(rc.Left, rc.Top, rc.Right, rc.Bottom, radio, 2, color, false); + } + } + + public class gui_progress_bar : GUIItem + { + public int desde; + public int hasta; + public int pos; + + public gui_progress_bar(DXGui gui, int x, int y, int dx, int dy, int id = -1) : + base(gui, "", x, y, dx, dy, id) + { + pos = desde = 1; + hasta = 100; + seleccionable = false; + } + + public void SetRange(int d, int h, string s = "") + { + desde = d; + hasta = h; + text = s; + } + + public void SetPos(int p) + { + pos = p; + } + + public override void Render(DXGui gui) + { + float k = (float)(pos - desde) / (float)(hasta - desde); + gui.DrawRect(rc.Left, rc.Top, rc.Right, rc.Bottom, 1, Color.FromArgb(240, 240, 240), true); + gui.DrawRect(rc.Left, rc.Top, rc.Right, rc.Bottom, 1, Color.FromArgb(0, 0, 0)); + gui.DrawRect(rc.Left, rc.Top, rc.Left + (int)(rc.Width * k), rc.Bottom, 1, Color.FromArgb(0, 100, 255), true); + gui.DrawRect(rc.Left, rc.Top, rc.Left + (int)(rc.Width * k), rc.Bottom, 1, Color.FromArgb(0, 0, 0)); + + Rectangle rc2 = new Rectangle(rc.Left, rc.Top - 50, rc.Width, 50); + gui.font.DrawText(gui.sprite, text, rc2, DrawTextFormat.NoClip | DrawTextFormat.Top, Color.FromArgb(0, 0, 0)); + } + } + + public class gui_tile_button : GUIItem + { + public float ox, oy, ex, ey, k; + public bool sel; + public DXGui gui; + public bool border; + + public gui_tile_button(DXGui gui, String s, String imagen, int id, int x, int y, int dx, int dy, bool bscrolleable = true) : + base(gui, s, x, y, dx, dy, id) + { + seleccionable = true; + scrolleable = bscrolleable; + border = true; + // Cargo la imagen en el gui + cargar_textura(imagen); + } + + public virtual void InitRender(DXGui p_gui) + { + // inicializacion comun a todos los controles + gui = p_gui; + + // estado del control + sel = state == itemState.hover; + + // Calcula la escala pp dicha + ex = gui.ex; + ey = gui.ey; + ox = gui.ox; + oy = gui.oy; + if (scrolleable) + { + // como este boton es un item scrolleable, tiene que aplicar tambien el origen sox,soy + ox += gui.sox; + oy += gui.soy; + } + + // sobre escala por estar seleccionado + k = 1; + if (sel) + { + // aumento las escala + k = 1 + (float)(0.5 * (gui.delay_sel0 - gui.delay_sel)); + + // Le aplico una matriz de escalado adicional, solo sobre el TEXTO. + // El glyph tiene su propia matriz + + // Este kilombo es porque una cosa es la escala global que se aplica uniformemente en todo el gui + // y esta centrada en el origen. + // Pero esta escala es local, del texto, que se aplica centra en centro del texto, luego de haberlo + // escalado por la escala global. + gui.sprite.Transform = gui.sprite.Transform * Matrix.Transformation2D(new Vector2((center.X + ox) * ex, (center.Y + oy) * ey), 0, new Vector2(k, k), + new Vector2(0, 0), 0, new Vector2(0, 0)); + } + } + + public virtual void RenderText() + { + // dibujo el texto pp dicho + String buffer = text; + Color color = sel ? Color.FromArgb(gui.alpha, c_selected) : Color.FromArgb(gui.alpha, c_font); + Rectangle pos_texto = new Rectangle((int)ox + rc.Left, (int)oy + rc.Bottom + 15, rc.Width, 32); + gui.font.DrawText(gui.sprite, buffer, pos_texto, DrawTextFormat.NoClip | DrawTextFormat.Top | DrawTextFormat.Center, + sel ? Color.FromArgb(gui.alpha, 0, 32, 128) : Color.FromArgb(gui.alpha, c_font)); + } + + public virtual void RenderFrame() + { + // Dibujo un rectangulo + int x0 = (int)(rc.Left + ox); + int x1 = (int)(rc.Right + ox); + int y0 = (int)(rc.Top + oy); + int y1 = (int)(rc.Bottom + oy); + + if (sel) + { + int dmx = (int)(rc.Width * (k - 1) * 0.5); + int dmy = (int)(rc.Height * (k - 1) * 0.5); + gui.RoundRect(x0 - dmx, y0 - dmy, x1 + dmx, y1 + dmy, 4, 2, Color.FromArgb(gui.alpha, 0, 0, 0), true); + } + else + if (state == itemState.pressed) + { + gui.RoundRect(x0, y0, x1, y1, 4, 2, Color.FromArgb(gui.alpha, 32, 140, 55)); + float k2 = 1 + (float)(0.5 * gui.delay_press); + int dmx = (int)(rc.Width * (k2 - 1) * 1.1); + int dmy = (int)(rc.Height * (k2 - 1) * 1.1); + gui.RoundRect(x0 - dmx, y0 - dmy, x1 + dmx, y1 + dmy, 4, 8, Color.FromArgb(gui.alpha, 255, 0, 0)); + } + else + gui.RoundRect(x0, y0, x1, y1, 4, 2, Color.FromArgb(gui.alpha, 32, 140, 55)); + } + + public virtual void RenderGlyph() + { + // dibujo el glyph + if (textura != null) + { + Vector3 pos = new Vector3(center.X * ex, center.Y * ey, 0); + Vector3 c0 = new Vector3(image_width / 2, image_height / 2, 0); + // Determino la escala para que entre justo + Vector2 scale = new Vector2(k * ex * (float)rc.Width / (float)image_width, k * ey * (float)rc.Height / (float)image_height); + Vector2 offset = new Vector2(ox * ex, oy * ey); + gui.sprite.Transform = Matrix.Transformation2D(new Vector2(center.X * ex, center.Y * ey), 0, scale, new Vector2(0, 0), 0, offset) * gui.RTQ; + gui.sprite.Draw(textura, c0, pos, Color.FromArgb(gui.alpha, 255, 255, 255).ToArgb()); + } + } + + public override void Render(DXGui gui) + { + // Guardo la Matrix anterior + Matrix matAnt = gui.sprite.Transform * Matrix.Identity; + // Inicializo escalas, matrices, estados + InitRender(gui); + // Secuencia standard: texto + Frame + Glyph + RenderText(); + if (border) + RenderFrame(); + RenderGlyph(); + // Restauro la transformacion del sprite + gui.sprite.Transform = matAnt; + } + } + + public class gui_circle_button : gui_tile_button + { + public Color c_border = Color.FromArgb(0, 0, 0); + public Color c_interior_sel = Color.FromArgb(30, 240, 40); + public bool texto_derecha; + + public gui_circle_button(DXGui gui, String s, String imagen, int id, int x, int y, int r) : + base(gui, s, imagen, id, x, y, r, r) + + { + texto_derecha = false; // indica si el texto va a derecha o debajo del glyph + } + + public override void RenderText() + { + // dibujo el texto pp dicho + String buffer = text; + Color color = sel ? Color.FromArgb(gui.alpha, c_selected) : Color.FromArgb(gui.alpha, c_font); + if (texto_derecha) + { + Rectangle pos_texto = new Rectangle((int)ox + rc.Right, (int)oy + rc.Top + rc.Height / 2, rc.Width, 32); + gui.font.DrawText(gui.sprite, buffer, pos_texto, DrawTextFormat.NoClip | DrawTextFormat.VerticalCenter | DrawTextFormat.Left, + sel ? Color.FromArgb(gui.alpha, 0, 32, 128) : Color.FromArgb(gui.alpha, c_font)); + } + else + { + Rectangle pos_texto = new Rectangle((int)ox + rc.Left, (int)oy + rc.Bottom + 15, rc.Width, 32); + gui.font.DrawText(gui.sprite, buffer, pos_texto, DrawTextFormat.NoClip | DrawTextFormat.Top | DrawTextFormat.Center, + sel ? Color.FromArgb(gui.alpha, 0, 32, 128) : Color.FromArgb(gui.alpha, c_font)); + } + } + + public override void RenderFrame() + { + float tr = (float)(4 * (gui.delay_sel0 - gui.delay_sel)); + // circulo + int R = (int)(rc.Width / 2 * k); + + gui.DrawCircle(new Vector2(rc.X + rc.Width / 2 + ox, rc.Y + rc.Height / 2 + oy), R, 10, Color.FromArgb(gui.alpha, c_border)); + + // relleno + if (sel) + gui.DrawDisc(new Vector2(rc.X + rc.Width / 2 + ox, rc.Y + rc.Height / 2 + oy), R - 10, + Color.FromArgb((byte)(255 * tr), c_interior_sel.R, c_interior_sel.G, c_interior_sel.B)); + else + if (state == itemState.pressed) + { + gui.DrawDisc(new Vector2(rc.X + rc.Width / 2 + ox, rc.Y + rc.Height / 2 + oy), R - 10, Color.FromArgb(255, 255, 0, 0)); + int R2 = (int)(rc.Width / 2 + gui.delay_press * 100); + gui.DrawCircle(new Vector2(rc.X + rc.Width / 2 + ox, rc.Y + rc.Height / 2 + oy), R2, 10, Color.FromArgb(255, 120, 120)); + } + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/GUITest.cs b/TGC.Examples/WorkshopShaders/GUITest.cs new file mode 100644 index 00000000..54ff9ec3 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/GUITest.cs @@ -0,0 +1,345 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using TGC.Core.Mathematica; +using TGC.Core.SkeletalAnimation; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Example; +using TgcViewer.Utils.Gui; + +namespace Examples.WorkshopShaders +{ + public class GuiTest : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + private Effect effect; + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool PeekMessage(ref MSG lpMsg, Int32 hwnd, Int32 wMsgFilterMin, Int32 wMsgFilterMax, PeekMessageOption wRemoveMsg); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool TranslateMessage(ref MSG lpMsg); + + [DllImport("user32.dll", SetLastError = true)] + private static extern Int32 DispatchMessage(ref MSG lpMsg); + + public const Int32 WM_QUIT = 0x12; + + // Defines + public const int IDOK = 0; + + public const int IDCANCEL = 1; + public const int ID_ABRIR_MISION = 100; + public const int ID_GRABAR_MISION = 101; + public const int ID_NUEVA_MISION = 102; + public const int ID_CONFIGURAR = 103; + public const int ID_APP_EXIT = 105; + public const int ID_PROGRESS1 = 107; + public const int ID_RESET_CAMARA = 108; + + public gui_progress_bar progress_bar; + public bool msg_box_app_exit = false; + public bool profiling = false; + + private TgcSkeletalMesh mesh; + private Color[] lst_colores = new Color[12]; + private int cant_colores = 12; + + public struct POINTAPI + { + public Int32 x; + public Int32 y; + } + + public struct MSG + { + public Int32 hwmd; + public Int32 message; + public Int32 wParam; + public Int32 lParam; + public Int32 time; + public POINTAPI pt; + } + + public enum PeekMessageOption + { + PM_NOREMOVE = 0, + PM_REMOVE + } + + // gui + private DXGui gui = new DXGui(); + + public GuiTest(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) + : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-GuiTest"; + Description = "Gui Demo"; + } + + public override void Init() + { + GuiController.Instance.CustomRenderEnabled = true; + Cursor.Hide(); + + Device d3dDevice = GuiController.Instance.D3dDevice; + MyMediaDir = MediaDir + "WorkshopShaders\\"; + MyShaderDir = ShadersDir + "WorkshopShaders\\"; + + //Cargar Shader personalizado + string compilationErrors; + effect = Effect.FromFile(GuiController.Instance.D3dDevice, MyShaderDir + "TgcSkeletalMeshShader.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors); + if (effect == null) + { + throw new Exception("Error al cargar shader. Errores: " + compilationErrors); + } + //Configurar Technique dentro del shader + effect.Technique = "DIFFUSE_MAP"; + + GuiController.Instance.FpsCamera.Enable = true; + GuiController.Instance.FpsCamera.setCamera(new TGCVector3(0, 60, 200), new TGCVector3(0, 0, 0)); + GuiController.Instance.FpsCamera.updateCamera(); + + //Cargar personaje con animaciones + TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader(); + mesh = skeletalLoader.loadMeshAndAnimationsFromFile(MediaDir + "SkeletalAnimations\\BasicHuman\\" + "CombineSoldier-TgcSkeletalMesh.xml", MediaDir + "SkeletalAnimations\\BasicHuman\\", new string[] { MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "StandBy-TgcSkeletalAnim.xml", MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Run-TgcSkeletalAnim.xml", }); + + //Configurar animacion inicial + mesh.playAnimation("StandBy", true); + mesh.Position = new TGCVector3(0, -50, 0); + mesh.Scale = new TGCVector3(2f, 2f, 2f); + mesh.Effect = effect; + mesh.Technique = "DIFFUSE_MAP"; + + // levanto el GUI + gui.Create(); + + // menu principal + gui.InitDialog(true); + int W = GuiController.Instance.Panel3d.Width; + int H = GuiController.Instance.Panel3d.Height; + int x0 = 70; + int y0 = 10; + int dy = 120; + int dy2 = dy; + int dx = 400; + gui.InsertMenuItem(ID_ABRIR_MISION, "Abrir Mision", "open.png", x0, y0, dx, dy); + gui.InsertMenuItem(ID_NUEVA_MISION, "Play", "Play.png", x0, y0 += dy2, dx, dy); + gui.InsertMenuItem(ID_CONFIGURAR, "Configurar", "navegar.png", x0, y0 += dy2, dx, dy); + gui.InsertMenuItem(ID_APP_EXIT, "Salir", "salir.png", x0, y0 += dy2, dx, dy); + + // lista de colores + lst_colores[0] = Color.FromArgb(100, 220, 255); + lst_colores[1] = Color.FromArgb(100, 255, 220); + lst_colores[2] = Color.FromArgb(220, 100, 255); + lst_colores[3] = Color.FromArgb(220, 255, 100); + lst_colores[4] = Color.FromArgb(255, 100, 220); + lst_colores[5] = Color.FromArgb(255, 220, 100); + lst_colores[6] = Color.FromArgb(128, 128, 128); + lst_colores[7] = Color.FromArgb(64, 255, 64); + lst_colores[8] = Color.FromArgb(64, 64, 255); + lst_colores[9] = Color.FromArgb(255, 0, 255); + lst_colores[10] = Color.FromArgb(255, 255, 0); + lst_colores[11] = Color.FromArgb(0, 255, 255); + } + + public override void Update() + { + mesh.RotateY(ElapsedTime * 1.2f); + } + + public override void Render() + { + gui_render(ElapsedTime); + + if (profiling) + { + Device device = GuiController.Instance.D3dDevice; + Viewport ant_view = device.Viewport; + Viewport view = new Viewport(); + view.X = (int)(400 * gui.ex); + view.Y = (int)(100 * gui.ey); + view.Width = (int)(400 * gui.ex); + view.Height = (int)(300 * gui.ey); + view.MinZ = 0; + view.MaxZ = 1; + + device.Viewport = view; + mesh.Render(); + device.Viewport = ant_view; + } + } + + public void gui_render(float elapsedTime) + { + // ------------------------------------------------ + GuiMessage msg = gui.Update(elapsedTime); + // proceso el msg + switch (msg.message) + { + case MessageType.WM_COMMAND: + switch (msg.id) + { + case IDOK: + case IDCANCEL: + // Resultados OK, y CANCEL del ultimo messagebox + gui.EndDialog(); + profiling = false; + if (msg_box_app_exit) + { + // Es la resupuesta a un messagebox de salir del sistema + if (msg.id == IDOK) + { + // Salgo del sistema + //GuiController.Instance.shutDown(); + Cursor.Show(); + } + } + msg_box_app_exit = false; + break; + + case ID_ABRIR_MISION: + ProgressBarDlg(); + break; + + case ID_NUEVA_MISION: + gui.MessageBox("Nueva Misión", "TGC Gui Demo"); + break; + + case ID_CONFIGURAR: + Configurar(); + break; + + case ID_APP_EXIT: + gui.MessageBox("Desea Salir?", "TGC Gui Demo"); + msg_box_app_exit = true; + break; + + default: + if (msg.id >= 1000 && msg.id < 1000 + cant_colores) + { + // Cambio el color + int color = msg.id - 1000; + + effect.SetValue("color_global", new TGCVector4( + (float)lst_colores[color].R / 255.0f, + (float)lst_colores[color].G / 255.0f, + (float)lst_colores[color].B / 255.0f, 1)); + } + break; + } + break; + + default: + break; + } + gui.Render(); + } + + public void Configurar() + { + gui.InitDialog(false, false); + profiling = true; + int W = GuiController.Instance.Panel3d.Width; + int H = GuiController.Instance.Panel3d.Height; + int x0 = 50; + int y0 = 50; + int dy = H - 100; + int dx = W - 100; + GUIItem frame = gui.InsertIFrame("Profiling", x0, y0, dx, dy, Color.FromArgb(140, 240, 140)); + frame.c_font = Color.FromArgb(0, 0, 0); + gui.InsertButton(IDOK, "OK", x0 + dx - 300, y0 + dy - 60, 120, 60); + gui.InsertButton(IDCANCEL, "Salir", x0 + dx - 140, y0 + dy - 60, 120, 60); + gui.InsertItem("Configure el color", x0 + 50, y0 + 130); + + int cdx = 50; + int pos_x = x0 + 100; + int pos_y = y0 + 220; + int s = 0; + for (int i = 0; i < cant_colores; ++i) + { + GUIItem item = gui.InsertItemColor(pos_x, pos_y, lst_colores[i], 1000 + i); + if ((i + 1) % 4 == 0) + { + if (s % 2 == 1) + pos_x = x0 + 100; + else + pos_x = x0 + 100 - 38; + pos_y += cdx / 2; + s++; + } + else + pos_x += cdx + cdx / 2; + + // uso el texto para meter el dato del nro de color + item.text = "" + i; + } + } + + public void ProgressBarDlg() + { + gui.InitDialog(false, false); + + int W = GuiController.Instance.Panel3d.Width; + int H = GuiController.Instance.Panel3d.Height; + int x0 = -20; + int y0 = 100; + int dy = 350; + int dx = W + 50; + + GUIItem frame = gui.InsertFrame("Cargando mision", x0, y0, dx, dy, Color.FromArgb(240, 240, 240), frameBorder.sin_borde); + frame.c_font = Color.FromArgb(0, 0, 0); + progress_bar = gui.InsertProgressBar(ID_PROGRESS1, 50, y0 + 150, W - 100, 60); + + Device d3dDevice = GuiController.Instance.D3dDevice; + int cant_textures = 5; + progress_bar.SetRange(0, cant_textures, "Descargando archivos.."); + progress_bar.SetPos(1); + for (int i = 0; i < cant_textures; ++i) + { + progress_bar.SetPos(i); + progress_bar.text = "Descargando archivo: " + MyMediaDir + "f1\\piso3.png"; + + Texture textura_piso = Texture.FromBitmap(d3dDevice, (Bitmap)Bitmap.FromFile(MyMediaDir + "f1\\piso3.png"), Usage.None, Pool.Managed); + textura_piso.Dispose(); + MessageLoop(); + } + + gui.EndDialog(); // progress bar dialog + } + + public bool MessageLoop() + { + MSG msg = new MSG(); + PeekMessage(ref msg, 0, 0, 0, PeekMessageOption.PM_REMOVE); + if (msg.message == WM_QUIT) + return false; + TranslateMessage(ref msg); + DispatchMessage(ref msg); + + Device d3dDevice = GuiController.Instance.D3dDevice; + d3dDevice.BeginScene(); + //render(0); + ElapsedTime = 0; + Render(); + + d3dDevice.EndScene(); + d3dDevice.Present(); + + return true; + } + + public override void Dispose() + { + mesh.Dispose(); + gui.Dispose(); + effect.Dispose(); + Cursor.Show(); + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/HDRLighting.cs b/TGC.Examples/WorkshopShaders/HDRLighting.cs new file mode 100644 index 00000000..3f420cd4 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/HDRLighting.cs @@ -0,0 +1,451 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using TGC.Core; +using TGC.Core.Mathematica; +using TGC.Core.SceneLoader; +using TGC.Core.Terrain; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Example; + +namespace Examples.WorkshopShaders +{ + public class HDRLighting : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + private List meshes; + private TgcSkyBox skyBox; + private TgcSimpleTerrain terrain; + private TgcMesh pasto, arbol, arbusto; + private Effect effect; + private Surface g_pDepthStencil; // Depth-stencil buffer + private Texture g_pRenderTarget, g_pGlowMap, g_pRenderTarget4, g_pRenderTarget4Aux; + + private const int NUM_REDUCE_TX = 5; + private Texture[] g_pLuminance = new Texture[NUM_REDUCE_TX]; + private Texture g_pLuminance_ant; + + private VertexBuffer g_pVBV3D; + private int cant_pasadas = 5; + + private float pupila_time = 0; + private float MAX_PUPILA_TIME = 3; + + public enum ToneMapping : int + { + Nada = 0, + Reinhard = 1, + Modified_Reinhard = 2, + Logaritmico = 3, + MiddleGray = 4 + }; + + public HDRLighting(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) + : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-HdrLighting"; + Description = "HDR lighting"; + } + + public override void Init() + { + Device d3dDevice = GuiController.Instance.D3dDevice; + MyMediaDir = MediaDir + "WorkshopShaders\\"; + MyShaderDir = ShadersDir + "WorkshopShaders\\"; + + //Cargamos un escenario + TgcSceneLoader loader = new TgcSceneLoader(); + + TgcScene scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Scenes\\Selva\\Selva-TgcScene.xml"); + meshes = scene.Meshes; + TgcScene scene2 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Pasto\\Pasto-TgcScene.xml"); + pasto = scene2.Meshes[0]; + TgcScene scene3 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\ArbolSelvatico\\ArbolSelvatico-TgcScene.xml"); + arbol = scene3.Meshes[0]; + arbol.Scale = new TGCVector3(1, 3, 1); + TgcScene scene4 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Arbusto2\\Arbusto2-TgcScene.xml"); + arbusto = scene4.Meshes[0]; + + //Cargar terreno: cargar heightmap y textura de color + terrain = new TgcSimpleTerrain(); + terrain.loadHeightmap(MyMediaDir + "Heighmaps\\" + "TerrainTexture2.jpg", 20, 0.3f, new TGCVector3(0, -115, 0)); + terrain.loadTexture(MyMediaDir + "Heighmaps\\" + "grass.jpg"); + + //Crear SkyBox + skyBox = new TgcSkyBox(); + skyBox.Center = new TGCVector3(0, 500, 0); + skyBox.Size = new TGCVector3(10000, 10000, 10000); + string texturesPath = MediaDir + "Texturas\\Quake\\SkyBox2\\"; + skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "lun4_up.jpg"); + skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "lun4_dn.jpg"); + skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "lun4_lf.jpg"); + skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "lun4_rt.jpg"); + skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "lun4_bk.jpg"); + skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "lun4_ft.jpg"); + skyBox.updateValues(); + + //Cargar Shader personalizado + string compilationErrors; + effect = Effect.FromFile(GuiController.Instance.D3dDevice, ShadersDir + "WorkshopShaders\\GaussianBlur.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors); + if (effect == null) + { + throw new Exception("Error al cargar shader. Errores: " + compilationErrors); + } + //Configurar Technique dentro del shader + effect.Technique = "DefaultTechnique"; + + //Camara en primera personas + GuiController.Instance.FpsCamera.Enable = true; + GuiController.Instance.FpsCamera.setCamera(new TGCVector3(-944.1269f, 50, -1033.307f), new TGCVector3(-943.6573f, 50.8481f, -1033.533f)); + GuiController.Instance.FpsCamera.MovementSpeed *= 2; + GuiController.Instance.FpsCamera.JumpSpeed = 600f; + GuiController.Instance.FpsCamera.RotationSpeed *= 4; + + g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true); + + // inicializo el render target + g_pRenderTarget = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default); + + g_pGlowMap = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default); + + g_pRenderTarget4 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth / 4, d3dDevice.PresentationParameters.BackBufferHeight / 4, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default); + + g_pRenderTarget4Aux = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth / 4, d3dDevice.PresentationParameters.BackBufferHeight / 4, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default); + + // Para computar el promedio de Luminance + int tx_size = 1; + for (int i = 0; i < NUM_REDUCE_TX; ++i) + { + g_pLuminance[i] = new Texture(d3dDevice, tx_size, tx_size, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default); + tx_size *= 4; + } + + g_pLuminance_ant = new Texture(d3dDevice, 1, 1, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default); + + effect.SetValue("g_RenderTarget", g_pRenderTarget); + + // Resolucion de pantalla + effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth); + effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight); + + CustomVertex.PositionTextured[] vertices = new CustomVertex.PositionTextured[] + { + new CustomVertex.PositionTextured( -1, 1, 1, 0,0), + new CustomVertex.PositionTextured(1, 1, 1, 1,0), + new CustomVertex.PositionTextured(-1, -1, 1, 0,1), + new CustomVertex.PositionTextured(1,-1, 1, 1,1) + }; + //vertex buffer de los triangulos + g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); + g_pVBV3D.SetData(vertices, 0, LockFlags.None); + + Modifiers.addBoolean("activar_glow", "Activar Glow", true); + Modifiers.addBoolean("pantalla_completa", "Pant.completa", true); + Modifiers.addEnum("tm_izq", typeof(ToneMapping), ToneMapping.MiddleGray); + Modifiers.addEnum("tm_der", typeof(ToneMapping), ToneMapping.Nada); + Modifiers.addInterval("adaptacion_pupila", new object[] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }, 2); + } + + public override void Update() + { + PreUpdate(); + + TGCVector3 pos = Camara.Position; + } + + public override void Render() + { + renderConEfectos(ElapsedTime); + } + + public void renderSinEfectos(float elapsedTime) + { + Device device = GuiController.Instance.D3dDevice; + + // dibujo la escena una textura + effect.Technique = "DefaultTechnique"; + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + device.BeginScene(); + //Dibujamos todos los meshes del escenario + renderScene(elapsedTime, "DefaultTechnique"); + //Render skybox + skyBox.Render(); + device.EndScene(); + } + + public void renderConEfectos(float elapsedTime) + { + Device device = GuiController.Instance.D3dDevice; + + // Resolucion de pantalla + float screen_dx = device.PresentationParameters.BackBufferWidth; + float screen_dy = device.PresentationParameters.BackBufferHeight; + effect.SetValue("screen_dx", screen_dx); + effect.SetValue("screen_dy", screen_dy); + + // dibujo la escena una textura + effect.Technique = "DefaultTechnique"; + // guardo el Render target anterior y seteo la textura como render target + Surface pOldRT = device.GetRenderTarget(0); + Surface pSurf = g_pRenderTarget.GetSurfaceLevel(0); + device.SetRenderTarget(0, pSurf); + // hago lo mismo con el depthbuffer, necesito el que no tiene multisampling + Surface pOldDS = device.DepthStencilSurface; + device.DepthStencilSurface = g_pDepthStencil; + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + effect.SetValue("KLum", 0.05f); + device.BeginScene(); + //Dibujamos todos los meshes del escenario + renderScene(elapsedTime, "DefaultTechnique"); + // y el skybox (el skybox no tiene efectos, va por fixed OJOOO) + skyBox.Render(); + + device.EndScene(); + pSurf.Dispose(); + + MAX_PUPILA_TIME = (float)Modifiers["adaptacion_pupila"]; + bool glow = (bool)Modifiers["activar_glow"]; + effect.SetValue("glow", glow); + if (glow) + { + // dibujo el glow map + effect.SetValue("KLum", 1.0f); + effect.Technique = "DefaultTechnique"; + pSurf = g_pGlowMap.GetSurfaceLevel(0); + device.SetRenderTarget(0, pSurf); + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + device.BeginScene(); + + // dibujo el skybox que es brillante, con la tecnica estandard + skyBox.Render(); + + // El resto opacos + renderScene(elapsedTime, "DibujarObjetosOscuros"); + + device.EndScene(); + pSurf.Dispose(); + + // Hago un blur sobre el glow map + // 1er pasada: downfilter x 4 + // ----------------------------------------------------- + pSurf = g_pRenderTarget4.GetSurfaceLevel(0); + device.SetRenderTarget(0, pSurf); + device.BeginScene(); + effect.Technique = "DownFilter4"; + device.VertexFormat = CustomVertex.PositionTextured.Format; + device.SetStreamSource(0, g_pVBV3D, 0); + effect.SetValue("g_RenderTarget", g_pGlowMap); + + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + effect.Begin(FX.None); + effect.BeginPass(0); + device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + pSurf.Dispose(); + device.EndScene(); + device.DepthStencilSurface = pOldDS; + + // Pasadas de blur + for (int P = 0; P < cant_pasadas; ++P) + { + // Gaussian blur Horizontal + // ----------------------------------------------------- + pSurf = g_pRenderTarget4Aux.GetSurfaceLevel(0); + device.SetRenderTarget(0, pSurf); + // dibujo el quad pp dicho : + device.BeginScene(); + effect.Technique = "GaussianBlurSeparable"; + device.VertexFormat = CustomVertex.PositionTextured.Format; + device.SetStreamSource(0, g_pVBV3D, 0); + effect.SetValue("g_RenderTarget", g_pRenderTarget4); + + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + effect.Begin(FX.None); + effect.BeginPass(0); + device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + pSurf.Dispose(); + device.EndScene(); + + pSurf = g_pRenderTarget4.GetSurfaceLevel(0); + device.SetRenderTarget(0, pSurf); + pSurf.Dispose(); + + // Gaussian blur Vertical + // ----------------------------------------------------- + device.BeginScene(); + effect.Technique = "GaussianBlurSeparable"; + device.VertexFormat = CustomVertex.PositionTextured.Format; + device.SetStreamSource(0, g_pVBV3D, 0); + effect.SetValue("g_RenderTarget", g_pRenderTarget4Aux); + + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + effect.Begin(FX.None); + effect.BeginPass(1); + device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + device.EndScene(); + } + //TextureLoader.Save("glowmap", ImageFileFormat.Bmp, g_pRenderTarget4Aux); + } + + // computo el promedio + pSurf = g_pLuminance[NUM_REDUCE_TX - 1].GetSurfaceLevel(0); + screen_dx = pSurf.Description.Width; + screen_dy = pSurf.Description.Height; + device.SetRenderTarget(0, pSurf); + device.BeginScene(); + effect.Technique = "DownFilter4"; + device.VertexFormat = CustomVertex.PositionTextured.Format; + device.SetStreamSource(0, g_pVBV3D, 0); + effect.SetValue("g_RenderTarget", g_pRenderTarget); + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + effect.Begin(FX.None); + effect.BeginPass(0); + device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + pSurf.Dispose(); + device.EndScene(); + device.DepthStencilSurface = pOldDS; + string fname2 = string.Format("Pass{0:D}.bmp", NUM_REDUCE_TX); + //SurfaceLoader.Save(fname2, ImageFileFormat.Bmp, pSurf); + + // Reduce + for (int i = NUM_REDUCE_TX - 1; i > 0; i--) + { + pSurf = g_pLuminance[i - 1].GetSurfaceLevel(0); + effect.SetValue("screen_dx", screen_dx); + effect.SetValue("screen_dy", screen_dy); + + device.SetRenderTarget(0, pSurf); + effect.SetValue("g_RenderTarget", g_pLuminance[i]); + device.BeginScene(); + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + effect.Begin(FX.None); + effect.BeginPass(0); + device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + pSurf.Dispose(); + device.EndScene(); + + string fname = string.Format("Pass{0:D}.bmp", i); + //SurfaceLoader.Save(fname, ImageFileFormat.Bmp, pSurf); + + screen_dx /= 4.0f; + screen_dy /= 4.0f; + } + + // Tone mapping + // ----------------------------------------------------- + effect.SetValue("tone_mapping_izq", (int)Modifiers["tm_izq"]); + effect.SetValue("tone_mapping_der", (int)Modifiers["tm_der"]); + effect.SetValue("pantalla_completa", (bool)Modifiers["pantalla_completa"]); + effect.SetValue("screen_dx", device.PresentationParameters.BackBufferWidth); + effect.SetValue("screen_dy", device.PresentationParameters.BackBufferHeight); + device.SetRenderTarget(0, pOldRT); + device.BeginScene(); + effect.Technique = "ToneMapping"; + device.VertexFormat = CustomVertex.PositionTextured.Format; + device.SetStreamSource(0, g_pVBV3D, 0); + effect.SetValue("g_RenderTarget", g_pRenderTarget); + effect.SetValue("g_GlowMap", g_pRenderTarget4Aux); + pupila_time += elapsedTime; + if (pupila_time >= MAX_PUPILA_TIME) + { + pupila_time = 0; + effect.SetValue("g_Luminance_ant", g_pLuminance[0]); + Texture aux = g_pLuminance[0]; + g_pLuminance[0] = g_pLuminance_ant; + g_pLuminance_ant = aux; + } + else + { + effect.SetValue("g_Luminance", g_pLuminance[0]); + } + + effect.SetValue("pupila_time", pupila_time / MAX_PUPILA_TIME); // 0..1 + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + effect.Begin(FX.None); + effect.BeginPass(0); + device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); + effect.EndPass(); + effect.End(); + + PostRender(); + } + + public void renderScene(float elapsedTime, String Technique) + { + //Dibujamos todos los meshes del escenario + Random rnd = new Random(1); + pasto.Effect = effect; + pasto.Technique = Technique; + for (int i = 0; i < 10; ++i) + for (int j = 0; j < 10; ++j) + { + pasto.Position = new TGCVector3(-i * 200 + rnd.Next(0, 50), 0, -j * 200 + rnd.Next(0, 50)); + pasto.Scale = new TGCVector3(3, 4 + rnd.Next(0, 4), 5); + pasto.Render(); + } + + arbusto.Effect = effect; + arbusto.Technique = Technique; + for (int i = 0; i < 5; ++i) + for (int j = 0; j < 5; ++j) + { + arbusto.Position = new TGCVector3(-i * 400 + rnd.Next(0, 50), 0, -j * 400 + rnd.Next(0, 50)); + arbusto.Render(); + } + + arbol.Effect = effect; + arbol.Technique = Technique; + for (int i = 0; i < 3; ++i) + for (int j = 0; j < 3; ++j) + { + arbol.Position = new TGCVector3(-i * 700 + rnd.Next(0, 50), 0, -j * 700 + rnd.Next(0, 50)); + arbol.Render(); + } + + // ------------------------------------- + //Renderizar terreno + terrain.Effect = effect; + terrain.Technique = Technique; + terrain.Render(); + } + + public override void Dispose() + { + foreach (TgcMesh m in meshes) + { + m.Dispose(); + } + effect.Dispose(); + skyBox.Dispose(); + terrain.Dispose(); + pasto.Dispose(); + arbol.Dispose(); + arbusto.Dispose(); + g_pRenderTarget.Dispose(); + g_pGlowMap.Dispose(); + g_pRenderTarget4Aux.Dispose(); + g_pRenderTarget4.Dispose(); + g_pVBV3D.Dispose(); + g_pDepthStencil.Dispose(); + for (int i = 0; i < NUM_REDUCE_TX; i++) + { + g_pLuminance[i].Dispose(); + } + g_pLuminance_ant.Dispose(); + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/POMTerrain.cs b/TGC.Examples/WorkshopShaders/POMTerrain.cs new file mode 100644 index 00000000..5cd504fd --- /dev/null +++ b/TGC.Examples/WorkshopShaders/POMTerrain.cs @@ -0,0 +1,342 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Drawing; +using System.Windows.Forms; +using TGC.Core.Mathematica; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Core.Utils; +using TGC.Examples.Example; + +namespace Examples.WorkshopShaders +{ + public class POMTerrain + { + private VertexBuffer vbTerrain; + public TGCVector3 center; + public Texture terrainTexture; + public int totalVertices; + public int[,] heightmapData; + public float scaleXZ; + public float scaleY; + public float ki; + public float kj; + public float ftex; // factor para la textura + + public POMTerrain() + { + ftex = 1f; + ki = 1; + kj = 1; + } + + public void loadHeightmap(string heightmapPath, float pscaleXZ, float pscaleY, TGCVector3 center) + { + scaleXZ = pscaleXZ; + scaleY = pscaleY; + + Device d3dDevice = GuiController.Instance.D3dDevice; + this.center = center; + + //Dispose de VertexBuffer anterior, si habia + if (vbTerrain != null && !vbTerrain.Disposed) + { + vbTerrain.Dispose(); + } + + //cargar heightmap + heightmapData = loadHeightMap(d3dDevice, heightmapPath); + float width = (float)heightmapData.GetLength(0); + float length = (float)heightmapData.GetLength(1); + + //Crear vertexBuffer + totalVertices = 2 * 3 * (heightmapData.GetLength(0) + 1) * (heightmapData.GetLength(1) + 1); + totalVertices *= (int)ki * (int)kj; + vbTerrain = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), totalVertices, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); + + //Cargar vertices + int dataIdx = 0; + CustomVertex.PositionNormalTextured[] data = new CustomVertex.PositionNormalTextured[totalVertices]; + + center.X = center.X * scaleXZ - (width / 2) * scaleXZ; + center.Y = center.Y * scaleY; + center.Z = center.Z * scaleXZ - (length / 2) * scaleXZ; + + for (int i = 0; i < width - 1; i++) + { + for (int j = 0; j < length - 1; j++) + { + //Vertices + TGCVector3 v1 = new TGCVector3(center.X + i * scaleXZ, center.Y + heightmapData[i, j] * scaleY, center.Z + j * scaleXZ); + TGCVector3 v2 = new TGCVector3(center.X + i * scaleXZ, center.Y + heightmapData[i, j + 1] * scaleY, center.Z + (j + 1) * scaleXZ); + TGCVector3 v3 = new TGCVector3(center.X + (i + 1) * scaleXZ, center.Y + heightmapData[i + 1, j] * scaleY, center.Z + j * scaleXZ); + TGCVector3 v4 = new TGCVector3(center.X + (i + 1) * scaleXZ, center.Y + heightmapData[i + 1, j + 1] * scaleY, center.Z + (j + 1) * scaleXZ); + + //Coordendas de textura + TGCVector2 t1 = new TGCVector2(ftex * i / width, ftex * j / length); + TGCVector2 t2 = new TGCVector2(ftex * i / width, ftex * (j + 1) / length); + TGCVector2 t3 = new TGCVector2(ftex * (i + 1) / width, ftex * j / length); + TGCVector2 t4 = new TGCVector2(ftex * (i + 1) / width, ftex * (j + 1) / length); + + //Cargar triangulo 1 + TGCVector3 n1 = TGCVector3.Cross(v2 - v1, v3 - v1); + n1.Normalize(); + data[dataIdx] = new CustomVertex.PositionNormalTextured(v1, n1, t1.X, t1.Y); + data[dataIdx + 1] = new CustomVertex.PositionNormalTextured(v2, n1, t2.X, t2.Y); + data[dataIdx + 2] = new CustomVertex.PositionNormalTextured(v4, n1, t4.X, t4.Y); + + //Cargar triangulo 2 + TGCVector3 n2 = TGCVector3.Cross(v4 - v1, v3 - v1); + n2.Normalize(); + data[dataIdx + 3] = new CustomVertex.PositionNormalTextured(v1, n2, t1.X, t1.Y); + data[dataIdx + 4] = new CustomVertex.PositionNormalTextured(v4, n2, t4.X, t4.Y); + data[dataIdx + 5] = new CustomVertex.PositionNormalTextured(v3, n2, t3.X, t3.Y); + + dataIdx += 6; + } + } + vbTerrain.SetData(data, 0, LockFlags.None); + } + + /// + /// Carga la textura del terreno + /// + public void loadTexture(string path) + { + //Dispose textura anterior, si habia + if (terrainTexture != null && !terrainTexture.Disposed) + { + terrainTexture.Dispose(); + } + + Device d3dDevice = GuiController.Instance.D3dDevice; + + //Rotar e invertir textura + Bitmap b = (Bitmap)Bitmap.FromFile(path); + b.RotateFlip(RotateFlipType.Rotate90FlipX); + terrainTexture = Texture.FromBitmap(d3dDevice, b, Usage.None, Pool.Managed); + } + + /// + /// Carga los valores del Heightmap en una matriz + /// + private int[,] loadHeightMap(Device d3dDevice, string path) + { + Bitmap bitmap = (Bitmap)Bitmap.FromFile(path); + int width = bitmap.Size.Width; + int height = bitmap.Size.Height; + int[,] heightmap = new int[width, height]; + for (int i = 0; i < width; i++) + { + for (int j = 0; j < height; j++) + { + //(j, i) invertido para primero barrer filas y despues columnas + Color pixel = bitmap.GetPixel(j, i); + float intensity = pixel.R * 0.299f + pixel.G * 0.587f + pixel.B * 0.114f; + heightmap[i, j] = (int)intensity; + } + } + + bitmap.Dispose(); + return heightmap; + } + + public void executeRender(Effect effect) + { + Device device = GuiController.Instance.D3dDevice; + GuiController.Instance.Shaders.setShaderMatrixIdentity(effect); + + //Render terrain + effect.SetValue("texDiffuseMap", terrainTexture); + + device.VertexFormat = CustomVertex.PositionNormalTextured.Format; + device.SetStreamSource(0, vbTerrain, 0); + + int numPasses = effect.Begin(0); + for (int n = 0; n < numPasses; n++) + { + effect.BeginPass(n); + device.DrawPrimitives(PrimitiveType.TriangleList, 0, totalVertices / 3); + effect.EndPass(); + } + effect.End(); + } + + public float CalcularAltura(float x, float z) + { + float largo = scaleXZ * 64; + float pos_i = 64f * (0.5f + x / largo); + float pos_j = 64f * (0.5f + z / largo); + + int pi = (int)pos_i; + float fracc_i = pos_i - pi; + int pj = (int)pos_j; + float fracc_j = pos_j - pj; + + if (pi < 0) + pi = 0; + else + if (pi > 63) + pi = 63; + + if (pj < 0) + pj = 0; + else + if (pj > 63) + pj = 63; + + int pi1 = pi + 1; + int pj1 = pj + 1; + if (pi1 > 63) + pi1 = 63; + if (pj1 > 63) + pj1 = 63; + + // 2x2 percent closest filtering usual: + float H0 = heightmapData[pi, pj] * scaleY; + float H1 = heightmapData[pi1, pj] * scaleY; + float H2 = heightmapData[pi, pj1] * scaleY; + float H3 = heightmapData[pi1, pj1] * scaleY; + float H = (H0 * (1 - fracc_i) + H1 * fracc_i) * (1 - fracc_j) + + (H2 * (1 - fracc_i) + H3 * fracc_i) * fracc_j; + return H; + } + + public void dispose() + { + if (vbTerrain != null) + { + vbTerrain.Dispose(); + } + if (terrainTexture != null) + { + terrainTexture.Dispose(); + } + } + } + + public class POMTerrainSample : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + private Effect effect; + private Texture g_pBaseTexture; + private Texture g_pHeightmap; + private POMTerrain terrain; + private TGCVector2 pos = new TGCVector2(0, 0); + private float dir_an = 0; + private float kvel = 1.0f; + + private float time; + + public POMTerrainSample(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) + : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-POMTerrain"; + Description = "POM Terrain"; + } + + public override void Init() + { + time = 0f; + Device d3dDevice = GuiController.Instance.D3dDevice; + GuiController.Instance.CustomRenderEnabled = true; + MyMediaDir = MediaDir + "WorkshopShaders\\"; + MyShaderDir = ShadersDir + "WorkshopShaders\\"; + + g_pBaseTexture = TextureLoader.FromFile(d3dDevice, MyMediaDir + "Piso\\Textures\\rocks.jpg"); + g_pHeightmap = TextureLoader.FromFile(d3dDevice, MyMediaDir + "Piso\\Textures\\rocks_NM_height.tga"); + + //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); + } + effect.Technique = "ParallaxOcclusion"; + effect.SetValue("aux_Tex", g_pBaseTexture); + effect.SetValue("height_map", g_pHeightmap); + effect.SetValue("phong_lighting", true); + effect.SetValue("k_alpha", 0.75f); + + Modifiers.addVertex3f("LightDir", new TGCVector3(-1, -1, -1), new TGCVector3(1, 1, 1), new TGCVector3(0, -1, 0)); + Modifiers.addFloat("minSample", 1f, 10f, 10f); + Modifiers.addFloat("maxSample", 11f, 50f, 50f); + Modifiers.addFloat("HeightMapScale", 0.001f, 0.5f, 0.1f); + + // ------------------------------------------------------------ + // Creo el Heightmap para el terreno: + terrain = new POMTerrain(); + terrain.ftex = 250f; + terrain.loadHeightmap(MediaDir + "WorkshopShaders\\Heighmaps\\" + "Heightmap3.jpg", 100f, 2.25f, new TGCVector3(0, 0, 0)); + terrain.loadTexture(MediaDir + "WorkshopShaders\\Heighmaps\\" + "TerrainTexture3.jpg"); + + GuiController.Instance.FpsCamera.Enable = true; + GuiController.Instance.FpsCamera.setCamera(new TGCVector3(-350, 1000, -1100), new TGCVector3(0, 0, 0)); + GuiController.Instance.RotCamera.Enable = false; + } + + public override void Update() + { + PreUpdate(); + + GuiController.Instance.FpsCamera.Enable = false; + // Actualizo la direccion + if (GuiController.Instance.D3dInput.keyDown(Microsoft.DirectX.DirectInput.Key.A)) + { + dir_an += 1f * ElapsedTime; + } + if (GuiController.Instance.D3dInput.keyDown(Microsoft.DirectX.DirectInput.Key.D)) + { + dir_an -= 1f * ElapsedTime; + } + + // calculo la velocidad + TGCVector2 vel = new TGCVector2((float)Math.Sin(dir_an), (float)Math.Cos(dir_an)); + // actualizo la posicion + pos += vel * kvel * ElapsedTime; + + // actualizo los parametros de la camara + float dH = 1.0f; // altura del personaje + float H = terrain.CalcularAltura(pos.X, pos.Y); + TGCVector2 pos_s = pos + vel * 2; + TGCVector3 lookFrom = new TGCVector3(pos.X, H + dH, pos.Y); + TGCVector3 lookAt = new TGCVector3(pos_s.X, H, pos_s.Y); + GuiController.Instance.D3dDevice.Transform.View = TGCMatrix.LookAtLH(lookFrom, lookAt, new TGCVector3(0, 1, 0)); + effect.SetValue("fvEyePosition", TgcParserUtils.TGCVector3ToFloat3Array(lookFrom)); + } + + public override void Render() + { + Device device = GuiController.Instance.D3dDevice; + Control panel3d = GuiController.Instance.Panel3d; + float aspectRatio = (float)panel3d.Width / (float)panel3d.Height; + time += ElapsedTime; + + TGCVector3 lightDir = (TGCVector3)Modifiers["LightDir"]; + effect.SetValue("g_LightDir", TgcParserUtils.TGCVector3ToFloat3Array(lightDir)); + effect.SetValue("min_cant_samples", (float)Modifiers["minSample"]); + effect.SetValue("max_cant_samples", (float)Modifiers["maxSample"]); + effect.SetValue("fHeightMapScale", (float)Modifiers["HeightMapScale"]); + //effect.SetValue("fvEyePosition", TgcParserUtils.TGCVector3ToFloat3Array(GuiController.Instance.FpsCamera.getPosition())); + effect.SetValue("time", time); + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + device.BeginScene(); + + //Renderizar terreno con POM + effect.Technique = "ParallaxOcclusion"; + terrain.executeRender(effect); + device.EndScene(); + } + + public override void Dispose() + { + effect.Dispose(); + g_pBaseTexture.Dispose(); + g_pHeightmap.Dispose(); + terrain.dispose(); + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/PlanarShadows.cs b/TGC.Examples/WorkshopShaders/PlanarShadows.cs new file mode 100644 index 00000000..3ef90b99 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/PlanarShadows.cs @@ -0,0 +1,174 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Drawing; +using TGC.Core.Direct3D; +using TGC.Core.Geometry; +using TGC.Core.Mathematica; +using TGC.Core.SceneLoader; +using TGC.Core.Shaders; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Camara; +using TGC.Examples.Example; + +namespace Examples.WorkshopShaders +{ + public class PlanarShadows : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + private TgcScene scene, scene2; + private TGCBox box; + private Effect effect; + private TgcMesh avion; + + // Shadow map + private TGCVector3 g_LightPos; // posicion de la luz actual (la que estoy analizando) + + private float near_plane = 2f; + private float far_plane = 1500f; + + private TGCVector3 dir_avion; + private float time; + + public PlanarShadows(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) + : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-PlanarShadows"; + Description = "Planar Shadows"; + } + + public override void Init() + { + MyMediaDir = MediaDir + "WorkshopShaders\\"; + MyShaderDir = ShadersDir + "WorkshopShaders\\"; + + //Crear loader + TgcSceneLoader loader = new TgcSceneLoader(); + + // ------------------------------------------------------------ + //Cargar la escena + scene = loader.loadSceneFromFile(MyMediaDir + "shadowTest\\ShadowTest-TgcScene.xml"); + + scene2 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\AvionCaza\\AvionCaza-TgcScene.xml"); + avion = scene2.Meshes[0]; + + avion.Scale = new TGCVector3(0.1f, 0.1f, 0.1f); + avion.Position = new TGCVector3(100f, 100f, 0f); + avion.AutoTransform = false; + dir_avion = new TGCVector3(0, 0, 1); + + Camara = new TgcRotationalCamera(new TGCVector3(0, 20, 125), 50, 0.15f, 50f, Input); + + //Cargar Shader personalizado + effect = TgcShaders.loadEffect(ShadersDir + "WorkshopShaders\\PlanarShadows.fx"); + + // le asigno el efecto a las mallas + foreach (TgcMesh T in scene.Meshes) + { + T.Scale = new TGCVector3(1f, 1f, 1f); + T.Effect = effect; + } + avion.Effect = effect; + + box = new TGCBox(); + box.Color = Color.Yellow; + + //GuiController.Instance.RotCamera.targetObject(scene.Meshes[0].BoundingBox); + float K = 300; + Modifiers.addVertex3f("LightLookFrom", new TGCVector3(-K, -K, -K), new TGCVector3(K, K, K), new TGCVector3(80, 120, 0)); + } + + public override void Update() + { + PreUpdate(); + } + + public override void Render() + { + Device d3dDevice = D3DDevice.Instance.Device; + + time += ElapsedTime; + // animo la pos del avion + float alfa = -time * Geometry.DegreeToRadian(115.0f); + avion.Position = new TGCVector3(80f * (float)Math.Cos(alfa), 20 - 20 * (float)Math.Sin(alfa), 80f * (float)Math.Sin(alfa)); + dir_avion = new TGCVector3(-(float)Math.Sin(alfa), 0, (float)Math.Cos(alfa)); + avion.Transform = CalcularMatriz(avion.Position, avion.Scale, dir_avion); + g_LightPos = (TGCVector3)Modifiers["LightLookFrom"]; + + d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + + // dibujo la escena pp dicha + d3dDevice.BeginScene(); + d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); + + // piso + scene.Meshes[0].Technique = "RenderScene"; + scene.Meshes[0].Render(); + + // dibujo las sombra del avion sobre el piso + effect.SetValue("matViewProj", d3dDevice.Transform.View * d3dDevice.Transform.Projection); + effect.SetValue("g_vLightPos", new TGCVector4(g_LightPos.X, g_LightPos.Y, g_LightPos.Z, 1)); + d3dDevice.RenderState.ZBufferEnable = false; + avion.Technique = "RenderShadows"; + avion.Render(); + d3dDevice.RenderState.ZBufferEnable = true; + + // avion + avion.Technique = "RenderScene"; + avion.Render(); + + // dibujo la luz + box.setPositionSize(g_LightPos, new TGCVector3(5, 5, 5)); + box.updateValues(); + box.Render(); + + PostRender(); + } + + // helper + public TGCMatrix CalcularMatriz(TGCVector3 Pos, TGCVector3 Scale, TGCVector3 Dir) + { + TGCVector3 VUP = new TGCVector3(0, 1, 0); + + TGCMatrix matWorld = TGCMatrix.Scaling(Scale); + // determino la orientacion + TGCVector3 U = TGCVector3.Cross(VUP, Dir); + U.Normalize(); + TGCVector3 V = TGCVector3.Cross(Dir, U); + 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; + } + + public override void Dispose() + { + effect.Dispose(); + scene.disposeAll(); + scene2.disposeAll(); + } + } +} \ No newline at end of file diff --git a/TGC.Examples/WorkshopShaders/Transformers.cs b/TGC.Examples/WorkshopShaders/Transformers.cs new file mode 100644 index 00000000..7e2a7d26 --- /dev/null +++ b/TGC.Examples/WorkshopShaders/Transformers.cs @@ -0,0 +1,368 @@ +using Microsoft.DirectX.Direct3D; +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using TGC.Core.Mathematica; +using TGC.Core.UserControls; +using TGC.Core.UserControls.Modifier; +using TGC.Examples.Example; +using TgcViewer.Utils.Gui; + +namespace Examples.WorkshopShaders +{ + // menu item + public class menu_item : GUIItem + { + public TGCVector3 pos_imagen = new TGCVector3(500, 60, 0); + + public menu_item(DXGui gui, String s, String imagen, int id, int x, int y, int dx = 0, int dy = 0, bool penabled = true) : + base(gui, s, x, y, dx, dy, id) + { + disabled = !penabled; + seleccionable = true; + cargar_textura(imagen); + font = gui.font_medium; + } + + // custom draw del menu item + public override void Render(DXGui gui) + { + bool sel = gui.sel == nro_item ? true : false; + + gui.DrawLine(rc.Left, rc.Bottom, rc.Left + 30, rc.Top, 5, Color.FromArgb(81, 100, 100)); + gui.DrawLine(rc.Left + 30, rc.Top, rc.Right, rc.Top, 5, Color.FromArgb(81, 100, 100)); + + if (sel) + { + // boton seleccionado: lleno el interior + TGCVector2[] p = new TGCVector2[20]; + p[0].X = rc.Left; + p[0].Y = rc.Bottom; + p[1].X = rc.Left + 30; + p[1].Y = rc.Top; + p[2].X = rc.Right; + p[2].Y = rc.Top; + p[3].X = rc.Right; + p[3].Y = rc.Bottom; + p[4].X = rc.Left; + p[4].Y = rc.Bottom; + p[5] = p[0]; + gui.DrawGradientPoly(p, 6, Color.White, Color.FromArgb(35, 56, 68)); + + // solo si esta seleccionado (hightlighted) muestro la imagen en un lugar fijo + if (textura != null) + gui.sprite.Draw(textura, Rectangle.Empty, TGCVector3.Empty, pos_imagen, + Color.FromArgb(gui.alpha, 255, 255, 255)); + } + // Texto del boton + Rectangle rc2 = new Rectangle(rc.Left + 40, rc.Top + 3, rc.Width, rc.Height - 3); + font.DrawText(gui.sprite, text, rc2, DrawTextFormat.VerticalCenter | DrawTextFormat.Left, Color.WhiteSmoke); + } + } + + // menu item secundario + public class menu_item2 : GUIItem + { + public menu_item2(DXGui gui, String s, String imagen, int id, int x, int y, int dx = 0, int dy = 0, bool penabled = true) : + base(gui, s, x, y, dx, dy, id) + { + disabled = !penabled; + seleccionable = true; + cargar_textura(imagen); + font = gui.font_medium; + } + + // custom draw del menu item + public override void Render(DXGui gui) + { + bool sel = gui.sel == nro_item ? true : false; + + float rx = rc.Height / 2; + float ry = rc.Height / 2; + float x0 = rc.Left + rx; + float y0 = rc.Top + ry; + + if (sel) + { + rx += 12; + ry += 12; + x0 -= 6; + y0 -= 6; + } + + TGCVector2[] p = new TGCVector2[20]; + p[0].X = rc.Left + 50; + p[0].Y = rc.Bottom - 15; + p[1].X = rc.Left + 50; + p[1].Y = rc.Top + 15; + p[2].X = rc.Right; + p[2].Y = rc.Top + 15; + p[3].X = rc.Right; + p[3].Y = rc.Bottom - 15; + p[4].X = rc.Left + 50; + p[4].Y = rc.Bottom - 15; + p[5] = p[0]; + + if (sel) + { + gui.DrawGradientPoly(p, 6, Color.White, Color.FromArgb(35, 56, 68)); + } + else + { + gui.DrawSolidPoly(p, 6, Color.FromArgb(42, 71, 90), false); + gui.DrawPoly(p, 6, 1, Color.FromArgb(50, 75, 240)); + } + + TGCVector2[] Q = new TGCVector2[7]; + for (int i = 0; i < 6; ++i) + { + Q[i].X = (float)(x0 + rx * Math.Cos(2 * Math.PI / 6 * i)); + Q[i].Y = (float)(y0 + ry * Math.Sin(2 * Math.PI / 6 * i)); + } + Q[6] = Q[0]; + + gui.DrawSolidPoly(Q, 7, c_fondo, false); + + if (sel) + // boton seleccionado: lleno el interior + gui.DrawPoly(Q, 7, 4, DXGui.c_buttom_selected); + else + gui.DrawPoly(Q, 7, 2, Color.FromArgb(61, 96, 100)); + + if (textura != null) + { + gui.sprite.Draw(textura, Rectangle.Empty, TGCVector3.Empty, + new TGCVector3(x0 - image_width / 2, y0 - image_height / 2, 0), + Color.FromArgb(gui.alpha, 255, 255, 255)); + } + + // Texto del boton + Rectangle rc2 = new Rectangle(rc.Left + 90, rc.Top + 3, rc.Width, rc.Height - 3); + font.DrawText(gui.sprite, text, rc2, DrawTextFormat.VerticalCenter | DrawTextFormat.Left, + sel ? Color.Black : Color.WhiteSmoke); + } + } + + // static text + public class static_text : GUIItem + { + public static_text(DXGui gui, String s, int x, int y, int dx = 0, int dy = 0) : + base(gui, s, x, y, dx, dy, -1) + { + disabled = false; + seleccionable = false; + } + + // custom draw + public override void Render(DXGui gui) + { + gui.font.DrawText(gui.sprite, text, rc, DrawTextFormat.Left, Color.WhiteSmoke); + gui.DrawLine(rc.Left, rc.Bottom, rc.Right, rc.Bottom, 6, Color.FromArgb(131, 108, 34)); + gui.DrawLine(rc.Left, rc.Bottom - 2, rc.Right, rc.Bottom - 2, 2, Color.FromArgb(255, 240, 134)); + } + } + + public class Transformers : TGCExampleViewer + { + private string MyMediaDir; + private string MyShaderDir; + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool PeekMessage(ref MSG lpMsg, Int32 hwnd, Int32 wMsgFilterMin, Int32 wMsgFilterMax, PeekMessageOption wRemoveMsg); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool TranslateMessage(ref MSG lpMsg); + + [DllImport("user32.dll", SetLastError = true)] + private static extern Int32 DispatchMessage(ref MSG lpMsg); + + public const Int32 WM_QUIT = 0x12; + + // Defines + public const int IDOK = 0; + + public const int IDCANCEL = 1; + public const int ID_SCOUT = 100; + public const int ID_HUNTER = 101; + public const int ID_COMMANDER = 102; + public const int ID_WARRIOR = 103; + public int dialog_sel = 0; + + public struct POINTAPI + { + public Int32 x; + public Int32 y; + } + + public struct MSG + { + public Int32 hwmd; + public Int32 message; + public Int32 wParam; + public Int32 lParam; + public Int32 time; + public POINTAPI pt; + } + + public enum PeekMessageOption + { + PM_NOREMOVE = 0, + PM_REMOVE + } + + // gui + private DXGui gui = new DXGui(); + + public Transformers(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) + : base(mediaDir, shadersDir, userVars, modifiers) + { + Category = "Shaders"; + Name = "Workshop-Transformers"; + Description = "Gui Demo"; + } + + public override void Init() + { + GuiController.Instance.CustomRenderEnabled = true; + Cursor.Hide(); + + Device d3dDevice = GuiController.Instance.D3dDevice; + MyMediaDir = MediaDir + "WorkshopShaders\\"; + MyShaderDir = ShadersDir + "WorkshopShaders\\"; + + // levanto el GUI + gui.Create(); + + // menu principal + gui.InitDialog(false, false); + int W = GuiController.Instance.Panel3d.Width; + int H = GuiController.Instance.Panel3d.Height; + int x0 = 70; + int y0 = 10; + int dy = 30; + int dy2 = dy; + int dx = 250; + GUIItem item = gui.InsertImage("transformers//custom_char.png", x0, y0); + item.image_centrada = false; + y0 += dy; + gui.InsertItem(new static_text(gui, "SCOUT", x0, y0, 400, 25)); + y0 += 45; + item = gui.InsertImage("transformers//scout.png", x0 + dx, y0); + item.image_centrada = false; + gui.InsertItem(new menu_item(gui, "SCOUT 1", "transformers//scout1.png", ID_SCOUT, x0, y0, dx, dy)); + y0 += dy + 5; + gui.InsertItem(new menu_item(gui, "SCOUT 2", "transformers//scout2.png", ID_SCOUT, x0, y0, dx, dy)); + y0 += 2 * dy; + + gui.InsertItem(new static_text(gui, "HUNTER", x0, y0, 400, 25)); + y0 += 45; + item = gui.InsertImage("transformers//hunter.png", x0 + dx, y0); + item.image_centrada = false; + menu_item hunter1 = (menu_item)gui.InsertItem(new menu_item(gui, "HUNTER 1", "transformers//hunter1.png", ID_HUNTER, x0, y0, dx, dy)); + hunter1.pos_imagen.Y = y0; + + y0 += 2 * dy; + + gui.InsertItem(new static_text(gui, "COMMANDER", x0, y0, 400, 25)); + y0 += 45; + item = gui.InsertImage("transformers//commander.png", x0 + dx, y0); + item.image_centrada = false; + menu_item commander1 = (menu_item)gui.InsertItem(new menu_item(gui, "COMMANDER 1", "transformers//commander1.png", ID_COMMANDER, x0, y0, dx, 25)); + commander1.pos_imagen.Y = y0; + y0 += 2 * dy; + + gui.InsertItem(new static_text(gui, "WARRIOR", x0, y0, 400, 25)); + y0 += 45; + item = gui.InsertImage("transformers//warrior.png", x0 + dx, y0); + item.image_centrada = false; + menu_item warrior1 = (menu_item)gui.InsertItem(new menu_item(gui, "WARRIOR 1", "transformers//warrior1.png", ID_WARRIOR, x0, y0, dx, 30)); + warrior1.pos_imagen.Y = y0; + + dialog_sel = 0; + } + + public void Configurar() + { + gui.InitDialog(false, false); + int W = GuiController.Instance.Panel3d.Width; + int H = GuiController.Instance.Panel3d.Height; + int x0 = 50; + int y0 = 50; + int dy = H - 100; + int dx = 320; + dialog_sel = 1; + + gui.InsertItem(new static_text(gui, "WARRIOR", x0, y0, 400, 25)); + y0 += 45; + gui.InsertItem(new menu_item2(gui, "WARRIOR 1", "transformers//w1.png", ID_WARRIOR, x0, y0, dx, 70)); + y0 += 75; + gui.InsertItem(new menu_item2(gui, "WARRIOR 2", "transformers//w2.png", ID_WARRIOR, x0, y0, dx, 70)); + y0 += 75; + gui.InsertItem(new menu_item2(gui, "WARRIOR 3", "transformers//w3.png", ID_WARRIOR, x0, y0, dx, 70)); + y0 += 75; + gui.InsertItem(new menu_item2(gui, "WARRIOR 4", "transformers//w4.png", ID_WARRIOR, x0, y0, dx, 70)); + y0 += 95; + gui_circle_button button = gui.InsertCircleButton(0, "SELECT", "ok.png", x0 + 70, y0, 40); + button.texto_derecha = true; + button = gui.InsertCircleButton(1, "BACK", "cancel.png", x0 + 300, y0, 40); + button.texto_derecha = true; + } + + public override void Update() + { + PreUpdate(); + } + + public override void Render() + { + Device device = GuiController.Instance.D3dDevice; + device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.FromArgb(35, 56, 68), 1.0f, 0); + gui_render(ElapsedTime); + } + + public void gui_render(float elapsedTime) + { + // ------------------------------------------------ + GuiMessage msg = gui.Update(elapsedTime); + // proceso el msg + switch (msg.message) + { + case MessageType.WM_COMMAND: + switch (msg.id) + { + case IDOK: + case IDCANCEL: + // Resultados OK, y CANCEL del ultimo messagebox + gui.EndDialog(); + + if (dialog_sel == 1) + { + // Estaba en el dialogo de configurar, paso al dialogo principal + dialog_sel = 0; + } + break; + + case ID_SCOUT: + // Abro un nuevo dialogo + Configurar(); + break; + + default: + break; + } + break; + + default: + break; + } + gui.Render(); + } + + public override void Dispose() + { + gui.Dispose(); + Cursor.Show(); + } + } +} \ No newline at end of file