elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Security Series.XSS. [Cross Site Scripting]


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de códigos C# (Compartan aquí sus códigos)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 2 [3] Ir Abajo Respuesta Imprimir
Autor Tema: Librería de códigos C# (Compartan aquí sus códigos)  (Leído 33,858 veces)
z3nth10n


Desconectado Desconectado

Mensajes: 1.583


"Jack of all trades, master of none." - Zenthion


Ver Perfil WWW
Re: Librería de códigos C# (Compartan aquí sus códigos)
« Respuesta #20 en: 22 Octubre 2018, 19:16 pm »

ThreadedDebug: Una utilidad que funciona junto NamedThread & ThreadMarker mostrándote información del Thread actual al debuggear en Unity3D

Código
  1. using GTAMapper.Extensions.Threading;
  2. using System;
  3. using UnityEngine;
  4.  
  5. namespace GTAMapper.Utils.Debugging
  6. {
  7.    public static class ThreadedDebug
  8.    {
  9.        private static double TimeRunning
  10.        {
  11.            get
  12.            {
  13.                return (DateTime.Now - System.Diagnostics.Process.GetCurrentProcess().StartTime).TotalSeconds;
  14.            }
  15.        }
  16.  
  17.        public static void Log(object obj, bool jumpBack = true)
  18.        {
  19.            Debug.Log($"[{ThreadMarker.Name} | {TimeRunning.ToString("F2")}] " + obj.ToString());
  20.        }
  21.  
  22.        public static void LogFormat(string str, params object[] objs)
  23.        {
  24.            LogFormat($"[{ThreadMarker.Name} | {TimeRunning.ToString("F2")}] " + str, true, objs);
  25.        }
  26.  
  27.        public static void LogFormat(string str, bool jumpBack = true, params object[] objs)
  28.        {
  29.            Debug.LogFormat($"[{ThreadMarker.Name} | {TimeRunning.ToString("F2")}] " + str, objs);
  30.        }
  31.  
  32.        public static void LogWarning(object obj, bool jumpBack = true)
  33.        {
  34.            Debug.LogWarning($"[{ThreadMarker.Name} | {TimeRunning.ToString("F2")}] " + obj.ToString());
  35.        }
  36.  
  37.        public static void LogWarningFormat(string str, params object[] objs)
  38.        {
  39.            LogWarningFormat($"[{ThreadMarker.Name} | {TimeRunning.ToString("F2")}] " + str, true, objs);
  40.        }
  41.  
  42.        public static void LogWarningFormat(string str, bool jumpBack = true, params object[] objs)
  43.        {
  44.            Debug.LogWarningFormat($"[{ThreadMarker.Name} | {TimeRunning.ToString("F2")}] " + str, objs);
  45.        }
  46.  
  47.        public static void LogError(object obj, bool jumpBack = true)
  48.        {
  49.            Debug.LogError($"[{ThreadMarker.Name} | {TimeRunning.ToString("F2")}] " + obj.ToString());
  50.        }
  51.  
  52.        public static void LogErrorFormat(string str, params object[] objs)
  53.        {
  54.            LogErrorFormat($"[{ThreadMarker.Name} | {TimeRunning.ToString("F2")}] " + str, true, objs);
  55.        }
  56.  
  57.        public static void LogErrorFormat(string str, bool jumpBack = true, params object[] objs)
  58.        {
  59.            Debug.LogErrorFormat($"[{ThreadMarker.Name} | {TimeRunning.ToString("F2")}] " + str, objs);
  60.        }
  61.  
  62.        public static void LogException(System.Exception ex, bool jumpBack = true)
  63.        {
  64.            Debug.LogException(ex);
  65.        }
  66.    }
  67. }

Básicamente, se usa igual que Debug.LogXX de Unity (https://docs.unity3d.com/ScriptReference/Debug.html) pero este a diferencia, te muesta el momento en el que se ha llamado, y desde el Thread que lo ha hecho.

Ejemplo:



PD: En el ejemplo, vemos dos Count, simplemente, estaba probando que el ConcurrentQueuedCoroutines funcionaba bien, viendo como ConcurrentQueued almacena los datos en todos los contextos usando la instrucción lock(...) internamente.


« Última modificación: 22 Octubre 2018, 19:35 pm por z3nth10n » En línea


Interesados hablad por Discord.
z3nth10n


Desconectado Desconectado

Mensajes: 1.583


"Jack of all trades, master of none." - Zenthion


Ver Perfil WWW
Re: Librería de códigos C# (Compartan aquí sus códigos)
« Respuesta #21 en: 22 Octubre 2018, 19:33 pm »

SendMessageContext: Una implementación Thread-Safe de SendMessage

Básicamente, el puñetero de Unity no te deja llamar la función SendMessage desde otro hilo, así que gracias a esta implementación que estuve probando, resolví el problema, para luego darme cuenta de que usaba (blocking) instrucciones en el main thread (dentro de una coroutina gracias a esta utilidad (https://assetstore.unity.com/packages/tools/thread-ninja-multithread-coroutine-15717) es facil/visual cambiar de contexto) :xD (Sí, así somos los programadores cuando tenemos sueño, implementamos cosas que luego ni usaremos)

La utilidad en cuestión: https://forum.unity.com/threads/sendmessage-argumentexception-error.73134/

Mi implementación:

Código
  1. using System.Collections.Concurrent;
  2. using UnityEngine;
  3.  
  4. namespace GTAMapper.Extensions.Threading
  5. {
  6.    public class SendMessageHelper : MonoBehaviour
  7.    {
  8.        private static ConcurrentQueue<SendMessageContext> QueuedMessages = new ConcurrentQueue<SendMessageContext>();
  9.  
  10.        public static void RegisterSendMessage(SendMessageContext context)
  11.        {
  12.            QueuedMessages.Enqueue(context);
  13.        }
  14.  
  15.        private void Update()
  16.        {
  17.            if (QueuedMessages.Count > 0)
  18.            {
  19.                SendMessageContext context = null;
  20.  
  21.                if (!QueuedMessages.TryDequeue(out context))
  22.                    return;
  23.  
  24.                context.Target.SendMessage(context.MethodName, context.Value, context.Options);
  25.            }
  26.        }
  27.    }
  28. }

Nota: No olvidéis añadir esto al inspector de cualquier gameobject donde se quiera usar (con añadir uno solo bastaría)

Código
  1. using UnityEngine;
  2.  
  3. namespace GTAMapper.Extensions.Threading
  4. {
  5.    public class SendMessageContext
  6.    {
  7.        public MonoBehaviour Target;
  8.        public string MethodName;
  9.        public object Value;
  10.        public SendMessageOptions Options = SendMessageOptions.RequireReceiver;
  11.  
  12.        public SendMessageContext(MonoBehaviour target, string methodName, object value, SendMessageOptions options)
  13.        {
  14.            this.Target = target;
  15.            this.MethodName = methodName;
  16.            this.Value = value;
  17.            this.Options = options;
  18.        }
  19.    }
  20. }

Algo que en el topic de arriba no está ;D

Código
  1. using UnityEngine;
  2.  
  3. namespace GTAMapper.Extensions.Threading
  4. {
  5.    public static class SendMessageExtensions
  6.    {
  7.        public static SendMessageContext SendSafeMessage(this MonoBehaviour monoBehaviour, string methodName, object value = null, SendMessageOptions sendMessageOptions = default(SendMessageOptions))
  8.        {
  9.            return new SendMessageContext(monoBehaviour, methodName, value, sendMessageOptions);
  10.        }
  11.    }
  12. }

Con esta extensión lo que se consigue es simplificar su uso, básicamente, desde un MonoBehaviour cualquiera dentro del metodo Start() (https://docs.unity3d.com/ScriptReference/MonoBehaviour.html) haciendo esto:

Código
  1. this.SendSafeMessage("pepito")

Y luego (desde el mismo MonoBehaviour):

Código
  1. public void pepito() {
  2.    // Moar code que seguirá ejecutándose en el mismo hilo desde el que se llamo "SendSafeMessage"
  3. }

Un saludo.
PD: Aquí termina el flood de snippets, staff no preocuparse, llevo muchos días picando código, y he querido compartir post a post mis utilidades :xD
PD2: Ale ya puedo borrar todo lo que no uso. Que no es poco. ;-) ;-)


« Última modificación: 22 Octubre 2018, 20:03 pm por z3nth10n » En línea


Interesados hablad por Discord.
z3nth10n


Desconectado Desconectado

Mensajes: 1.583


"Jack of all trades, master of none." - Zenthion


Ver Perfil WWW
Re: Librería de códigos C# (Compartan aquí sus códigos)
« Respuesta #22 en: 23 Octubre 2018, 18:31 pm »

Simplificar una lista de puntos para obtener las esquinas (dicho de otra forma, obtener la minima cantidad de puntos que puedan definir dicha forma)

Esto ya lo respondí en Stackoverflow: https://stackoverflow.com/a/52952874/3286975 (Pero lo traduciré)

Citar
Después de horas de investigación he encontrado una librería Simplify.NET que internamente ejecuta el algoritmo de Ramer–Douglas–Peucker.

También, os puede interesar el algoritmo de Bresenham, con este algoritmo podéis dibujar una linea a partir de dos puntos.

Con este algoritmo, se podría comprobar si la tolerancia del primer algoritmo es muy alta (comprobando los puntos generados y los que ya tenías antes de simplificar, haciendo una función que te devuelva un porcentaje de similitud). Por suerte, la implementación de Simplify.NET es rápida (unos 25.000 ticks de Stopwatch), llamandose unas 10 veces solo llevaría unos ~30 ms.

Finalmente, es interesante mencionar el algoritmo Concave Hull y Convex Hull (y sus respectivas implementaciones en Unity3D).

Lo que he obtenido con esta implementación:





Nota:
  • Los puntos azules son los puntos iterados.
  • Los puntos verdes son los puntos simplificados.

Y mi implementación: https://dotnetfiddle.net/aPOhPi

Es muy importante decir que los puntos deben de estar ordenados de tal forma que estén conectados. Si la forma es concava (como se puede ver en la segunda foto) quizás necesites una implementación que itere pixel a pixel dentro de la pared de la figura.

Aquí podéis ver una implementación gracias a Bunny83.

Un saludo.
« Última modificación: 23 Octubre 2018, 18:35 pm por z3nth10n » En línea


Interesados hablad por Discord.
z3nth10n


Desconectado Desconectado

Mensajes: 1.583


"Jack of all trades, master of none." - Zenthion


Ver Perfil WWW
Re: Librería de códigos C# (Compartan aquí sus códigos)
« Respuesta #23 en: 14 Noviembre 2018, 22:03 pm »

Dibujar curvas a partir de Perlin Noise (de forma acotada)

Por acotada me refiero, a que puedes establecer el centro del ruido y su amplitud.

Enlace: https://github.com/z3nth10n/Unity-Curve-Drawer

Imagen:



Un saludo.
« Última modificación: 27 Noviembre 2018, 19:08 pm por z3nth10n » En línea


Interesados hablad por Discord.
z3nth10n


Desconectado Desconectado

Mensajes: 1.583


"Jack of all trades, master of none." - Zenthion


Ver Perfil WWW
Re: Librería de códigos C# (Compartan aquí sus códigos)
« Respuesta #24 en: 12 Diciembre 2018, 02:47 am »

Rasterizar un triangulo cualquiera

Hoy estoy felis, ya que he conseguido rasterizar un triangulo. Y me diréis pues muy bien no? Vale, os explico.

Rasterizar es esto. Es decir, pintar por pantalla los pixeles que conforman un poligono cualquiera. Bueno sí... Pero lo que no os he dicho que un poligono cualquiera se puede triangular, es decir, como en el post anterior al igual que con Ramer-Douglas-Pecker puedes conseguir el minimo de puntos que definen un poligono cualquiera, con triangulación consigues algo parecido, ya que si lo pensamos, un triangulo es la minima expresión de poligono, es decir, el poligono con menos vertices y que de sumas de ellos podemos definir los demas.

Si queréis conseguir una buena triangulación os recomiendo LibTessDotNet. Funciona muy bien.

Esto es muy potente ya que puedes mostrar por pantalla (aunque para esto ya está DirectX y OpenGL, internamente, esto que comento es un trabajo que la GPU hace muy bien ya que se trata de repetir), hacer procesos más complejos (que es por lo que fundamental lo necesito yo) o bien hacer librerías de pago de rasterización para Unity :xD.

Así que aquí os dejo mi buena *****:

Código
  1. using System;
  2. using UnityEngine;
  3.  
  4. namespace UnityEngine.Utilities.Drawing
  5. {
  6.    // Uncomment this if you don't a an own implementation
  7.    /*public struct Point
  8.     {
  9.         public int x;
  10.         public int y;
  11.  
  12.         public Point(int x, int y)
  13.         {
  14.             this.x = 0;
  15.             this.y = 0;
  16.         }
  17.     }*/
  18.  
  19.    public static class TriangleUtils
  20.    {
  21.        public static void Rasterize(Point pt1, Point pt2, Point pt3, Action<int, int> action, bool debug = false)
  22.        {
  23.            /*
  24.                  // https://www.geeksforgeeks.org/check-whether-triangle-valid-not-sides-given/
  25.                  a + b > c
  26.                  a + c > b
  27.                  b + c > a
  28.              */
  29.  
  30.            if (!CheckIfValidTriangle(pt1, pt2, pt3, debug))
  31.                return;
  32.  
  33.            if (TriangleArea(pt1, pt2, pt3) <= 1)
  34.            {
  35.                Point center = GetTriangleCenter(pt1, pt2, pt3);
  36.                action?.Invoke(center.x, center.y);
  37.  
  38.                return;
  39.            }
  40.  
  41.            Point tmp;
  42.  
  43.            if (pt2.x < pt1.x)
  44.            {
  45.                tmp = pt1;
  46.                pt1 = pt2;
  47.                pt2 = tmp;
  48.            }
  49.  
  50.            if (pt3.x < pt2.x)
  51.            {
  52.                tmp = pt2;
  53.                pt2 = pt3;
  54.                pt3 = tmp;
  55.  
  56.                if (pt2.x < pt1.x)
  57.                {
  58.                    tmp = pt1;
  59.                    pt1 = pt2;
  60.                    pt2 = tmp;
  61.                }
  62.            }
  63.  
  64.            var baseFunc = CreateFunc(pt1, pt3);
  65.            var line1Func = pt1.x == pt2.x ? (x => pt2.y) : CreateFunc(pt1, pt2);
  66.  
  67.            for (var x = pt1.x; x < pt2.x; ++x)
  68.            {
  69.                int maxY;
  70.                int minY = GetRange(line1Func(x), baseFunc(x), out maxY);
  71.  
  72.                for (int y = minY; y <= maxY; ++y)
  73.                    action?.Invoke(x, y);
  74.            }
  75.  
  76.            var line2Func = pt2.x == pt3.x ? (x => pt2.y) : CreateFunc(pt2, pt3);
  77.  
  78.            for (var x = pt2.x; x <= pt3.x; ++x)
  79.            {
  80.                int maxY;
  81.                int minY = GetRange(line2Func(x), baseFunc(x), out maxY);
  82.  
  83.                for (int y = minY; y <= maxY; ++y)
  84.                    action?.Invoke(x, y);
  85.            }
  86.        }
  87.  
  88.        private static int GetRange(float y1, float y2, out int maxY)
  89.        {
  90.            if (y1 < y2)
  91.            {
  92.                maxY = Mathf.FloorToInt(y2);
  93.                return Mathf.CeilToInt(y1);
  94.            }
  95.  
  96.            maxY = Mathf.FloorToInt(y1);
  97.            return Mathf.CeilToInt(y2);
  98.        }
  99.  
  100.        private static Func<int, float> CreateFunc(Point pt1, Point pt2)
  101.        {
  102.            var y0 = pt1.y;
  103.  
  104.            if (y0 == pt2.y)
  105.                return x => y0;
  106.  
  107.            float m = (float)(pt2.y - y0) / (pt2.x - pt1.x);
  108.  
  109.            return x => m * (x - pt1.x) + y0;
  110.        }
  111.  
  112.        public static void RasterizeStandard(Point p1, Point p2, Point p3, Action<int, int> action, bool debug = false)
  113.        {
  114.            // Thanks to: https://www.davrous.com/2013/06/21/tutorial-part-4-learning-how-to-write-a-3d-software-engine-in-c-ts-or-js-rasterization-z-buffering/
  115.  
  116.            if (!CheckIfValidTriangle(p1, p2, p3, debug))
  117.                return;
  118.  
  119.            // Sorting the points in order to always have this order on screen p1, p2 & p3
  120.            // with p1 always up (thus having the y the lowest possible to be near the top screen)
  121.            // then p2 between p1 & p3
  122.            if (p1.y > p2.y)
  123.            {
  124.                var temp = p2;
  125.                p2 = p1;
  126.                p1 = temp;
  127.            }
  128.  
  129.            if (p2.y > p3.y)
  130.            {
  131.                var temp = p2;
  132.                p2 = p3;
  133.                p3 = temp;
  134.            }
  135.  
  136.            if (p1.y > p2.y)
  137.            {
  138.                var temp = p2;
  139.                p2 = p1;
  140.                p1 = temp;
  141.            }
  142.  
  143.            // inverse slopes
  144.            float dP1P2, dP1P3;
  145.  
  146.            // http://en.wikipedia.org/wiki/Slope
  147.            // Computing inverse slopes
  148.            if (p2.y - p1.y > 0)
  149.                dP1P2 = (p2.x - p1.x) / (p2.y - p1.y);
  150.            else
  151.                dP1P2 = 0;
  152.  
  153.            if (p3.y - p1.y > 0)
  154.                dP1P3 = (p3.x - p1.x) / (p3.y - p1.y);
  155.            else
  156.                dP1P3 = 0;
  157.  
  158.            // First case where triangles are like that:
  159.            // P1
  160.            // -
  161.            // --
  162.            // - -
  163.            // -  -
  164.            // -   - P2
  165.            // -  -
  166.            // - -
  167.            // -
  168.            // P3
  169.            if (dP1P2 > dP1P3)
  170.            {
  171.                for (var y = p1.y; y <= p3.y; y++)
  172.                {
  173.                    if (y < p2.y)
  174.                        ProcessScanLine(y, p1, p3, p1, p2, action);
  175.                    else
  176.                        ProcessScanLine(y, p1, p3, p2, p3, action);
  177.                }
  178.            }
  179.            // First case where triangles are like that:
  180.            //       P1
  181.            //        -
  182.            //       --
  183.            //      - -
  184.            //     -  -
  185.            // P2 -   -
  186.            //     -  -
  187.            //      - -
  188.            //        -
  189.            //       P3
  190.            else
  191.            {
  192.                for (var y = p1.y; y <= p3.y; y++)
  193.                {
  194.                    if (y < p2.y)
  195.                        ProcessScanLine(y, p1, p2, p1, p3, action);
  196.                    else
  197.                        ProcessScanLine(y, p2, p3, p1, p3, action);
  198.                }
  199.            }
  200.        }
  201.  
  202.        // drawing line between 2 points from left to right
  203.        // papb -> pcpd
  204.        // pa, pb, pc, pd must then be sorted before
  205.        private static void ProcessScanLine(int y, Point pa, Point pb, Point pc, Point pd, Action<int, int> action)
  206.        {
  207.            // Thanks to current y, we can compute the gradient to compute others values like
  208.            // the starting x (sx) and ending x (ex) to draw between
  209.            // if pa.y == pb.y or pc.y == pd.y, gradient is forced to 1
  210.            var gradient1 = pa.y != pb.y ? (y - pa.y) / (pb.y - pa.y) : 1;
  211.            var gradient2 = pc.y != pd.y ? (y - pc.y) / (pd.y - pc.y) : 1;
  212.  
  213.            int sx = (int)Mathf.Lerp(pa.x, pb.x, gradient1);
  214.            int ex = (int)Mathf.Lerp(pc.x, pd.x, gradient2);
  215.  
  216.            // drawing a line from left (sx) to right (ex)
  217.            for (var x = sx; x < ex; x++)
  218.                action?.Invoke(x, y);
  219.        }
  220.  
  221.        public static void RasterizeBarycentric(Point v1, Point v2, Point v3, Action<int, int> action, bool debug = false)
  222.        {
  223.            // Thanks to: http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html#algo3 && https://www.cs.unm.edu/~joel/cs491_VR/src/DrawUtilities.cs
  224.  
  225.            /* checks for a valid triangle */
  226.  
  227.            if (!CheckIfValidTriangle(v1, v2, v3, debug))
  228.                return;
  229.  
  230.            /* get the bounding box of the triangle */
  231.            int maxX = Mathf.Max(v1.x, Mathf.Max(v2.x, v3.x));
  232.            int minX = Mathf.Min(v1.x, Mathf.Min(v2.x, v3.x));
  233.            int maxY = Mathf.Max(v1.y, Mathf.Max(v2.y, v3.y));
  234.            int minY = Mathf.Min(v1.y, Mathf.Min(v2.y, v3.y));
  235.  
  236.            //if (debug)
  237.            //    Debug.Log($"({minX}, {minY}, {maxX}, {maxY})");
  238.  
  239.            /* spanning vectors of edge (v1,v2) and (v1,v3) */
  240.            Point vs1 = new Point(v2.x - v1.x, v2.y - v1.y);
  241.            Point vs2 = new Point(v3.x - v1.x, v3.y - v1.y);
  242.  
  243.            for (int x = minX; x <= maxX; x++)
  244.            {
  245.                for (int y = minY; y <= maxY; y++)
  246.                {
  247.                    Point q = new Point(x - v1.x, y - v1.y);
  248.  
  249.                    float s = Vector2.Dot(q, vs2) / Vector2.Dot(vs1, vs2);
  250.                    float t = Vector2.Dot(vs1, q) / Vector2.Dot(vs1, vs2);
  251.  
  252.                    if ((s >= 0) && (t >= 0) && (s + t <= 1))
  253.                    { /* inside triangle */
  254.                        action?.Invoke(x, y);
  255.                    }
  256.                }
  257.            }
  258.        }
  259.  
  260.        public static void RasterizeBresenham(Point vt1, Point vt2, Point vt3, Action<int, int> action, bool debugException = false)
  261.        {
  262.            // Thanks to: http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html#algo3 && https://www.cs.unm.edu/~joel/cs491_VR/src/DrawUtilities.cs
  263.  
  264.            /* checks for a valid triangle */
  265.  
  266.            if (!CheckIfValidTriangle(vt1, vt2, vt3, debugException))
  267.                return;
  268.  
  269.            string invalidTriangle = $"The given points must form a triangle. {{{vt1}, {vt2}, {vt3}}}";
  270.  
  271.            /* at first sort the three vertices by y-coordinate ascending so v1 is the topmost vertice */
  272.            sortVerticesAscendingByY(ref vt1, ref vt2, ref vt3);
  273.  
  274.            /* here we know that v1.y <= v2.y <= v3.y */
  275.            /* check for trivial case of bottom-flat triangle */
  276.            if (vt2.y == vt3.y)
  277.            {
  278.                if (!fillBottomFlatTriangle(vt1, vt2, vt3, action, debugException))
  279.                {
  280.                    if (debugException)
  281.                        Debug.LogWarning(invalidTriangle);
  282.  
  283.                    return;
  284.                }
  285.            }
  286.            /* check for trivial case of top-flat triangle */
  287.            else if (vt1.y == vt2.y)
  288.            {
  289.                if (!fillTopFlatTriangle(vt1, vt2, vt3, action, debugException))
  290.                {
  291.                    if (debugException)
  292.                        Debug.LogWarning(invalidTriangle);
  293.  
  294.                    return;
  295.                }
  296.            }
  297.            else
  298.            {
  299.                /* general case - split the triangle in a topflat and bottom-flat one */
  300.                Point v4 = new Point((int)(vt1.x + (vt2.y - vt1.y) / (float)(vt3.y - vt1.y) * (vt3.x - vt1.x)), vt2.y);
  301.  
  302.                if (!fillBottomFlatTriangle(vt1, vt2, v4, action, debugException) || !fillTopFlatTriangle(vt2, v4, vt3, action, debugException))
  303.                {
  304.                    if (debugException)
  305.                        Debug.LogWarning(invalidTriangle);
  306.  
  307.                    return;
  308.                }
  309.            }
  310.        }
  311.  
  312.        public static bool CheckIfValidTriangle(Point v1, Point v2, Point v3, bool debug = false)
  313.        {
  314.            /*
  315.                 // https://www.geeksforgeeks.org/check-whether-triangle-valid-not-sides-given/
  316.                 a + b > c
  317.                 a + c > b
  318.                 b + c > a
  319.             */
  320.  
  321.            float a = Vector2.Distance(new Vector2(v1.x, v1.y), new Vector2(v2.x, v2.y)),
  322.                  b = Vector2.Distance(new Vector2(v2.x, v2.y), new Vector2(v3.x, v3.y)),
  323.                  c = Vector2.Distance(new Vector2(v3.x, v3.y), new Vector2(v1.x, v1.y));
  324.  
  325.            if (a + b <= c || a + c <= b || b + c <= a)
  326.            {
  327.                if (debug)
  328.                    Debug.LogWarning($"The given points must form a triangle. {{{v1}, {v2}, {v3}}}");
  329.  
  330.                return false;
  331.            }
  332.  
  333.            return true;
  334.        }
  335.  
  336.        public static bool CheckIfValidTriangle(Point v1, Point v2, Point v3, out float a, out float b, out float c)
  337.        {
  338.            a = Vector2.Distance(new Vector2(v1.x, v1.y), new Vector2(v2.x, v2.y));
  339.            b = Vector2.Distance(new Vector2(v2.x, v2.y), new Vector2(v3.x, v3.y));
  340.            c = Vector2.Distance(new Vector2(v3.x, v3.y), new Vector2(v1.x, v1.y));
  341.  
  342.            if (a + b <= c || a + c <= b || b + c <= a)
  343.            {
  344.                // Debug.LogWarning($"The given points must form a triangle. {{{v1}, {v2}, {v3}}}");
  345.                return false;
  346.            }
  347.  
  348.            return true;
  349.        }
  350.  
  351.        private static bool fillBottomFlatTriangle(Point v1, Point v2, Point v3, Action<int, int> action, bool debugException = false)
  352.        {
  353.            try
  354.            {
  355.                float invslope1 = (v2.x - v1.x) / (v2.y - v1.y);
  356.                float invslope2 = (v3.x - v1.x) / (v3.y - v1.y);
  357.  
  358.                float curx1 = v1.x;
  359.                float curx2 = v1.x;
  360.  
  361.                for (int scanlineY = v1.y; scanlineY <= v2.y; scanlineY++)
  362.                {
  363.                    DrawLine((int)curx1, scanlineY, (int)curx2, scanlineY, action);
  364.  
  365.                    curx1 += invslope1;
  366.                    curx2 += invslope2;
  367.                }
  368.            }
  369.            catch (Exception ex)
  370.            {
  371.                if (debugException)
  372.                    Debug.LogException(ex);
  373.  
  374.                return false;
  375.            }
  376.  
  377.            return true;
  378.        }
  379.  
  380.        private static bool fillTopFlatTriangle(Point v1, Point v2, Point v3, Action<int, int> action, bool debugException = false)
  381.        {
  382.            try
  383.            {
  384.                float invslope1 = (v3.x - v1.x) / (v3.y - v1.y);
  385.                float invslope2 = (v3.x - v2.x) / (v3.y - v2.y);
  386.  
  387.                float curx1 = v3.x;
  388.                float curx2 = v3.x;
  389.  
  390.                for (int scanlineY = v3.y; scanlineY > v1.y; scanlineY--)
  391.                {
  392.                    DrawLine((int)curx1, scanlineY, (int)curx2, scanlineY, action);
  393.                    curx1 -= invslope1;
  394.                    curx2 -= invslope2;
  395.                }
  396.            }
  397.            catch (Exception ex)
  398.            {
  399.                if (debugException)
  400.                    Debug.LogException(ex);
  401.  
  402.                return false;
  403.            }
  404.  
  405.            return true;
  406.        }
  407.  
  408.        private static void sortVerticesAscendingByY(ref Point v0, ref Point v1, ref Point v2)
  409.        {
  410.            if (v2.y < v1.y)
  411.                Swap(ref v1, ref v2);
  412.  
  413.            if (v1.y < v0.y)
  414.                Swap(ref v0, ref v1);
  415.  
  416.            if (v2.y < v1.y)
  417.                Swap(ref v1, ref v2);
  418.        }
  419.  
  420.        private static void Swap<T>(ref T lhs, ref T rhs)
  421.        {
  422.            (lhs, rhs) = (rhs, lhs);
  423.  
  424.            // Impl for versions lower than C# 7
  425.  
  426.            //T temp;
  427.            //temp = lhs;
  428.            //lhs = rhs;
  429.            //rhs = temp;
  430.        }
  431.  
  432.        public static float TriangleArea(Point p1, Point p2, Point p3)
  433.        {
  434.            float a, b, c;
  435.  
  436.            if (!CheckIfValidTriangle(p1, p2, p3, out a, out b, out c))
  437.                return 0;
  438.  
  439.            return TriangleArea(a, b, c);
  440.        }
  441.  
  442.        public static float TriangleArea(float a, float b, float c)
  443.        {
  444.            // Thanks to: http://james-ramsden.com/area-of-a-triangle-in-3d-c-code/
  445.  
  446.            float s = (a + b + c) / 2.0f;
  447.            return Mathf.Sqrt(s * (s - a) * (s - b) * (s - c));
  448.        }
  449.  
  450.        // Bresenham impl: https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
  451.  
  452.        public static void DrawLine(Vector2 p1, Vector2 p2, Action<int, int> action)
  453.        {
  454.            DrawLine((int)p1.x, (int)p1.y, (int)p2.x, (int)p2.y, action);
  455.        }
  456.  
  457.        public static void DrawLine(int x0, int y0, int x1, int y1, Action<int, int> action)
  458.        {
  459.            int sx = 0,
  460.                sy = 0;
  461.  
  462.            int dx = Mathf.Abs(x1 - x0),
  463.                dy = Mathf.Abs(y1 - y0);
  464.  
  465.            if (x0 < x1) { sx = 1; } else { sx = -1; }
  466.            if (y0 < y1) { sy = 1; } else { sy = -1; }
  467.  
  468.            int err = dx - dy,
  469.                e2 = 0;
  470.  
  471.            while (true)
  472.            {
  473.                //colors[P(x0 % width, y0 % height, width, height)] = x0 / width >= 1 || y0 / height >= 1 ? UnityEngine.Color.yellow : c;
  474.                action?.Invoke(x0, y0);
  475.  
  476.                if ((x0 == x1) && (y0 == y1))
  477.                    break;
  478.  
  479.                e2 = 2 * err;
  480.  
  481.                if (e2 > -dy)
  482.                {
  483.                    err = err - dy;
  484.                    x0 = x0 + sx;
  485.                }
  486.                if (e2 < dx)
  487.                {
  488.                    err = err + dx;
  489.                    y0 = y0 + sy;
  490.                }
  491.            }
  492.        }
  493.  
  494.        public static Point GetTriangleCenter(Point p0, Point p1, Point p2)
  495.        {
  496.            // Thanks to: https://stackoverflow.com/questions/524755/finding-center-of-2d-triangle
  497.  
  498.            return new Point(p0.x + p1.x + p2.x / 3, p0.y + p1.y + p2.y / 3);
  499.        }
  500.    }
  501. }

Gist: https://gist.github.com/z3nth10n/7d60f22c7e906f645d53c9622507c23b (dadle una estrellica, no me seais gitanos :laugh: :laugh:)

Vídeo de ejemplo:



Un saludo.
« Última modificación: 12 Diciembre 2018, 04:45 am por z3nth10n » En línea


Interesados hablad por Discord.
Páginas: 1 2 [3] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Para todos los amantes del irc aqui les dejo codigos de Guerra de Irc
Mensajería
KxM 0 3,740 Último mensaje 17 Septiembre 2010, 20:56 pm
por KxM
Librería de Plantillas !! (Compartan aquí sus plantillas)
.NET (C#, VB.NET, ASP)
Eleкtro 5 21,621 Último mensaje 22 Octubre 2014, 13:42 pm
por 1quark1
Códigos
Java
TickTack 4 3,291 Último mensaje 16 Enero 2021, 00:37 am
por TickTack
Usar códigos escape ANSI en C es standard?
Programación C/C++
Lieutenant McFarley 2 3,014 Último mensaje 9 Marzo 2022, 22:19 pm
por MinusFour
Mis códigos A2F para discord no funcionan y no tengo los códigos de seguridad
Hacking
Lotte 0 2,299 Último mensaje 15 Mayo 2022, 17:54 pm
por Lotte
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines